/**
* Script contains all functions related to html objects (window, document, radio, select...) 
*/

/**
 * Creates a class called DomUtils.
 */
var DomUtils = {
    version : "1.0.0"
};


/**
 * Calculates the window document height
 *
 * @return window document height value.
 */
DomUtils.calculateWindowHeight = function() {

    var pageHeight;

    if( window.innerHeight && window.scrollMaxY ) { // Firefox
        pageHeight = window.innerHeight + window.scrollMaxY;
    } else if( document.body.scrollHeight > document.body.offsetHeight )  { // all but Explorer Mac
        pageHeight = document.body.scrollHeight;
    } else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
        pageHeight = document.body.offsetHeight + document.body.offsetTop;
    }

    return pageHeight;
}

/**
 * Calculates the window document width
 *
 * @return window document width value.
 */
DomUtils.calculateWindowWidth = function() {

      var pageWidth;

    if( window.innerHeight && window.scrollMaxY ) { // Firefox
        pageWidth = window.innerWidth + window.scrollMaxX;
    } else if( document.body.scrollHeight > document.body.offsetHeight )  { // all but Explorer Mac
        pageWidth = document.body.scrollWidth;
    } else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
        pageWidth = document.body.offsetWidth + document.body.offsetLeft;
    }

    return pageWidth;
}


/**
 * Retrieves the value of the currently checked radio button on a given form
 * 
 * @param formname that contains the radio to get value from
 * @param radioname to query
 * @return value of the currently checked radio button
 */
DomUtils.getRadioValue = function(formname, radioname) {
    var radiobuttons = document[formname][radioname];

      if (radiobuttons.length == undefined) {
        if (radiobuttons.checked) {
              return radiobuttons.value
        }
      } else  {
        for (var i=0;i<radiobuttons.length;i++){
            if (radiobuttons[i].checked) {
                  return radiobuttons[i].value;
            }
        }
    }
}

/**
 * Checks if a radio option is selected or not.
 * 
 * @param formname that contains the radio to get value from
 * @param radioname to query
 * @return true if an option is selected, false otherwise.
 */
DomUtils.isRadioSelected = function(formname, radioname) {
    
    var value = DomUtils.getRadioValue(formname, radioname);
    if (value ===  undefined) {
        return false
    } else {
        return true;
    }

}

/**
 * Retrieves the value of a radio button on a given form
 *
 * @param formObj that contains the radio to get value from
 * @param radioname to query
 * @return value of the currently checked radio button
 */
DomUtils.getRadioValueByForm = function(formObj, radioname) {
    var radiobuttons = formObj.elements[radioname];

      if (radiobuttons.length == undefined) {
        if (radiobuttons.checked) {
              return radiobuttons.value
        }
      } else  {
        for (var i=0;i<radiobuttons.length;i++){
            if (radiobuttons[i].checked) {
                  return radiobuttons[i].value;
            }
        }
    }
}


/**
 * Sets the value of a radio button on a given form
 *
 * @param formname that contains the radio to set a value on
 * @param radioname to query
 * @param radiovalue to set
 */
DomUtils.setRadioValue = function(formname, radioname, radiovalue) {
  var radiobuttons = document[formname][radioname];

  if (radiobuttons) {
      for (var i=0;i<radiobuttons.length;i++){
        var tmp = radiobuttons[i].value;
        if (tmp == radiovalue) {
          radiobuttons[i].checked = true;
        }
      }
  }
}

/**
 * Makes sure the the user has checked at least (1) checkbox.
 *
 * @param objChkChildren list of checkboxes.
 * @return true if found any checked checkboxes; false, otherwise.
 */
DomUtils.hasSelectedCheckBoxes = function( objChkChildren ) {
    var blnIsSelected = false;

    if ( objChkChildren != null ) {
        if  ( objChkChildren.length != null ) {
          for (var i=0; i < objChkChildren.length;i++) {
                    if (objChkChildren[i].checked) {
                        blnIsSelected = true;
                        break;
                    }
          }
        } else {
          if ( objChkChildren.checked != null ) {
                    blnIsSelected = objChkChildren.checked;
          }
        }
    }

    return blnIsSelected;
}

/**
 * Retrieves the value of a select list on a given form
 *
 * @param formname that contains the select element to query
 * @param selectname name of the select element to query
 * @return the value of the currently selected value in a select list.
 */
DomUtils.getSelectListValue = function(formname, selectname) {
    var theMenu = document[formname].elements[selectname];
    var selecteditem = theMenu.selectedIndex;
    return theMenu.options[selecteditem].value;
}

/**
 * Sets the value of a select list on a given form
 *
 * @param formname that contains the select element to update
 * @param selectname object to update
 * @param selectvalue to set
 */
DomUtils.setSelectListValue = function(formname, selectname, selectvalue) {
  var theMenu = document[formname][selectname];
  for (var i=0;i<theMenu.options.length;i++){
    var tmp = theMenu.options[i].value;
    if (tmp == selectvalue) {
      theMenu.selectedIndex = i;
    }
  }
}

/**
 * Unchecks/checks dependent check boxes based on parent select all check box
 *
 * @param objChkChildren list of checkboxes
 * @param objIsAllSelected used to update the elements inside objChkChildren
 */
DomUtils.handleCheckBoxes = function(objChkChildren, objIsAllSelected) {

    if (objIsAllSelected == undefined) {
        return;
    }

    if ( objChkChildren !== undefined ) {
        if  ( objChkChildren.length !== undefined ) {
              for (var i=0; i < objChkChildren.length;i=i+1) {
                  objChkChildren[i].checked = objIsAllSelected.checked;
              }
        } else {
            objChkChildren.checked = objIsAllSelected.checked;
        }
      }

}

/**
 * Creates a form
 *
 * @param formAction value used for the 'action' attribute of the html form about to be created.
 * @return the newly created form object.
 */
DomUtils.createForm = function(formAction) {

    var newForm = document.createElement("form");
    var currentBody = document.getElementsByTagName("body")[0];
    currentBody.appendChild(newForm);
    newForm.action=formAction;
    newForm.method="POST";
    return newForm;

}

/**
 * Creates a hidden field on the given form
 *
 * @param documentObj document object to create the input type='hidden' element within (i.e. window.document)
 * @param formObj form object to create the input type='hidden' element within (i.e. window.document) 
 * @param fieldName name of the input type='hidden' element.
 * @param fieldValue value of the input type='hidden' element.
 */
DomUtils.createHiddenFormField = function(documentObj, formObj, fieldName, fieldValue) {

    var hiddenInput = documentObj.createElement("input");
    hiddenInput.setAttribute('type','hidden');
    hiddenInput.setAttribute('name', fieldName);
    hiddenInput.setAttribute('value', fieldValue);
    formObj.appendChild(hiddenInput);

}

/**
 * Removes smart quotes for a given string
 *
 * @param value to clean up
 * @return the cleaned up string without smart quotes
 */
DomUtils.removeSmartQuotes = function(value) {
    var sbuf = "";
    var len = value.length;
    for( var i = 0; i < len; i++ ) {
      var ch = value.charAt(i);

      var cc = value.charCodeAt(i);

      if (cc == 8220)
         sbuf += '"';
      else if (cc == 8221)
         sbuf += '"';
      else if (cc == 8216)
         sbuf += '\'';
      else if (cc == 8217)
         sbuf += '\'';
      else if (cc == 8211)
         sbuf += '-';
      else sbuf += ch;
    }
    return sbuf;
}

/**
 * Replaces special characters
 *
 * @param value to clean up
 * @return the cleaned up string without special characters
 */
DomUtils.replaceSpecialCharacters = function(value) {

    value = DomUtils.removeSmartQuotes(value);

    var sbuf = "";
    var len = value.length;
    for( var i = 0; i < len; i++ ) {
      var ch = value.charAt(i);

      var cc = value.charCodeAt(i);

      if (cc == 174)
         sbuf += '&#174;';
      else sbuf += ch;
    }
    return sbuf;
}


/**
 * Checks to see if any item with value and original attributes show any change
 *
 * @return true if any item changed; false otherwise
 */
DomUtils.checkIfPageChanged = function() {
    
    var myForm = document.forms["frmMain"];
    var result = false;

    for(var x = 0; x < myForm.length; x++ ) {
        var myField = myForm.elements[x];

        switch( myField.type ) {
            case "text":
                result = myField.value != myField.original;
                break;
            case "checkbox":
                result = (myField.checked + "") != myField.original;
                break;
            case "select-one":
                result = myField.item(myField.selectedIndex).value != myField.original;
                break;
        }

        if( result ) {
            break;
        }
    }

    return result;
}

/**
 * Preloads any images passed in as parameters.
 */
DomUtils.preloadImages = function() { //v3.0
    var d=document;
    if  (d.images) {
        if(!d.MM_p) d.MM_p=new Array();
        var i,j=d.MM_p.length,a=DomUtils.preloadImages.arguments;
        for(i=0; i<a.length; i++)
            if (a[i].indexOf("#")!=0) {
                d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];
            }
    }
}

/**
 * Opens a new browser window.
 *
 * @param theURL url to render in the window
 * @param winName name of the window
 * @param features to enable/disable for the window (menubar,sizeable...)
 */
DomUtils.openBrWindow = function(theURL,winName,features) { //v2.0
    window.open(theURL,winName,features);
}

/**
 * Swaps images
 */
DomUtils.swapImage = function() { //v3.0
    var i,j=0,x,a=DomUtils.swapImage.arguments;
    document.MM_sr=new Array;
    for(i=0;i<(a.length-2);i+=3)
        if ((x=DomUtils.findObj(a[i]))!=null) {
            document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];
        }
}

/**
 * Restores images after swaping them.
 */
DomUtils.swapImgRestore = function() { //v3.0
    var i,x,a=document.MM_sr;
    for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

/**
 * Finds an object
 * 
 * @param n object to find
 * @param d document to look for (i.e. window.document)
 * @return object found.
 */
DomUtils.findObj = function(n, d) { //v4.0
    var p,i,x;
    if(!d) d=document;
    if ((p=n.indexOf("?"))>0&&parent.frames.length) {
        d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
    }
    if (!(x=d[n])&&d.all) x=d.all[n];
    for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
    for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=DomUtils.findObj(n,d.layers[i].document);
    if (!x && document.getElementById) x=document.getElementById(n);
    return x;
}

/**
 * Checks if the function exists in the current document.
 * 
 * @param functionname function name to check for.
 * @return true if found.
 */
DomUtils.functionExists = function(functionname) {
    if(typeof functionname=='function') {
        return true;
    }
    return false;
}

/**
 * Checks to see if the event is an enter key press.
 * 
 * @param the browser event.
 * @return true if event is enter key, false otherwise.
 */
DomUtils.isEnterKeyEvent = function(event) {
    
    var characterCode; //literal character code will be stored in this variable

    if(event && event.which){ //if which property of event object is supported (NN4)
        characterCode = event.which; //character code is contained in NN4's which property
    } else {
        characterCode = event.keyCode; //character code is contained in IE's keyCode property
    } 

    if(characterCode == 13) { //if generated character code is equal to ascii 13 (if enter key)        
        return true;
    } else {
        return false;
    }

}

/**
 * Creates a drop down option.
 * 
 * @param the browser document.
 * @param the option id.
 * @param the option description.
 * @param flag indicating if option is selected.
 * @return created select option.
 */
DomUtils.createSelectOption = function(documentObj, optionId, optionDescription, isSelected) {
    
    var option = documentObj.createElement('OPTION');
    option.value = optionId;
    option.innerHTML = optionDescription;

    if (isSelected) {
        option.selected = true;
    }
    
    return option;

}

/**
 * Creates a drop down option.
 * 
 * @param the select object to clear.
 * @param flag indicating if first option should be skipped, allows skipping select option.
 */
DomUtils.removeSelectOptions = function(objDropDown, skipFirst) {
    
    if (objDropDown == undefined) {
        return;
    }
    
    if (objDropDown.options == undefined) {
        return;
    }
    
    var indexLength = objDropDown.options.length;
    
    var loopEnd = 0;
    if (skipFirst) {
        loopEnd=1;
    }
    
    for (var idx=indexLength-1; idx >= loopEnd; idx=idx-1) {
        var optionChild = objDropDown.options[idx];
        objDropDown.removeChild(optionChild);
    }

}
