/**
* Generic JavaScript routines for form objects. Routines are for formatting, validation,
* creating, and manipulating various types of form objects.
*
* Gary Wells - 10/10/2003
*/

/*******************************************************************************************
* CHECK BROWSER VERSION
*******************************************************************************************/

/*
 * checkBrowserVersion - Determines if browser is IE 5.5 or greater
 * INPUT - forward to page if error (example: "invalid_browser_version.htm")
 * OUTPUT - boolean = true if IE 5.5 or greater
 */
function checkBrowserVersion(OnErrorPage) {
	// This is extracted from the mozilla browser sniffer
	// http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
	// convert all characters to lowercase to simplify testing
	var agt=navigator.userAgent.toLowerCase();
	// *** BROWSER VERSION ***
	// Note: On IE5, these return 4, so use is_ie5up to detect IE5.
	var is_major = parseInt(navigator.appVersion);
	var is_minor = parseFloat(navigator.appVersion);
	var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
	var is_ie3    = (is_ie && (is_major < 4));
	var is_ie4    = (is_ie && (is_major == 4) && (agt.indexOf("msie 4")!=-1) );
	var is_ie5    = (is_ie && (is_major == 4) && (agt.indexOf("msie 5.0")!=-1) );
	var is_ie5_5  = (is_ie && (is_major == 4) && (agt.indexOf("msie 5.5") !=-1));
	var is_ie5_5up =(is_ie && !is_ie3 && !is_ie4 && !is_ie5);

	if(!is_ie5_5up) {
//	  alert("You must have IE 5.5 or later installed to run this application");
	  window.navigate(OnErrorPage);
	  return false;
	}
    return true;
}


/*******************************************************************************************
* DATE FUNCTIONS
*******************************************************************************************/

/*
 * validateDate - Validates and formats a date mm/dd/yyyy
 * INPUT - object = form element with the date
 * OUTPUT - boolean = true if valid date
 */
function validateDate(ele) {
  var val = ele.value;
  if(val!=null && val!="") {
    var d = parseDate(val);
    if(isNaN(d)) {
      return false;
    } else {
      var year = val.substring(val.length-4,val.length);
      if (isNaN(year)) {
        d = adjustCentury(d);
      }
      ele.value=formatDate(d);
    }
  }
  // adjust century if two char year entered
  return true;
}

/*
 * isYear - Validates is a valid four digit year
 * INPUT - object = form element with the year
 * OUTPUT - boolean = true if valid year
 */
function isYear(ele) {
  var val = ele.value;
  if(val!=null && val!="") {
    var blankRegExp = /^[0-9]{4}$/;
	  if(!blankRegExp.test(val)) {
      return false;
    }
  }
  return true;
}

/*
 * formatDate - Parses a date into a date object
 * INPUT = string - date/time string
 * OUTPUT = date object ,  or NaN if date does not parse
 *          see http://msdn.microsoft.com/library/en-us/script56/html/js56jsmthparse.asp?frame=true
 *          for more information on how Date.parse() works.
 */
function parseDate(s) {
  return new Date(Date.parse(s));
}

/*
 * formatDate - Formats a date object into an mm/dd/yyyy date string
 * INPUT = date object
 * OUTPUT = String - formatted mm/dd/yyyy
 */
 /* function formatDate(d) {
  if(d!=null) {
      var s = (d.getMonth() + 1) + "/";
      s += d.getDate() + "/";
      s += d.getFullYear();
      return s;
  } else {
    return null;
  }
} */

/*
 * Appends current year to the date stored in the given field if
 * one isn't already specified
 *
 */
function formatDate(field) {
/**************Included On 9/9/2004 *********
 To Check Null value in Entered/Modified/lastTouchedDate ****/
/* ss = new Date();
  switch(field.name)
  {
  case 'enteredDate':
  case 'modifiedDate':
  case 'lastTouchedDate':
    {
    if(field.value == ""){
    field.value = ss.getDate()+"/"+(ss.getMonth()+1)+"/"+ss.getYear();break;}
    }
  }*/
/*********************End*************************/
	dateField = field.value;
	if (dateField != null && dateField != "") {
		// if the user entered a date of the form "5/1" or "10/27"
		if ((dateField.length >= 3 && dateField.length < 6) || (dateField.length >=6 && dateField.length <= 8)) {
			if (dateField.length >= 3 && dateField.length < 6) {
			  //getting month from  input
        var str_mon = (dateField.substring(0,dateField.indexOf("/")));
        //getting the date from the input
        var str_dat= dateField.substring(dateField.lastIndexOf("/")+1,dateField.length);

        if ((dateField.charAt(dateField.length - 1) != "/") && (str_mon >= 1 && str_mon <= 12) && (str_dat >= 1 && str_dat <= 31)) {
          // add a "/" if we need one (we probably do, but
          // we'll want to guard against users entering
          // something like "3/15/"
          dateField += "/";
        }
			}
			//getting month from  input
			var strMon = (dateField.substring(0,dateField.indexOf("/")));
			//getting the date from the input
			var strDat= dateField.substring(dateField.indexOf("/")+1,dateField.lastIndexOf("/"));
			//getting the year from the input
			var str_yr= dateField.substring(dateField.lastIndexOf("/")+1,dateField.length);
			// If there is year is empty
			if((strMon >= 1 && strMon <= 12) && (strDat >= 1 && strDat <= 31) && str_yr == "") {
			  if(((strMon == 1 || strMon == 3 || strMon == 5 || strMon == 7 || strMon == 9 || strMon == 11) && (strDat >= 1 && strDat <= 31)) || ((strMon == 2 || strMon == 4 || strMon == 6 || strMon == 8 || strMon == 10 || strMon == 12) && (strDat >= 1 && strDat <= 30))) {
			    var curYear = (new Date()).getYear();
			    if((strMon == 2) && (strDat == 30)) {
			    } else {
            dateField += curYear;
            field.value = dateField;
          }
				}
			}
		  if(dateField.length >=6 && dateField.length <= 8) { // If there is a two digit year
		    // if the date is in 6/6/2 format
		    if(dateField.substring(dateField.length-1) == "/") {
          dateField = dateField.substring(0,dateField.length-1);
          strMon = (dateField.substring(0,dateField.indexOf("/")));
          strDat = dateField.substring(dateField.indexOf("/")+1,dateField.lastIndexOf("/"));
          str_yr = dateField.substring(dateField.lastIndexOf("/")+1,dateField.length);
        }
			  if((strMon >= 1 && strMon <= 12) && (strDat >= 1 && strDat <= 31)) {
          // If the year is less than 50 then prefix 20 value to it
          if(str_yr<50) {
            if(str_yr.length==1) {
              str_yr="200"+str_yr;
            } else if(str_yr.length==2) {
              str_yr="20"+str_yr;
            } else if(str_yr.length==3) {
              str_yr="2"+str_yr;
            }

          }
          // If the year is more than 50 value and less than 100 then prefix 19 value to it
          else if(str_yr>50&&str_yr<100) {
            if(str_yr.length==2) {
              str_yr="19"+str_yr;
            }
          }
          field.value = strMon + "/" + strDat+ "/" +str_yr;
        }
			}
		}
	}
 }

/*
 * adjustCentury - Adjusts the year within a data object
 * INPUT = date object = date containing yeat to be adjusted
 *         int = pivot year (defaults to year 20)
 * OUTPUT - date object = date with year adjusted
 */
function adjustCentury(d, pivot) {
  if(pivot==null) {
    pivot = 20;
  }
  if(d!=null) {
    if (d.getYear() <= pivot) {
      d.setFullYear(2000+d.getYear());
    }
    return d;
  } else {
    return null;
  }
}

/*******************************************************************************************
* STRING FUNCTIONS
*******************************************************************************************/

/*
 * trim - Trims leading and trailing blanks.
 * INPUT - string = input string
 * OUTPUT - string = trimmed string
 */
function trim(st) {
	var len = st.length
	var begin = 0, end = len - 1;
	while (st.charAt(begin) == " " && begin < len) {
		begin++;
	}
	while (st.charAt(end) == " " && begin < end) {
		end--;
	}
	return st.substring(begin, end+1);
}

/**
 * crlfToBr - Replaces line feeds with <br>
 * INPUT - string reference to manipulate.
 * OUTPUT - manipulated string reference
 */
function crlfToBr(s) {
  var expr = /\n/g;
  if(s!=null)
    return s.replace(expr, "\n<br>");
}


/*******************************************************************************************
* TELEPHONE NUMBER FUNCTIONS
*******************************************************************************************/

/*
 * formatPhone - Formats a user entered phone number.
 * INPUT - object = phone number
 * OUTPUT - boolean = true if success
 */
function formatPhone (field) {

	field.value = trim(field.value);

 	var ov = field.value;
  	var v = "";
  	var x = -1;

	// format only if no leading + indicating an international number
	if (0 < ov.length && '+' != ov.charAt(0)) {
		var n = 0;

		// remove phone numbers beginning with a 1
		if ('1' == ov.charAt(0)) {
			ov = ov.substring(1, ov.length);
		}

    		// loop through characters
		for (i = 0; i < ov.length; i++) {
      			var ch = ov.charAt(i);

      			// build formatted number
      			if (ch >= '0' && ch <= '9') {
        			if (n == 0) v += "(";
        			else if (n == 3) v += ") ";
        			else if (n == 6) v += "-";
        			v += ch;
        			n++;
      			}
      			// break at first non-valid character assuming it's the beginning of an extension
      			if (! (ch >= '0' && ch <= '9') && ch != ' ' && ch != '-' && ch != '.' && ch != '(' && ch != ')') {
      			  	x = i;
        			break;
      			}
    		}
    		// append the extension
    		if (x >= 0) v += " " + ov.substring(x, ov.length);

    		// if a valid phone number, then use new formatted number
    		if (n == 10 && v.length <= 40) field.value = v;
	}
  	return true;
}

/*******************************************************************************************
* SELECT LIST FUNCTIONS
*******************************************************************************************/

/*
 * createSelectList - Creates a select list from the array of data provided.
 * INPUT - name = a string to assign to the select's name & id
 *        optionsDict = ActiveX Scripting.Dictionary object with ID's and values for the <option> tags
 *        selectedValue = the value attibute of the <option> tag to select
 * OUTPUT - new <Select> tag object
 */
function createSelectList(name, optionsDict, selectedValue, parentNode, oldNode) {
	var s = document.createElement("SELECT");
	if(oldNode==null) {
		parentNode.appendChild(s);
	} else {
		parentNode.replaceChild(s,oldNode);
	}
	s.name=name;
	s.id=name;
	if(optionsDict != null) {
		var keys = (new VBArray(optionsDict.Keys())).toArray();   // Get the keys.
		var items = (new VBArray(optionsDict.Items())).toArray();   // Get the values.
		for (key in keys)   {
			s.add(createOption(keys[key],items[key],false));
			if(keys[key]==selectedValue) {
				s.options[key].selected=true;
			}
		}
	}
	return s;
}

/*
 * selectOption - Selects an option in a select list by value
 * INPUT - selectList = <Select> tag object
 *         optionsValue =  the value attibute of the <option> tag to select
 * OUTPUT - modified <Select> tag object
 */
function selectOption(selectList, optionValue) {
  var options = selectList.options;
  for(i = 0;i<options.length;i++) {
    if(options[i].value==optionValue) {
      options[i].selected=true;
    }
  }
  return selectList;
}

/*
 * selectOption - Selects an option in a select list by description
 * INPUT - selectList = <Select> tag object
 *         optionDesc =  the description attibute of the <option> tag to select
 * OUTPUT - modified <Select> tag object
 */
function selectOptionDesc(selectList, optionDesc) {
  var options = selectList.options;
  for(i = 0;i<options.length;i++) {
    if(options[i].description==optionDesc) {
      options[i].selected=true;
    }
  }
  return selectList;
}

/*
 * selectAllOptions - Selects all options in a select list
 * INPUT - selectList = <Select> tag object
 * OUTPUT - modified <Select> tag object
 */
function selectAllOptions(selectList) {
  if(selectList != null) {
    for (i=0; i < selectList.length; i++) {
 	  selectList.options[i].selected = true;
    }
  }
  return selectList;
}

/*
 * deleteOption - Deletes an option from a select list by value
 * INPUT - selectList = <Select> tag object
 *         optionValue = value to delete
 * OUTPUT - modified <Select> tag object
 */
function deleteOption(selectList, optionValue) {
  var options = selectList.options;
  for(i = 0;i<options.length;i++) {
    if(options[i].value==optionValue) {
      options[i] = null;
    }
  }
  return selectList;
}

/*
 * selectOptionText - Selects and returns the text of an option from a select list by value
 * INPUT - selectList = <Select> tag object
 *         optionsValue =  the value attibute of the <option> tag to look for
 * OUTPUT - the text string associated with the selected value
 */
function selectOptionText(selectList, optionValue) {
  var options = selectList.options;
  var text;
  for(i = 0;i<options.length;i++) {
    if(options[i].value==optionValue) {
      text = options[i].innerText;
    }
  }
  return text;
}

/*
 * createOption - Creates a new option in a select list
 * INPUT - value = the value attribute of the new <option> tag
 *         text = the text attribute of the new <option> tag
 *         selected = a boolean dictating the selected state of the tag
 * OUTPUT - new <option> tag object
 */
function createOption(value,text,selected) {
  var o = document.createElement("OPTION");
  o.text=text
  o.value=value;
  if(selected) o.selected=true;
  return o;
}

/*
 * currentSelectedDescription - Returns the text of the selected option in a select list
 * INPUT - selectList = <Select> tag object
 * OUTPUT - String description of the current selected option
 *          (or first select option in multi-select)
 */
function currentSelectedDescription(selectList) {
  try {
  	return selectList.options[selectList.selectedIndex].innerText;
  } catch (e) {}
	return null;
}

/*
 * currentSelectedDescriptions - Returns all the text of the selected options in a multi select list
 * INPUT - selectList = <Select> tag object
 * OUTPUT - Array of string descriptions of the current selected options in a multi select list
 */
function currentSelectedDescriptions(selectList) {
	var selectedValues = new Array();
  var options = selectList.options;
    for(i = 0;i<options.length;i++) {
      if(options[i].selected==true) {
		selectedValues.push(ptions[i].innerText);
      }
    }
    return selectedValues;
}

/*
 * moveSelectedOptions - Moves selected options from one select list to another
 * INPUT - selectFrom = the <select> tag to move selected <option> tags from.
 *         selectFrom = the <select> tag to move selected <option> tags to.
 * OUTPUT - void
 */
function moveSelectedOptions(selectFrom, selectTo){
  for(i=0; i < selectFrom.length; i++){
    if (selectFrom.options[i].selected == true ) {
      var selectToLen = selectTo.length;
      selectTo.options[selectToLen] = createOption(selectFrom.options[i].value, selectFrom.options[i].text, false);
      selectFrom.options[i] = null;
      i--;
    }
  }
}

/*
 * replaceSelectWithInput - Replaces a select list with a text box containing the selected option description
 * INPUT - selectList = <Select> tag object
 * OUTPUT - obj = the new input text object
 */
function replaceSelectWithInput(selectList) {
	var parent = selectList.parentNode;
	var selectedText = currentSelectedDescription(selectList);
	var input = createTextInput(selectList.id, selectedText, parent)
	parent.replaceChild(input,selectList);
	return input;
}

/*******************************************************************************************
* RADIO FUNCTIONS
*******************************************************************************************/

/*
 * getRadioValue - Gets the value of the select radio button
 * INPUT - event
 * OUTPUT - none
 */
function getRadioValue(name){
  var theRadios = document.getElementsByName(name);
  var theVal = "";
  for(var i=0;i<theRadios.length;i++){
    if(theRadios[i].checked) {
      theVal = theRadios[i].value;
    }
  }
  return theVal;
}

/*******************************************************************************************
* CREATE INPUT FUNCTIONS
*******************************************************************************************/

/*
 * createTextInput - Creates a text input object on a form
 * INPUT - name = string to assign to the id and name attributes
 *         value = string to assign to the value attribute
 *         parentNode = form to be appended to
 * OUTPUT - new <input type="text"> tag
 */
function createTextInput(name, value, parentNode) {
  var i = document.createElement("INPUT");
  parentNode.appendChild(i);
  //Type text is the default
  i.name=name;
  i.id=name;
  i.value=value;
  return i;
}

/*
 * createHiddenInput - Creates a hidden input object on a form
 * INPUT - name = string to assign to the id and name attributes
 *         value = string to assign to the value attribute
 *         parentNode = form to be appended to
 * OUTPUT - new <input type="text"> tag
 */
function createHiddenInput(name, value, parentNode) {
  var h = document.createElement("<INPUT id=" + name + " name=" + name + ">");
  h.type="hidden";
  parentNode.appendChild(h);
  h.value=value;
  return h;
}

/*
 * createRadioButton - Creates a radio button within a radio set
 * INPUT - name = string to assign to the id and name attributes
 *         value = string to assign to the value attribute
 *         checked = a boolean dictating the selected state of the tag
 *         parentNode = radio set to be appended to
 * OUTPUT - new <input type="radio"> tag
 */
function createRadioButton(name,value,checked, parentNode) {
  var checkStr = "";
  if(checked) checkStr = "CHECKED";
  var r = document.createElement("<INPUT id=" + name + " name=" + name +" " + checkStr + " >");
  r.type="radio";
  parentNode.appendChild(r);
  r.value=value;

  // r.checked=checked;
  return r;
}

/*
 * createCheckbox - Creates a check box on a form
 * INPUT - name = string to assign to the id and name attributes
 *         value = string to assign to the value attribute
 *         checked = a boolean dictating the selected state of the tag
 *         parentNode = form to be appended to
 * OUTPUT - new <input type="checkbox"> tag
 */
function createCheckbox(name,value,checked, parentNode) {
  var c = document.createElement("INPUT");
  c.type="checkbox";
  parentNode.appendChild(c);
  c.name=name;
  c.id=name;
  c.value=value;
  c.checked=checked;
  return c;
}

/*
 * createTextArea - Creates a text area on a form
 * INPUT - name = string to assign to the id and name attributes
 *         value = string to assign to the value attribute
 *         value = number to assign to the cols attribute
 *         rows = number to assign to the rows attribute
 *         parentNode = form to be appended to
 * OUTPUT - new <textarea> tag
 */
function createTextArea(name,value,cols,rows, parentNode) {
  //alert('enter textarea');
  var t = document.createElement("TEXTAREA");
  //alert('appending child');
  parentNode.appendChild(t);
  //alert('creating name');
  t.name=name;
  //alert('id');
  t.id=name;
  t.value=value;
  t.cols=cols;
  t.rows=rows;
  return t;
}

/*******************************************************************************************
* VALIDATION FUNCTIONS
*******************************************************************************************/

/*
 * isRadioChecked - Determines if any of the radios are checked
 * INPUT - string = element name
 * OUTPUT - boolean = true if checked
 */
function isRadioChecked(name){
    var theRadios = document.getElementsByName(name);
    var bChecked = false;
    for(var i=0;i<theRadios.length;i++){
        if(theRadios[i].checked) bChecked = true;
    }
    return bChecked;
}

/*
 * isBlank - Determines if blank
 * INPUT - string = string to be exmanined
 * OUTPUT - boolean = true if blank
 */
function isBlank(val){
	var blankRegExp = /[^\s+?]/;
	return val == null || val == '' || !blankRegExp.test(val);
}

/*
 * isNotBlank - Determines if not blank
 * INPUT - string = string to be exmanined
 * OUTPUT - boolean = true if not blank
 */
function isNotBlank(val){
	var blankRegExp = /[\S]/;
	return blankRegExp.test(val);
}

/*
 * isDollarValue - Determines if a valid dollar amount
 * INPUT - string = string to be exmanined
 * OUTPUT - boolean = true if dollar amount
 */
function isDollarValue(val){
	var asstRegExp = /^\$?\d*(\.\d{1,2})?$/;
	if(!asstRegExp.test(val)){
		return isCommaDollarValue(val);
	}
	else return true;
}

/*
 * isCommaDollarValue - Determines if a valid dollar amount
 * INPUT - string = string to be exmanined containing commas
 * OUTPUT - boolean = true if dollar amount
 */
function isCommaDollarValue(val){
	var dvRegExp = /^\$?\d{1,3}(,\d{3})*(\.\d{1,2})?$/;
	return (dvRegExp.test(val));
}

/**
 * Returns true if the given value is a number
 */
function isNumeric(val) {
	// account for dollar signs and commas 
	return !isNaN(val);
}

function isNumericOrCash(val) {
	return isCommaDollarValue(val) || isNumeric(val);
}

function removeCommas(val) {
	return val.toString().replace(',', '');
}

function roundCurrency(currency) {
	if (currency != null && currency != '' && isNumeric(currency)) {
		currency = Math.round(currency * 100)/100;
	}
	return appendZeroes(currency);
}

function currencyToNumber(currency) {	
	num = parseFloat(removeCommas(removeLeadingCurrencySymbol(currency.toString())));	
	if (isNumeric(num)) {
		return num;
	}
	// don't return null here - for some reason, subsequent checks for null seem to fail.
	// I've grown tired trying to figure out why...
	return '';	
	
	//currency.toString().replace(/\$|\,/g,'')));
}

function nullIfZero(num) {
	return parseFloat(num) == 0 ? '' : num;
}

/**
 * appends zeroes, as needed, to the given numeric value.
 *
 */
function appendZeroes(val) {

	str = "" + val;
	
	if (str != "" && isNumeric(val)) {
		dotIndex = str.indexOf('.');

		if (dotIndex == -1) {
			str += ".00";
		} else if (str.length - (dotIndex + 1) == 1) {
			str += "0";
		}
	} 
	return str;
}

/*
 * Removes the first non-numeric, non-decimal character found in the given string
 * (presumably, this wil be a currency symbol).
 */
function removeLeadingCurrencySymbol(str) {	
	if (str != null && str.length > 0) {
		str = trim(str);
		ch = str.charAt(0);
		if (ch != '.' && !(ch >= '0' && ch <= '9')) {
			str = str.substring(1, str.length);
		}
	}
	return str;
}

/*******************************************************************************************
* FORM FUNCTIONS
*******************************************************************************************/

/*
 * submitForm - Submits a form
 * INPUT - form Object
 * OUTPUT - boolean success/failure
 */
function submitForm(formEle) {
  //be generous and only cancel if onsubmit returns false (i.e. don't assume it returns true)
  var success = formEle.fireEvent("onsubmit");
  if(success==null || success == true) {
    formEle.submit();
    return true;
  } else {
    return false;
  }
}

/*
 * subFormOnEnter - Monitors for the enter key and submits the form once detected
 * INPUT - event
 * OUTPUT - none
 */
function subFormOnEnter() {
	var key = event.keyCode;
	if(key==13) { //enter key code
		var frmEle = event.srcElement;
	  var form = frmEle.form;
		form.submit();
	}
}

/*
 * buildQueryString - Builds the query string portion of the request based upon all the
 *                    all the input elements on the form
 * INPUT - form name
 * OUTPUT - the form as a GET Query String
 */
function buildQueryString(frm) {
	//var action=frm.action;

  var qs = frm.action;
  for (e=0;e<frm.elements.length;e++) {
    if (frm.elements[e].name!='') {
      qs+=(qs.indexOf('?')==-1)?'?':'&';
      qs+=frm.elements[e].name+'='+frm.elements[e].value;
    }
  }
  //return action + escape(qs);
	return qs;
}

/*
 * clearForm - Clears all the input elements on a form
 * INPUT - form name
 * OUTPUT - none
 */
function clearForm(formName) {
  for (x=0 ; x< document.forms[formName].elements.length; x++) {
    e = document.edit(x);
    // skip hidden fields
    if (e.type != 'hidden') {
      if (e.type == 'checkbox') {
        e.checked = false;
      } else if (e.type == 'select-one') {
        e.selectedIndex = 0;
      } else if (e.type == 'select-multiple') {
           for(m=0;m<e.length;m++) {
             e.options[m].selected = false;
           }
      } else {
        e.value = '';
      }
    }
  }
}

/*
 * makeReadOnly - Makes all input type objects on a form read only
 * INPUT - form object
 * OUTPUT - true
 */
function makeReadOnly(e) {
  var inputs = e.tags("INPUT");
  for(i=0;i<inputs.length;i++) {
    var selectable = inputs[i].getAttribute("ALWAYS_SELECTABLE");
    if(selectable==null || selectable=="false") {
  	  if(inputs[i].type =="checkbox" || inputs[i].type =="radio") {
    		inputs[i].disabled=true;
  	  } else {
    		inputs[i].readOnly=true;
  	  }
    }
  }
  return true;
}

/*
 * makeFormReadOnly - Makes all input type objects on a form read only
 * INPUT - form name
 * OUTPUT - true
 */
function makeFormReadOnly(formName) {
  var e = document.forms(formName);
  makeReadOnly(e);
}
/*
 * makeAllReadOnly - Makes all input type objects in the document read only
 * INPUT - void
 * OUTPUT - void
 */
function makeAllReadOnly() {
  var e = document.body.all;
  makeReadOnly(e);
}

/*******************************************************************************************
* EVENT FUNCTIONS
*******************************************************************************************/

/*
 * inputEvents - This function binds the selectInputEvt and unselectInputEvt functions to
 *               the onactivete and onblur events (respectively) of all <input type="text">
 *               tags on the page
 * INPUT - none
 * OUTPUT - true
 */
function inputEvents() {
  //bind events to input tags
  //var inputs = document.body.all.tags("INPUT");
  var inputs = document.getElementsByTagName("INPUT");
  for(i=0;i<inputs.length;i++) {
    var selectable = inputs[i].getAttribute("ALWAYS_SELECTABLE");
    if(selectable==null || selectable=="false") {
      if(inputs[i].type=='text') {
        inputs[i].attachEvent("onactivate",selectInputEvt);
        inputs[i].attachEvent("onblur",unselectInputEvt);
      }
    }
  }
  return true;
}

/*
 * selectInputEvt - This function gets the active event element and passes it to the selectInput function
 * INPUT - event object (implied);
 * OUTPUT - true (methods called from event handlers should return true to continue event bubbling)
 */
function selectInputEvt() {
  var ele = event.srcElement;
  selectInput(ele);
  return true;
}

/*
 * selectInput - Selects an input object
 * INPUT - <input type="text"> tag
 * OUTPUT - none
 */
function selectInput(input) {
  input.style.borderStyle = "inset";
  input.style.margin="0 0 0 0";
}

/*
 * unselectInputEvt - This function gets the active event element and passes it to the unselectInput function
 * INPUT - event object (implied);
 * OUTPUT - true (methods called from event handlers should return true to continue event bubbling)
 */
function unselectInputEvt() {
  var ele = event.srcElement;
  unselectInput(ele);
  return true;
}

/*
 * unselectInput - Unselects an input object
 * INPUT - <input type="text"> tag
 * OUTPUT - none
 */
function unselectInput(input) {
  input.style.borderStyle = "none";
  input.style.margin="2px 2px 2px 2px";
  return true;
}



/**
 * Formats the given string value into currency.  Places commas
 * into the string at every three orders of magnitude (thousands,
 * millions, billions, etc).  Rounds to two decimal places.
 *
 */
function formatCurrency(strValue) {
	// argh - special case.  If we pass 0 to this method, it seems
	// to fail the "isBlank" test below.  This is a hack, but I don't understand
	// regular expressions well enough to debug isBlank()...
	if (strValue == "0") {
		return "0.00";
	} else if (strValue == null || isBlank(strValue)) {		
		return "";
	} else {
		
		dblValue1 = parseFloat(strValue);
		blnSign = (dblValue1 == (dblValue1 = Math.abs(dblValue1)));
		strValue = currencyToNumber(strValue);
		dblValue = parseFloat(strValue);

		//blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
		dblValue = Math.floor(dblValue*100+0.50000000001);
		intCents = dblValue%100;
		strCents = intCents.toString();
		dblValue = Math.floor(dblValue/100).toString();
		if(intCents<10) {
			strCents = "0" + strCents;
		}
		for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++) {
			dblValue = dblValue.substring(0,dblValue.length-(4*i+3)) + ',' + dblValue.substring(dblValue.length-(4*i+3));
		}
		return (((blnSign)? '' : '-' ) + dblValue + '.' + strCents);
	}
}


/**
 * getCookie - Returns the value of the specified cookie or null if it doesn't exist.
 *
 */
function getCookie(name) {
  var allCookies = document.cookie;
  var cookie = null;
  start = allCookies.indexOf(name + "=");
  if (start != -1) {
    start = allCookies.indexOf("=", start) + 1; // first character
    var end = allCookies.indexOf(";", start);
    if (end == -1) {
      end = allCookies.length;
    }
    return unescape(allCookies.substring(start, end));
  }
  return cookie;
}


/**
 * setCookie - Adds or replaces a cookie. Use null for parameters you don't care about.
 *             Pass a time value in the past to clear the cookie.
 *
 */
function setCookie(name, value, expires) {
  document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString() + "; path=/";
}

/**
 * moveOption - Move items one level up, one level down, to first and to last in a list .
 *              Pass the list object along with move option name.
 *              Option name should be one of the following
 *              'up' : move the item up by one element
 *              'down' : move the item down by one element
 *              'first' : move the item beginning of the list
 *              'last' : move the item end of the list
 *              Exceptions : No Exceptions and error handling , if list or option has
 *              invalid data, no errors or no exceptions
 *
 */

function moveOption(list,option)
{
	var items = new Array;
	var values = new Array;
	var total = list.options.length-1;
	var index = list.selectedIndex;

	for (i = list.options.length-1; i >= 0; i--)
	{
		items[i] = list.options[i].text;
		values[i] = list.options[i].value;
	}

	/* Move items up and down */
	if((option=="up") || (option=="down"))
	{
		var to;
		if(option=="up")	to = -1;
		if(option=="down")	to = +1;

		if (index == -1)
			return false;
		if (to == +1 && index == total)
			return false;
		if (to == -1 && index == 0)
			return false;
		for (i = total; i >= 0; i--)
		{
			if (index == i)
			{
				list.options[i + to] = new Option(items[i],values[i], 0, 1);
				list.options[i] = new Option(items[i + to], values[i + to]);
				i--;
			}
			else
			{
				list.options[i] = new Option(items[i], values[i]);
			}
		}

	}
	/* End condition for moving items up and down */

	/* Move items first and last */
	if((option=="first") || (option=="last"))
	{
		if(option == "first")
		{
			list.options[0] = new Option(items[index],values[index], 0, 1);
			for (i = 0; i < index; i++)
			{
				j=i+1;
				list.options[index-i] = new Option(items[index-j],values[index-j]);
			}
		}
		if(option == "last")
		{
			for(i = 0; i < total; i++)
			{
				j=i+1;
				if((index+i)<=total)
				list.options[index+i] = new Option(items[index+j],values[index+j]);
			}
			list.options[total] = new Option(items[index],values[index],0,1);
		}
	}
	/* End condition for moving items first and last */

	list.focus();

}


