/**
 * ADDED TEXT THAT NEEDS TO BE DELETED
 * This lib contains js functions that alter the client behavior. It uses W3C DOM 1
 * This lib has a the following dependency:
 *          xbDOM.js
 * Copyright:    Copyright (c) 2004
 * Company:      Fujitsu Australia Limited
 * @author       Trevor Plant
 * @version 1.0
 *
 */

function showit()
{
    //get the storage fields
    var hiddenEntities = xbGetElementById("entities")
    var hiddenMedia = xbGetElementById("media")
    var hiddenLoc = xbGetElementById("loc")
    
    
}

/**
 * This function is called to set the state of the checkboxes on the 
 * Advanced Search Screen.
 * If checkbox is All, toggle other entities and enable media & loc
 * if checkbox is Series enable loc and if checkbox item is not checked disable media
 * if checkox is item enable media and id checkbox paper not checked enable loc
 * if checkbox is paper disabe loc
 */
function onClickAdvSearchCheckbox(obj)
{
    var id = obj.id
    var checkbox = xbGetElementById(id)
    
    //get the storage fields
    var hiddenEntities = xbGetElementById("entities")
    var hiddenMedia = xbGetElementById("media")
    var hiddenLoc = xbGetElementById("loc")
    
    //get all the checkboxes
    var chkbxAll = xbGetElementById("ckbAll")
    var chkbxFunction = xbGetElementById("ckbFunction")
    var chkbxGroup = xbGetElementById("ckbGroup")
    var chkbxAgency = xbGetElementById("ckbAgency")
    var chkbxSeries = xbGetElementById("ckbSeries")
    var chkbxItem = xbGetElementById("ckbItem")
    var chkbxPaper = xbGetElementById("ckbpaper")
    var chkbxDigital = xbGetElementById("ckbdigital")
    var chkbxNthMelb = xbGetElementById("ckbnthmelb")
    var chkbxBal = xbGetElementById("ckbbal")
    var chkbxOther = xbGetElementById("ckbother")    
    
    switch(id)
    {
        case "ckbAll":
            if(checkbox.checked)
            {
                doEntities()
                // fitchett - don't check digital by default for go live
                //doMedia(true,true)
                doMedia(true,true,false)
                doLoc(true,true)
                hiddenEntities.value = "ckbAll"
                // fitchett - don't check digital by default for go live
                //hiddenMedia.value = "ckbpaper~ckbdigital"
                hiddenMedia.value = "ckbpaper"
                hiddenLoc.value = "ckbnthmelb~ckbbal~ckbother"
            }
            else
            {
                doEntities()
                doMedia(false,false)
                doLoc(false,false)
                hiddenEntities.value = ""
                hiddenMedia.value = ""
                hiddenLoc.value = ""
            }
            break
      
        case "ckbSeries":
            var chbxItem
             if(checkbox.checked)
            {
                doLoc(true,true)
            }
            else
            {
               chbxItem = xbGetElementById("ckbItem")
               var chkbxDigital = xbGetElementById("ckbdigital")
               var chkbxPaper = xbGetElementById("ckbpaper")

               if(!chbxItem.checked)
               {
                    doLoc(false,false)
               }
               if(!chkbxPaper.checked)
               {
                    doLoc(false,false)
               }
            }
            hiddenEntities.value = getListOfEntities()
            hiddenMedia.value = getListOfMedia()
            hiddenLoc.value = getListOfLoc()
            break
        case "ckbItem":
            if(checkbox.checked)
            {
                // fitchett - don't check digital by default for go live
                //doMedia(true,true)
                doMedia(true,true,false)
                doLoc(true,true)
            }
            else
            {
                doMedia(false,false)
            
                var chbxSeries = xbGetElementById("ckbSeries")

                if(!chbxSeries.checked)
                {

                    doLoc(false,false)
                }
                else
                {

                    doLoc(true,true)
                }
            }
            hiddenEntities.value = getListOfEntities()
            hiddenMedia.value = getListOfMedia()
            hiddenLoc.value = getListOfLoc()
            break
        case "ckbpaper":
            if(checkbox.checked)
            {
                doLoc(true,true)
            }
            else
            {
                var chbxSeries = xbGetElementById("ckbSeries")
                var chbxAll = xbGetElementById("ckbAll")
                var chkbxDigital = xbGetElementById("ckbdigital")
                if (!chbxSeries.checked && !chbxAll.checked)
                {
                    doLoc(false,false)
                }
                if(chkbxDigital.checked)
                {
                    doLoc(false,false)
                }
                if(chkbxSeries.checked)
                {
                    //if series is checked the location should be checked.
                    //regardless of whether content is digital
                    doLoc(true,true)
                }
           }

            hiddenEntities.value = getListOfEntities()
            hiddenMedia.value = getListOfMedia()
            hiddenLoc.value = getListOfLoc()
            break
        
        case "ckbdigital":
            var chkbxDigital = xbGetElementById("ckbdigital")
            var chkbxPaper = xbGetElementById("ckbpaper")
            var chkbxSeries = xbGetElementById("ckbSeries")

            if(chkbxDigital.checked && !chkbxPaper.checked)
            {
                doLoc(false,false)              
            }
            
            break

        default:
           
            hiddenEntities.value = getListOfEntities()
            hiddenMedia.value = getListOfMedia()
            hiddenLoc.value = getListOfLoc()
     }
    
}

/**
 * Function to process Entities checkbox
 * uncheck and disable checkboxes
 */
function doEntities()
{
    var chbxFunct = xbGetElementById("ckbFunction")
    var functHidden = xbGetElementById("ckbFunction_hidden")
    var chbxGroup = xbGetElementById("ckbGroup")
    var groupHidden = xbGetElementById("ckbGroup_hidden")
    var chbxAgency = xbGetElementById("ckbAgency")
    var agencyHidden = xbGetElementById("ckbAgency_hidden")
    var chbxSeries = xbGetElementById("ckbSeries")
    var seriesHidden = xbGetElementById("ckbSeries_hidden")
    var chbxItem = xbGetElementById("ckbItem")
    var itemHidden = xbGetElementById("ckbItem_hidden")
    
    chbxFunct.disabled = !chbxFunct.disabled
    chbxFunct.checked = false
    functHidden.value = null

    chbxGroup.disabled = !chbxGroup.disabled
    chbxGroup.checked = false
    groupHidden.value = null
    
    chbxAgency.disabled = !chbxAgency.disabled
    chbxAgency.checked = false
    agencyHidden.value = null

    chbxSeries.disabled = !chbxSeries.disabled
    if(chbxSeries.checked)
    {
        chbxSeries.checked=false
        seriesHidden.value = null
        if(!chbxItem.checked)
        {
            doLoc(true,true)
        }
    }
    
    chbxItem.disabled = !chbxItem.disabled
    if(chbxItem.checked)
    {
        chbxItem.checked=false
        itemHidden.value = null
        doMedia(true,true)
        doLoc(true,true)
    }
}

/**
 *Function to process media
 *
 */
function doMedia(check, enabled, checkDigital)
{
    if (checkDigital == undefined || checkDigital == null)
    {
      checkDigital = check
    }

    var chbx = xbGetElementById("ckbpaper")
    var hid =  xbGetElementById("ckbpaper_hidden")
    chbx.checked = check
    if(check)
    {
        hid.value=true
    }
    else
    {
         hid.value=null
    }
    chbx.disabled = !enabled    //need to not as js is reversed

    chbx = xbGetElementById("ckbdigital")
    dighid =  xbGetElementById("ckbdigital_hidden")
    chbx.checked = checkDigital
    if(checkDigital)
    {
        dighid.value=true
    }
    else
    {
        dighid.value = null
    }
    chbx.disabled = !enabled    //need to not as js is reversed

}

/**
 *Function to process Location
 *
 */
function doLoc(check, enabled)
{
    var chbx = xbGetElementById("ckbnthmelb")
    var hid = xbGetElementById("ckbnthmelb_hidden")
    chbx.checked = check
    
    if(check)
    {
        hid.value=true
    }
    else
    {
        hid.value = null
    }
    chbx.disabled = !enabled    //need to not as js is reversed

    chbx = xbGetElementById("ckbbal")
    balhid = xbGetElementById("ckbbal_hidden")
    chbx.checked = check
   
    if(check)
    {
        balhid.value=true
    }
    else
    {
         balhid.value = null
    }
    chbx.disabled = !enabled    //need to not as js is reversed

    chbx = xbGetElementById("ckbother")
    otherhid = xbGetElementById("ckbother_hidden")
    chbx.checked = check
    
    if(check)
    {
        hid.value=true
    }
    else
    {
        otherhid.value = null
    }
    chbx.disabled = !enabled    //need to not as js is reversed
}

/**
 * Function to set checkbox state on the Search in a Series screen
 */
function setSisCheckBox(obj)
{
    chbox = xbGetElementById(obj.id.substring(4))
    chboxHidden =  xbGetElementById(obj.id.substring(4)+"_hidden")
    
    //set check
    chbox.checked = !chbox.checked
    //set hidden
    chboxHidden = chbox.checked ? true : null
}

/**
 * Function to call checkbox click behavior from a label 
 * on the advanced search screen
 */
function setCheckBox(obj)
{
    chbox = xbGetElementById(obj.id.substring(4))
    //ignore if chbox is disabled
    if(chbox.disabled)
    {
        return
    }
    //toggle checked
    chbox.checked = !chbox.checked
    onClickAdvSearchCheckbox(chbox)
}

/**
 * will select/deselect all checkboxes, 
 * @param the object of the select all checkbox.  Can be passed in as: this
 */
function doSelectAll(selectAllObj)
{
    var tags = document.getElementsByTagName('input');
    var checkbox = null;
  
    try
    {	
      if (tags != null)
      {
        for (var k = 0; k < tags.length; k++)
        {
          if (tags[k].type != null)
          {
            if (tags[k].type == "checkbox" && !tags[k].disabled)
            { 
              if (tags[k].name != selectAllObj.name)
              {		
                if (!tags[k].checked && selectAllObj.checked)
                {
                  tags[k].checked = true;
                  //highlight the corresponding row
                  onActionMultiselectCheckboxClick(tags[k]);
                }
    						else
    						{
                  if (tags[k].checked && !selectAllObj.checked)
    							{
                    tags[k].checked = false;
                    //change row to white
    								onActionMultiselectCheckboxClick(tags[k]);								 
    							}
								}  
              }
            }
          }
        }		
      } 		    
    }
    catch(e)
    {
      return;
    }	
}

function getType(str)
{
    var stPos = str.indexOf(">")
    var endPos = str.lastIndexOf("<")
    var inTag = str.substring(stPos+1,endPos)
    return inTag
}
        
function isToBeDisabledType(str)
{
    if (str == "Agency" || str == "Function" || str == "Group"|| str=="Series")
    {
      return true
    }
    else
    {
      return false
    }
}
        
function isToBeDisabledAccess(str)
{
    var ret = true

    if(str != null && str=="OPEN")
    {
      ret=false
    }
    return ret
}
        
function getTextNodeValue(parentNode)
{
    var ret=""     
    
    for ( var i = 0; i < parentNode.childNodes.length; i++)
    {
      
      if (parentNode.childNodes[i].nodeType==3)
      {        
        ret = parentNode.childNodes[i].nodeValue 
       
      }
      else 
      {
        //drill down
        ret = getTextNodeValue(parentNode.childNodes[i])        
      }
      if (!(ret == null || trim(ret) == ""))
      {
        
        break
      }
    }
    
    return ret
}

function switchContextHelp()
{
    var parent = xbGetElementById("contextHelp")
    var otherParent = xbGetElementById("getContextHelp")
    var container = xbGetElementById("helpContainer")

    var img = xbGetElementById("helpImg")

    var browser = navigator.appName
    var style = null
    if (browser.indexOf("Microsoft") >= 0)
    {
      style = parent.style
    }
    else
    {
      style = getClassStyle("contextHelp")
    }
    
    if (style.display == "none")
    {
      //make the container wider
      container.style.width = '140px'
      //show the help content
      parent.style.display = "block"
      otherParent.style.display = "none"
      window.scrollBy(100,0)
      //change the image
      if (img != null)
      {
        img.src = g_virtualRoot + "/custom/images/lessHelp.gif"
      }
    }
    else
    {
      //hide the help content
      container.style.width = '50px'      
      parent.style.display = "none"
      otherParent.style.display = "block"
      window.scrollBy(-100,0)
      //change the image
      if (img != null)
      {
        img.src = g_virtualRoot + "/custom/images/Help.gif"
      }
    } 
}

function switchRadioButton(obj)
{
    var radioBtn = xbGetElementById("rdo_"+obj.id.substring(4))
    radioBtn.checked = true
}

/**
 * Function to get list of entities
 */
function getListOfEntities()
{
    var chkbxAll = xbGetElementById("ckbAll")
    var chkbxFunction = xbGetElementById("ckbFunction")
    var chkbxGroup = xbGetElementById("ckbGroup")
    var chkbxAgency = xbGetElementById("ckbAgency")
    var chkbxSeries = xbGetElementById("ckbSeries")
    var chkbxItem = xbGetElementById("ckbItem")
    
    var list = new Array()
    if(chkbxAll.checked)
    {
        list.push("ckbAll")
    }
    if(chkbxFunction.checked)
    {
        list.push("ckbFunction")
    }
    if(chkbxGroup.checked)
    {
        list.push("ckbGroup")
    }
    if(chkbxAgency.checked)
    {
        list.push("ckbAgency")
    }
    if(chkbxSeries.checked)
    {
        list.push("ckbSeries")
    }
    if(chkbxItem.checked)
    {
        list.push("ckbItem")
    }
    
    //flatten and return
   
    return list.join("~")
    
}

/**
 * Function to list Media
 */
function getListOfMedia()
{
    var chkbxPaper = xbGetElementById("ckbpaper")
    var chkbxDigital = xbGetElementById("ckbdigital")

    var list = new Array()
    if(chkbxPaper.checked)
    {
        list.push("ckbpaper")
    }
    if(chkbxDigital.checked)
    {
        list.push("ckbdigital")
    }
    //flatten and return
    return list.join("~")
}

/**
 * Function to list Location
 */
function getListOfLoc()
{
    var chkbxNthMelb = xbGetElementById("ckbnthmelb")
    var chkbxBal = xbGetElementById("ckbbal")
    var chkbxOther = xbGetElementById("ckbother")    

    var list = new Array()
    if(chkbxNthMelb.checked)
    {
        list.push("ckbnthmelb")
    }
    if(chkbxBal.checked)
    {
        list.push("ckbbal")
    }
    if(chkbxOther.checked)
    {
        list.push("ckbother")
    }
    //flatten and return
    return list.join("~")
}

/**
 * Function to sumbit search request
 * @param searchType name of server function to call
 *
 */
function doSearch(searchType)
{
   postServerEvent("PublicBaseContainer_0","body_search_0","PublicBaseContainer_body_0",searchType)
}

/**
 * Function to call redefine on the server
 * 
 */
function callDoGoBack()
{
   postServerEvent("PublicBaseContainer_0","","PublicBaseContainer_body_0","doGoBack")
}

/**
 * Function on clear event on the screens
 * @param action The action to jump to
 *
 */
function doClear(action)
{
    postServerEvent(null,null,null,"onaction","action",action)
}

/**
 * Function to switch classes to simulate a button press.
 * Called on the onmousedown event.
 */
function changeButtonClass(obj)
{
    var currClass = obj.className
    if (currClass == "buttonStyle")
    {
        obj.className = "buttonUnStyle"
    }
    else
    {
        obj.className = "buttonStyle"
    }            
}

/**
 * Function to display a Series title for the Search in Series screen
 * @param action The action to execute.
 */
function doDisplayTitle(action)
{
    postServerEvent("PublicBaseContainer_0","body_clear_0","PublicBaseContainer_body_0","onaction","fieldList","vprs","action","search_display_title")
}

/**
 * Function to call ordering
 *
 */
function doOrderItems()
{
    postServerEvent("PublicBaseContainer_0","body_clear_0","PublicBaseContainer_body_0","onaction","action","order_entries")
}

function doEmptyInputCheck(srcObj, arg1)
{
     userID = xbGetElementById("userIdText")
     password = xbGetElementById("passwordText")
     EmptyUserIdLabel = xbGetElementById("EmptyUserId")
     EmptyPasswordLabel = xbGetElementById("EmptyPassword")
     EmptyPasswordLabel1 = xbGetElementById("EmptyPassword1")
     invalidAttemptText = xbGetElementById("InvalidAttemptText")      
     invalidAttemptLabel = xbGetElementById("InvalidAttemptLabel") 
     invalidAttemptDiv = xbGetElementById("InvalidAttemptDiv")

     EmptyUserIdLabel.style.display="none"
     EmptyPasswordLabel.style.display="none"
     EmptyPasswordLabel1.style.display="none"
     invalidAttemptLabel.style.display="none"
     invalidAttemptText.style.display="none"

     if (userID.value == "" && password.value == "")
     {
        EmptyPasswordLabel.style.display="block"
        EmptyPasswordLabel1.style.display="block"
        xbSetInnerHTML(EmptyPasswordLabel,"<li>    Please enter your User ID")
        xbSetInnerHTML(EmptyPasswordLabel1,"and Password.")
        userID.focus()
        return
     }
     if (userID.value == "")
     {
        EmptyUserIdLabel.style.display="block"
        xbSetInnerHTML(EmptyUserIdLabel,"<li>    Please enter your User ID.")
        userID.focus();
        return
     }
     if (password.value == "")
     {
        EmptyPasswordLabel.style.display="block"
        xbSetInnerHTML(EmptyPasswordLabel,"<li>    Please enter your Password.")
        password.focus()
        return
     }
     if (userID.value.indexOf("(") != -1)
     {
        EmptyUserIdLabel.style.display="block"
        xbSetInnerHTML(EmptyUserIdLabel,"<li>    User Id must not contain the '(' or ')' characters.") 
        userID.focus()
        return
     } 
     if (userID.value.indexOf(")") != -1)
     {
        EmptyUserIdLabel.style.display="block"
        xbSetInnerHTML(EmptyUserIdLabel,"<li>    User Id must not contain the '(' or ')' characters.") 
        userID.focus()
        return
     } 

     postServerEvent("PublicBaseContainer_0","body_defaultButton_0","PublicBaseContainer_body_0","onClickLogin") 
}

function doEmptyInputCheckForgetPage(srcObj, arg1)
{
     userID = xbGetElementById("forgetPwUserIdText")
     elementId = xbGetElementById("ForgetPwFailedAttemptLabel")

     if (userID.value == "")
     {      
        xbSetInnerHTML(elementId,"<li>    Please enter your User ID.")
        userID.focus()
        return
     }
     if (userID.value.indexOf("(") != -1)
     {
        xbSetInnerHTML(elementId,"<li>    User Id must not contain the '(' or ')' characters.") 
        userID.focus()
        return
     } 
     if (userID.value.indexOf(")") != -1)
     {
        xbSetInnerHTML(elementId,"<li>    User Id must not contain the '(' or ')' characters.") 
        userID.focus()
        return
     } 
     postServerEvent("PublicBaseContainer_0","body_ForgetPwUIDButton_0","PublicBaseContainer_body_0","onClickForgetPwUID")
}
 
function doEmptyInputCheckQuestion(srcObj, arg1)
{
     answerText = xbGetElementById("answerText")
     elementId = xbGetElementById("ForgetPwFailedQuestionLabel")
     
     if (answerText.value == "")
     {      
        xbSetInnerHTML(elementId,"<li>    Please enter your answer to the forgotten password question.")
        return
     }
     postServerEvent("PublicBaseContainer_0","body_ForgetPwChQButton_0","PublicBaseContainer_body_0","onClickForgetPwChQ")
}

function doResetPreCheck(srcObj, arg1)
{
     newPassword = xbGetElementById("newPassword")
     confirmPassword = xbGetElementById("confirmPassword")
     elementId = xbGetElementById("FailedResetLabel")

     if (newPassword.value == "" && confirmPassword.value == "")
     {
        xbSetInnerHTML(elementId,"<li>    Please enter your new password in the above fields.")
        newPassword.focus()
        return
     }
     if (newPassword.value == "")
     {
        xbSetInnerHTML(elementId,"<li>    Please enter a new password in the New Password field.")
        newPassword.focus()
        return
     }
     if (confirmPassword.value == "")
     {
        xbSetInnerHTML(elementId,"<li>    Please enter your new password in the Confirm Password field.")
        confirmPassword.focus()
        return
     }
     if (newPassword.value != confirmPassword.value)
     {
        xbSetInnerHTML(elementId,"<li>    The new and confirmed passwords do not match.")
        newPassword.focus()
        return
     }
     if (newPassword.value.length < 6 || newPassword.value.length > 10)
     {
        xbSetInnerHTML(elementId,"<li>    Password must be between 6 and 10 characters.")
        newPassword.focus()
        return       
     }
     postServerEvent("PublicBaseContainer_0","body_defaultButton_0","PublicBaseContainer_body_0","onClickResetPassword")
} 

/**
 * Creates a virtual form on the HTMLdom reads the passed array of fieldIds and 
 * and creates hidden fields of the name paramName. Then sets the action to the drl 
 * for the destination component. It then calls submit on the virtual form.
 * The array of Params will contain 1 * 4 array of strings in the following structure:
 * [fieldId, type, paramName, defaultVal].
 * where:
 *   fieldId is the id of the field to get the value from
 *   type is the type of field to get, text, textarea, select, radio, check.
 *   paramName is the name of the outgoing param
 *   defaultVal is the val if fieldId or fieldId.value is null
 *
 * So, to pass params not in fields set fieldId to null and set paramName and defaultVal.
 * destComponent is the name of the component to load.
 * origForm is the form object from the caller.
 */
function virtualForm(arrParams, destComponent, origFormName)
{
    //show the search hourglass
    showHourglass()

    //Get hold of virtual dir via the window.location.pathname
    var strPath = window.location.pathname;
    var nIndex1 = strPath.indexOf("/");
    var nIndex2 = strPath.indexOf("/", nIndex1 + 1);
    var strVirtualDir = strPath.substring(nIndex1 + 1, nIndex2);
    
    var destURL = "/component/daPublicBaseContainer"
    
    //build form
    var submitForm = document.createElement("form")
    submitForm.method = "GET"   //so the url appears in the address bar
    submitForm.action = "/" + strVirtualDir + destURL

    var newField = document.createElement("input")
    newField.type = "hidden"
    newField.name = "component"
    newField.value = destComponent
    submitForm.appendChild(newField)
    document.documentElement.appendChild(submitForm)
    
    // loop over the arrParams and translate into fields in the virtual form
    for (var i = 0; i < arrParams.length; i++)
    {
        var entry = arrParams[i]
        var fieldId = entry[0]
        var fieldType = entry[1]
        var paramName = entry[2]
        var defaultVal = entry[3]

        var newField = document.createElement("input")
        newField.type = "hidden"
        newField.name = paramName
        
        if (fieldId == null || fieldId == "")
        {
            //just a pass through params
            newField.value = defaultVal
        }
        else
        {
            //get the value from the field name
            //switch based on type allowed values are text, textarea, radio, check, select
            switch(entry[1])
            {
                case "text":
                    //get the element
                    var obj = xbGetElementById(fieldId)
                    if (obj != null || obj != undefined)
                    {
                        newField.value = obj.value
                    }
                    else
                    {
                        newField.value = defaultVal
                    }
                    break
                case "textarea":
                     //get the element
                    var obj = xbGetElementById(fieldId)
                    if (obj != null || obj != undefined)
                    {
                        newField.value = obj.value
                    }
                    else
                    {
                        newField.value = defaultVal
                    }
                    break
                case "radio":
                    
                    var arrRadio = xbGetElementsByName(fieldId)
                    for (var j = 0; j < arrRadio.length; j++)
                    {
                        var radio = arrRadio[i]
                        if (radio.checked)
                        {
                            newField.value = radio.value
                            break
                        }                    
                    }                    
                    break   
                case "check":
                     //get the element
                    var obj = xbGetElementById(fieldId)
                    if (obj != null || obj != undefined)
                    {
                        if(obj.checked)
                        {
                            newField.value = true
                        }
                    }
                    break
                case "select":
                    
                    var theForm = document.forms[origFormName]
                    var obj = eval("theForm." + fieldId)
                    for(var k = 0; k < obj.length; k++)
                    {
                        if(obj.options[k].selected)
                        {
                            newField.value = obj.options[k].value
                            break
                        }
                    }
                    break
                default:
                    //oops
            }
        }
        submitForm.appendChild(newField)
    }
    //send it away
    submitForm.submit()
}

/**
 * From WDK popupMenu.js
 * /

/**
* Obscuring select element constructor
*
* @param element   Select element
*/
function ObscuringSelectElement(element)
{
   this.selectElement = element;
   this.selectVisibility = element.style.visibility;
}

/**
 * Hide any select elements in the passed window
 *
 * @param wnd Window object
 */
function hideObscuringSelects(wnd)
{
   if (typeof(wnd.disabledSelectCallCount) == "undefined")
   {
      wnd.disabledSelectCallCount = 0;
      wnd.disabledSelectCtrls = [];
   }

   if (wnd.disabledSelectCallCount == 0 && wnd.document.forms.length > 0)
   {
      // remember state of all select controls, and hide them
      for (j = 0; j < wnd.document.forms.length; j++)
      {
         var form = wnd.document.forms[j];
         for (i = 0; i < form.elements.length; i++)
         {
            var element = form.elements[i];
            if (element.type.indexOf("select") == 0)
            {
               wnd.disabledSelectCtrls[wnd.disabledSelectCtrls.length] = new ObscuringSelectElement(element);
               element.style.visibility = "hidden";
            }
         }
      }
   }

   // increment call count
   wnd.disabledSelectCallCount++;
}
/**
 * Show any select elements that were previously hidden, in the passed window
 *
 * @param wnd Window object
 */
function showObscuringSelects(wnd)
{
   if (typeof(wnd.disabledSelectCallCount) != "undefined")
   {
      wnd.disabledSelectCallCount--;
      if (wnd.disabledSelectCallCount == 0)
      {
         // restore the state of any previously hidden select elements
         for (i = 0; i < wnd.disabledSelectCtrls.length; i++)
         {
            var element = wnd.disabledSelectCtrls[i];
            element.selectElement.style.visibility = element.selectVisibility;
         }
         wnd.disabledSelectCtrls = [];
      }
   }
}
/* End From WDK popupMenu.js*/

/**
 * Open new browser window for help
 */
function showHelp(url)
{
    
    var newWin = open(url, "PROVHelp", 
            "dependent=yes,resizable=yes,location=yes,toolbar=yes,scrollbars=yes,menubar=yes,status=yes,width=800px,height=600px")

}

function getSelectSingleValue(fieldName)
{
    var sortTypeObj = xbGetElementById(fieldName)
    var ret = ""
    var opts
    if (sortTypeObj.options == undefined || sortTypeObj.options == null)
    {
        opts = sortTypeObj
    }
    else
    {
        opts = sortTypeObj.options
    }
    var L = opts.length

    for (var i = 0; i < L; i++)
    {
        if (opts[i].selected)
        {
            ret = opts[i].value
            break
        }
    }

    return ret
}
    
function isFieldEmpty(fieldName)
{
    var ret = true
    var field = xbGetElementById(fieldName)

    if (field.value.length > 0 )
    {
        ret = false
    }
    return ret
}
    
function unwelcomeChars(fieldName, errorLabel)
{
    var err = xbGetElementById(errorLabel)

    err.style.display = "none"
    xbSetInnerHTML(err, "")
    var ret = false
    var field = xbGetElementById(fieldName)
    var testStr = field.value

    var regex = /([>]+)|([<]+)|([\?]+)|([\\]+)|([\,]+)|([']+)|(["]+)|([@]+)|([!]+)|([`]+)|([\{]+)|([\[]+)|([\(]+)|([\)]+)/
    var p = testStr.search(regex)
    if (p > -1)
    {
        //double asterisk
        ret = true
        var tmp = err.innerHTML
        xbSetInnerHTML(err, tmp + "<ul><li>Please change your search so that none of the <br>following characters are contained in the search string:<br> &gt;, &lt;, ?, comma, single quote, double quote, back quote,<br>back slash, @, !, {, [, (, ).</li></ul>")
        err.style.display = "block"

    }

    // check stemless wildcards, but only if the previous check did not detect an error
    if (ret != true)
    {
      var stemless = false
      var words = testStr.split(" ")
      for (var i=0; i < words.length; i++) {
         if (words[i] == "*")
         {
           stemless = true
         }
      }
      if (stemless == true)
      {
        ret = true
        var tmp = err.innerHTML
        xbSetInnerHTML(err, tmp + "<ul><li>A wildcard search must contain at least one character aside from the <br>wildcard.</li></ul>")
        err.style.display = "block"
      }
    }

    return ret
}
    
function getTextFieldValue(fieldName)
{
    var ret = ""
    var field = xbGetElementById(fieldName)
    ret = field.value
    return ret    
}
    
function resolveCheckBoxValues(nameArray, delim)
{

    var ret = ""
    var tmpArray = new Array()

    //collect all the checked boxes
    for (var i = 0; i < nameArray.length; i++)
    {
       var cb = xbGetElementById(nameArray[i])
       if (cb.checked)
       {
           tmpArray.push(nameArray[i].substring(3))
       }
    }
    ret = tmpArray.join(delim)
    return ret
}
    
/**
 * Creates window to submit array of url requests to download VEOs
 */
function downloadVeoWindow()
{
  //Get hold of virtual dir via the window.location.pathname
  var strPath = window.location.pathname;
  var nIndex1 = strPath.indexOf("/");
  var nIndex2 = strPath.indexOf("/", nIndex1 + 1);
  var strVirtualDir = strPath.substring(nIndex1 + 1, nIndex2);
  var destURL = "/veo-download"

  var obj = xbGetElementsByName("checkDownload")

  if (obj.length > 0)
  {
    for (var i = 0; i < obj.length; i++)
    {
      if (obj[i].checked == true)
      {
        var objId = obj[i].value
        var path = "/" + strVirtualDir + destURL + "?objectId=" + objId
        
        var win = open(path, 'DownloadVeo' + i, 'width=1,height=1')
        win.document.close
      }
    }
  }
  else
  {
    if (obj.checked == true)
    {
      var objId = obj.value
      var path = "/" + strVirtualDir + destURL + "?objectId=" + objId
      var win = open(path, 'DownloadVeo' + i, 'width=1,height=1')
      win.document.close
    }
  }
}

/**
 * Creates a window to open url requests to download Item attachment
 */
function downloadItemWindow(url)
{
  showHourglass()
  if (url != null)
  {
    
    //build virtual form to submit request to url
    var submitForm = document.createElement("form")
    submitForm.method = "GET"
    submitForm.action = url.substring(0, url.indexOf("?"))
    document.documentElement.appendChild(submitForm)
    
    var variables = url.substring(url.indexOf("?") + 1)
    var parArr = variables.split("&")
    for (var i = 0; i < parArr.length; i++)
    {
      var par = parArr[i].split("=")
      var input = document.createElement("input")
      input.type = "hidden"
      input.name = par[0]
      input.value = par[1]
      submitForm.appendChild(input)
    }
    
    
    submitForm.submit()
  }
}

/**
 * Download VEO checkbox control
 */
function onDownloadCheckboxClick(checkbox)
{
  var obj = xbGetElementsByName("checkDownload")
  
  var select = false
  if (obj.length > 0)
  {
    for (var i = 0; i < obj.length; i++)
    {
	  if (obj[i].checked == true)
      {
        select = true
      }
    }
  }
  else
  {
    if (obj.checked == true)
    {
      select = true
    }
  }
  
  var but = xbGetElementById("downloadentries")
  
  if (select == true)
  {
    but.disabled = false
  }
  else
  {
    but.disabled = true
  }
}

/**
 * Download VEO select all checkbox control
 */
function doDownloadSelectAll(selectAllObj)
{
  var tags = document.getElementsByTagName('input');
  var checkbox = null;

  try
  {	
    if (tags != null)
    {
      for (var k = 0; k < tags.length; k++)
      {
        if (tags[k].type != null)
        {
          if (tags[k].type == "checkbox" && !tags[k].disabled)
          { 
            if (tags[k].name != selectAllObj.name)
            {		
              if (!tags[k].checked && selectAllObj.checked)
              {
                tags[k].checked = true;
                //highlight the corresponding row
                onDownloadCheckboxClick(tags[k]);
              }
              else
              {
                if (tags[k].checked && !selectAllObj.checked)
                {
                  tags[k].checked = false;
                  //change row to white
                  onDownloadCheckboxClick(tags[k]);								 
                }
              }  
            }	                 
          }
        }
      }		
    } 		    
  }
  catch(e)
  {
    return;
  }	
}

function goBack()
{
  history.back();
}

function showHourglass()
{
  var show = xbGetElementById("hourglass")
  show.style.display = "block"
  var hide = xbGetElementById("search")
  hide.style.display="none"    
}

function getClassStyle(name)
{
	var El = xbGetElementById(name)
  var style = El.style

  if (style.display == "")
  {
    // it works in ie, firefox & opera... 
    var currentStyle = El.currentStyle
    if (currentStyle)
    {
      style.display = currentStyle["display"]
    }
    else if (window.getComputedStyle)
    {
      var windowComputerStyle = window.getComputedStyle(El, "")
      style.display = windowComputerStyle.getPropertyValue("display");
    }
  }
  return style
}

/**
 * Disable invalid function will disable the checkboxes for the items users are
 * not permitted to cancel (not having the order status of 'On Order'
 * @param takes the id of the table you wish to scan
 */
function disableInvalidOrderStatus(id) 
{
  // obtain a reference to the desired table
  // if no such table exists, abort
  var checkbox = null;
  var orderablevalue = null;
  // the permitted cell values
  var arOrderable = new Array(1);
  arOrderable[0] = "ON ORDER";
  
 var table = xbGetElementById(id);
 
  if (! table) { return; }
  
  // find all the &lt;tr&gt; elements... 
  var trs = table.getElementsByTagName("tr");

  // ... and iterate through them
  for (var i = 0; i < trs.length; i++)
  {
    // get all the cells in this row...
    var tds = trs[i].getElementsByTagName("td");
    // and iterate through them...
    for (var j = 0; j < tds.length; j++)
    {
      var mytd = tds[j];

      //grab the contents of the td
      if (checkbox == null)
      {
        checkbox = getCheckbox(mytd);
      }

      if (orderablevalue == null)
      {
        orderablevalue = getSpanValue(mytd, "orderStatus");  		
      }
    }

    //disable the checkbox if the entitytypevalue is other than ON ORDER
    if ((orderablevalue != arOrderable[0] && checkbox != null)
    || (orderablevalue == null && checkbox != null))
    {	
      checkbox.disabled = true;
    }		

    //reset the checkbox and span values before the next row is processed   
    checkbox = null;
    orderablevalue = null;
  }
}

/**
 * Disable invalid function will disable the checkboxes for the items users are
 * not permitted to order
 * @param takes the id of the table you wish to scan
 */
function disableInvalid(id) 
{
  // obtain a reference to the desired table
  // if no such table exists, abort
  
  var checkbox = null;
  var entitytypevalue = null;
  var locationvalue = null;
  var permissionvalue = null;
  // the permitted cell values
  var arOrderable = new Array(1);
  arOrderable[0] = "UNIT";
  arOrderable[1] = "ITEM";
  arOrderable[2] = "TRUE";		
  arOrderable[3] = "ONLINE";

  var table = xbGetElementById(id);

  if (! table) { return; }
  
  // find all the &lt;tr&gt; elements... 
  var trs = table.getElementsByTagName("tr");
  
  // ... and iterate through them
  for (var i = 0; i < trs.length; i++)
  {
    // get all the cells in this row...
    var tds = trs[i].getElementsByTagName("td");
    // and iterate through them...
     
    for (var j = 0; j < tds.length; j++)
    {
      var mytd = tds[j];

      //grab the contents of the td
      if (checkbox == null)
      {
        checkbox = getCheckbox(mytd);
        
      }

      if (entitytypevalue == null)
      {
        entitytypevalue = getSpanValue(mytd, "entityType");
        permissionvalue = getSpanValue(mytd, "orderStatus");
      }

      if (locationvalue == null)
      {
        locationvalue = getSpanValue(mytd, "location");
       
      }
    }
    
    //disable the checkbox if the entitytypevalue is other than UNIT or ITEM or if the permission level is other than TRUE
    if ((entitytypevalue != arOrderable[0] && entitytypevalue != arOrderable[1] && entitytypevalue != null && checkbox != null)
    || (permissionvalue != arOrderable[2] && checkbox != null)
    || (entitytypevalue == null && checkbox != null)
    || (permissionvalue == null && checkbox != null)
    || (locationvalue == arOrderable[3] && checkbox != null))
    {	
      checkbox.disabled = true;
    }		

    //reset the checkbox and span values before the next row is processed   
    checkbox = null;
    entitytypevalue = null;
    locationvalue = null;
    permissionvalue = null;
  }
}

/**
 * Disable record veo - will disable the checkboxes for the record veos users are
 * not permitted to download
 * @param takes the id of the table you wish to scan
 */
function downloadControl(id) 
{
  // obtain a reference to the desired table
  // if no such table exists, abort
  var checkbox = null;
  var permissionvalue = null;

  var table = document.getElementById(id);
  if (! table) { return; }

  // find all the &lt;tr&gt; elements... 
  var trs = table.getElementsByTagName("tr");

  // ... and iterate through them
  for (var i = 0; i < trs.length; i++)
  {
    // get all the cells in this row...
    var tds = trs[i].getElementsByTagName("td");
    // and iterate through them...
    for (var j = 0; j < tds.length; j++)
    {
      var mytd = tds[j];
      //grab the contents of the td
      if (checkbox == null)
      {
        checkbox = getCheckbox(mytd);
      }

      if (permissionvalue == null)
      {
        permissionvalue = getSpanValue(mytd, "downloadStatus");
        
      }
    }
    
    //disable the checkbox if the permission level is other than TRUE
    if ((permissionvalue == null && checkbox != null)
     || (permissionvalue != "TRUE" && checkbox != null))
    {	
      checkbox.disabled = true;
    }
    		

    //reset the checkbox and span values before the next row is processed   
    checkbox = null;
    permissionvalue = null;
  }
}

/**
 * getCheckbox will find the checkbox in the current row
 * @param obj takes the table row object
 */
function getCheckbox(obj)
{
  var ins = obj.getElementsByTagName('input');
  var checkbox = null;

  try
  {
    if (ins != null)
    {
      for (var k = 0; k < ins.length; k++)
      {
        if (ins[k].type != null)
        {
          type = ins[k].type;

          if (type == "checkbox")
          {
            checkbox = ins[k];
            //break out of the loop
            k = ins.length;
          }
        }
      }		 	
    }
  }
	catch(e)
	{
    checkbox = null;
  }
  return checkbox; 
}

/**
 * getSpanValue will find the value in the named span 
 * @param obj takes the table row object
 * @param spanName the name of span containing the value
 */
function getSpanValue(obj, spanName)
{	 
  var spanContent = null;
  var spanValue = null;
  var sps = obj.getElementsByTagName('span');
  var q = null;

  try
  {
    if (sps != null)
    {
      
      for (var m = 0; m < sps.length; m++)
      {
        
        if (sps[m].id != null)
        {	
          
          if (sps[m].id == spanName)
          {
            spanContent = sps[m].innerHTML.toUpperCase();
            
            if (spanContent.length > 0)
            {
              //can't be sure that Documentum included the formatting span so..
              q = spanContent.indexOf("CLASS");
              if (q == -1)
              {
                spanValue = spanContent;
              } 
              else
              {
                //get rid of the formatting tag
                                
                stripSpan = spanContent.split(">");
                //spanValue = stripSpan[stripSpan.length - 2].split("<");
                spanValue = getTextNodeValue(sps[m]).toUpperCase();  
                
                /*if (spanValue.length > 0)
                {
                  spanValue = spanValue[0];
                }*/
              }	
              q = null; 
            }
            //break out of the loop
            m = sps.length;
          }				
        } 
      }
    }	
  }	
  catch(e)
  {
    spanValue = null;
  }
  return spanValue; 
}

/**
 * used to reload a component
 * portions of the path need to be passed in, 
 * due to the behaviour of the login screen.  The login screen mauls the dir structure
 */
function reloadComponent(dirPath, component, componentLabel, breadcrumbPath)
{
  path = dirPath + "?component=" + component + "&componentLabel=" + componentLabel + "&breadcrumbPath=" + breadcrumbPath ;
  window.location.href = path;
}

/**
 * A function to trim spaces from a string
 * as per 
 */
function trim(value) 
{
   var temp = value;
   var obj = /^(\s*)([\W\w]*)(\b\s*$)|(\s*)/;
   if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
  
   var obj = / +/g;
   temp = temp.replace(obj, " ");
   if (temp == " ") { temp = ""; }
   
   return temp;
}
