﻿function confirmDelete() {
	return confirm("Are you sure you want to delete this item?");
}

// JScript File
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

function checkVersion()
{
  var msg = "You're not using Internet Explorer.";
  var ver = getInternetExplorerVersion();

  if ( ver > -1 )
  {
    if ( ver >= 6.0 ) 
      msg = "You're using a recent copy of Internet Explorer."
    else
      msg = "You should upgrade your copy of Internet Explorer.";
  }
  alert( msg );
}


function validateCountry(ddlID, tdID)
{
	var fld = document.getElementById(ddlID);
	if (!fld)
		alert("Field " + fldName + " not found");
	if (tdID)
	{
		var td = document.getElementById(tdID);
		if (!td)
			alert("Element " + tdID + " not found");
	}
	if (fld.options[fld.selectedIndex].value == "0")
	{
		if (td)
			td.style.visibility = "visible";
		return false;
	}
	else
	{
		if (td)
			td.style.visibility = "hidden";
		return true;
	}
}

function checkField(fldName, tagName, tdID)
{
	var fld = document.getElementById(fldName);
	if (!fld)
		fld = FindNodeTag(document, tagName, fldName);
	if (!fld)
	{
		alert("Field " + fldName + " not found");
		return false;
	}
	if (tdID)
	{
		var td = document.getElementById(tdID);
		if (!td)
			td = FindNodeTag(document, "TD", tdID);
		if (!td)
			var td = FindNode(document, tdID);
		if (!td)
				alert("Element " + tdID + " not found");
	}
	if (fld.value == "")
	{
		if (td)
			td.style.visibility = "visible";
		return false;
	}
	else
	{
		if (tdID)
			td.style.visibility = "hidden";
		return true;
	}
}

function checkDropDownField(fldName, tagName, tdID)
{
	var fld = document.getElementById(fldName);
	if (!fld)
		fld = FindNodeTag(document, tagName, fldName);
	if (!fld)
	{
		alert("Field " + fldName + " not found");
		return false;
	}
	if (tdID)
	{
		var td = document.getElementById(tdID);
		if (!td)
			alert("Element " + tdID + " not found");
	}
	if (fld.options[fld.selectedIndex].value == "")
	{
		if (td)
			td.style.visibility = "visible";
		return false;
	}
	else
	{
		if (tdID)
			td.style.visibility = "hidden";
		return true;
	}
}

/*
**  Returns the caret (cursor) position of the specified text field.
**  Return value range is 0-oField.length.
*/
function caretPos(oField) {

    // Initialize
    var iCaretPos = 0;

    // IE Support
    if (document.selection) {

        // Set focus on the element
        oField.focus();

        // To get cursor position, get empty selection range
        var oSel = document.selection.createRange();

        // Move selection start to 0 position
        oSel.moveStart('character', -oField.value.length);

        // The caret position is selection length
        iCaretPos = oSel.text.length;
    }

    // Firefox support
    else if (oField.selectionStart || oField.selectionStart == '0')
        iCaretPos = oField.selectionStart;

    // Return results
    return (iCaretPos);
}



function numbersonly(e, tb, dp) {
    var unicode = e.charCode ? e.charCode : e.keyCode;

    // firefox Delete key keyCode = 46 and charCode is undefined
    // IE . charCode = 46 and deleteKey doesn't fire the keypress event
    if (typeof (e.charCode) != "undefined" && e.keyCode == 46)
        return true;

    if (unicode != 8 && unicode != 37 && unicode != 39) {
        if (unicode >= 48 && unicode <= 57 || unicode == 46) {
            if (typeof (dp) == "undefined")
                dp = 2;
            var dpPos = tb.value.indexOf('.');
            if (dpPos > -1) {
                if (unicode == 46)
                    return false;
                else if (tb.value.length - dpPos == dp + 1) {
                    if (caretPos(tb) <= dpPos)
                        return true;
                    else
                        return false;
                }
            }
            else if (unicode == 46) {
                if (dp == 0)
                    return false;
                else if (tb.value.length - caretPos(tb) <= dp)
                    return true;
                else
                    return false;
            }
            else
                return true;
        } //end if
        else {
            return false;
        } 
    }
    else {
        return true;
    } 
}

function checkNumField(fldName, errName, mandatory, minVal, maxVal)
{
	var fld = document.getElementById(fldName);
	if (!fld)
		fld = FindNodeTag(document, "INPUT", fldName);
	var isValid;
	if (fld)
	{
		if (!mandatory && fld.value == "")
			isValid = true;
		else if (fld.value != "" && validateNumeric(fld.value) && parseInt(fld.value) >= minVal && parseInt(fld.value) <= maxVal)
			isValid = true;
		else
			isValid = false;
		var err = document.getElementById(errName);
		if (!err)
			err = FindNode(document, errName);
		if (err)
			err.style.visibility = isValid ? "hidden" : "visible";
	}
	else
		isValid = true;
	return isValid;
}

function checkCurrencyField(fldName, errName)
{
	var fld = document.getElementById(fldName);
	if (!fld)
		fld = FindNodeTag(document, "INPUT", fldName);
	var isValid;
	if (fld)
	{
		if (fld.value != "" && validateNumeric(removeCurrency(fld.value)))
			isValid = true;
		else
			isValid = false;
		var err = document.getElementById(errName);
		if (!err)
			err = FindNode(document, errName);
		if (err)
			err.style.visibility = isValid ? "hidden" : "visible";
	}
	else
		isValid = true;
	return isValid;
}
function checkDateField(fldName, errName)
{
	var fld = FindNodeTag(document, "INPUT", fldName);
	var isValid;
	if (fld)
	{
		if (fld.value != "" && validateDate(fld, true))
			isValid = true;
		else
			isValid = false;
		var err = FindNode(document, errName);
		if (err)
			err.style.visibility = isValid ? "hidden" : "visible";
	}
	else
		isValid = true;
	return isValid;
}

function getFloat(strVal)
{
	strVal = strVal.replace("$", "").replace(",", "");
	if (strVal == "")
		return 0;
	var val = parseFloat(strVal);
	if (isNaN(val))
		val = 0;
	return val;
}

function round_decimals(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return result3;
}
var months = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
var days = new Array("Sunday", "Monday", "Tuesday","Wednesday","Thursday", "Friday","Saturday");

function formatDateWithDay(dt)
{
	var strDate = days[dt.getDay()].substr(0, 3) + " " + dt.getDate() + " " + months[dt.getMonth()] + " " + dt.getFullYear();
	return (strDate);
}

function formatDate(dt)
{
	var strDate = dt.getDate() + " " + months[dt.getMonth()] + " " + dt.getFullYear();
	return (strDate);
}

function validateCity(controlID, comboID, tdID, validateCity)
{
	var wcCityText = document.getElementById(comboID + "_Text");
	var wcCityValue = document.getElementById(comboID + "_Value");
	if (tdID)
	{
		var td = document.getElementById(tdID);
		if (!td)
			alert("Element " + tdID + " not found");
	}
	var valid = false;
	if (wcCityValue.value != "") // If user has selected a value from the dropdown
		valid = true;
	else if (wcCityText.value != "")
	{
		Anthem_Clear__EVENTTARGET(); // fix for bug #1429412
		var result = Anthem_CallBack(null, "Control", controlID, 'CheckCity', [wcCityText.value], null, null, false, false);
		var cityID = result.value;

		if (cityID == -1)
		{
			if (validateCity)
				valid = false;
			else
				valid = true;
		}
		else
		{
			wcCityValue.value = cityID;
			valid = true;
		}
	}
	else 
		valid = false;
	
	if (td)
		if (valid)
			td.style.visibility = "hidden";
		else
			td.style.visibility = "visible";
	return valid;
}


function validateEmail( strValue) {
/************************************************
DESCRIPTION: Validates that a string contains a
  valid email pattern.

 PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS: Accounts for email with country appended
  does not validate that email contains valid URL
  type (.com, .gov, etc.) or valid country suffix.
*************************************************/
var objRegExp  =
 /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i;

  //check for valid email
  return objRegExp.test(strValue);
}

function validateUSPhone( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains valid
  US phone pattern.
  Ex. (999) 999-9999 or (999)999-9999

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
  var objRegExp  = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/;

  //check for valid us phone with or without space between
  //area code
  return objRegExp.test(strValue);
}

function  validateNumeric( strValue ) {
/*****************************************************************
DESCRIPTION: Validates that a string contains only valid numbers.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
******************************************************************/
  var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;

  //check for numeric characters
  return objRegExp.test(strValue);
}

function validateInteger( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid integer number.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
**************************************************/
  var objRegExp  = /(^-?\d\d*$)/;

  //check for integer characters
  return objRegExp.test(strValue);
}

function validateCurrency( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid integer number, $, , and optional 2 decimal places.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
**************************************************/
  var objRegExp  = /\$?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?\b/;

  //check for integer characters
  return objRegExp.test(strValue);
}


function validateNotEmpty( strValue ) {
/************************************************
DESCRIPTION: Validates that a string is not all
  blank (whitespace) characters.

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
   var strTemp = strValue;
   strTemp = trimAll(strTemp);
   if(strTemp.length > 0){
     return true;
   }
   return false;
}

function validateUSZip( strValue ) {
/************************************************
DESCRIPTION: Validates that a string a United
  States zip code in 5 digit format or zip+4
  format. 99999 or 99999-9999

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

*************************************************/
var objRegExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;

  //check for valid US Zipcode
  return objRegExp.test(strValue);
}

function validateUSDate( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
    valid dates with 2 digit month, 2 digit day,
    4 digit year. Date separator can be ., -, or /.
    Uses combination of regular expressions and
    string parsing to validate date.
    Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
*************************************************/
  var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
 
  //check to see if in correct format
  if(!objRegExp.test(strValue))
    return false; //doesn't match pattern, bad date
  else{
    var strSeparator = strValue.substring(2,3) 
    var arrayDate = strValue.split(strSeparator); 
    //create a lookup for months not equal to Feb.
    var arrayLookup = { '01' : 31,'03' : 31, 
                        '04' : 30,'05' : 31,
                        '06' : 30,'07' : 31,
                        '08' : 31,'09' : 30,
                        '10' : 31,'11' : 30,'12' : 31}
    var intDay = parseInt(arrayDate[1],10); 

    //check if month value and day value agree
    if(arrayLookup[arrayDate[0]] != null) {
      if(intDay <= arrayLookup[arrayDate[0]] && intDay != 0)
        return true; //found in lookup table, good date
    }
    
    //check for February (bugfix 20050322)
    //bugfix  for parseInt kevin
    //bugfix  biss year  O.Jp Voutat
    var intMonth = parseInt(arrayDate[0],10);
    if (intMonth == 2) { 
       var intYear = parseInt(arrayDate[2]);
       if (intDay > 0 && intDay < 29) {
           return true;
       }
       else if (intDay == 29) {
         if ((intYear % 4 == 0) && (intYear % 100 != 0) || 
             (intYear % 400 == 0)) {
              // year div by 4 and ((not div by 100) or div by 400) ->ok
             return true;
         }   
       }
    }
  }  
  return false; //any other values, bad date
}

function validateValue( strValue, strMatchPattern ) {
/************************************************
DESCRIPTION: Validates that a string a matches
  a valid regular expression value.

PARAMETERS:
   strValue - String to be tested for validity
   strMatchPattern - String containing a valid
      regular expression match pattern.

RETURNS:
   True if valid, otherwise false.
*************************************************/
var objRegExp = new RegExp( strMatchPattern);

 //check if string matches pattern
 return objRegExp.test(strValue);
}


function rightTrim( strValue ) {
/************************************************
DESCRIPTION: Trims trailing whitespace chars.

PARAMETERS:
   strValue - String to be trimmed.

RETURNS:
   Source string with right whitespaces removed.
*************************************************/
var objRegExp = /^([\w\W]*)(\b\s*)$/;

      if(objRegExp.test(strValue)) {
       //remove trailing a whitespace characters
       strValue = strValue.replace(objRegExp, '$1');
    }
  return strValue;
}

function leftTrim( strValue ) {
/************************************************
DESCRIPTION: Trims leading whitespace chars.

PARAMETERS:
   strValue - String to be trimmed

RETURNS:
   Source string with left whitespaces removed.
*************************************************/
var objRegExp = /^(\s*)(\b[\w\W]*)$/;

      if(objRegExp.test(strValue)) {
       //remove leading a whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}

function trimAll( strValue ) {
/************************************************
DESCRIPTION: Removes leading and trailing spaces.

PARAMETERS: Source string from which spaces will
  be removed;

RETURNS: Source string with whitespaces removed.
*************************************************/
 var objRegExp = /^(\s*)$/;

    //check for all spaces
    if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '');
       if( strValue.length == 0)
          return strValue;
    }

   //check for leading & trailing spaces
   objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
   if(objRegExp.test(strValue)) {
       //remove leading and trailing whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}

function removeCurrency( strValue ) {
/************************************************
DESCRIPTION: Removes currency formatting from
  source string.

PARAMETERS:
  strValue - Source string from which currency formatting
     will be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /\(/;
  var strMinus = '';

  //check if negative
  if(objRegExp.test(strValue)){
    strMinus = '-';
  }

  objRegExp = /\)|\(|[,]/g;
  strValue = strValue.replace(objRegExp,'');
  if(strValue.indexOf('$') >= 0){
    strValue = strValue.substring(1, strValue.length);
  }
  return strMinus + strValue;
}

function zeroPad(rounded_value, decimal_places) {

    // Convert the number to a string
    var value_string = rounded_value.toString()
    
    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")

    // Is there a decimal point?
    if (decimal_location == -1) {
        
        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0
        
        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    }
    else {

        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }
    
    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length
    
    if (pad_total > 0) {
        
        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0"
        }
    return value_string
}

function leftPad(val, len, padchar)
{
	val = val.toString();
	while(val.length < len)
		val = padchar + val;
	return val;
}	

function addCurrency( strValue ) {
/************************************************
DESCRIPTION: Formats a number as currency.

PARAMETERS:
  strValue - Source string to be formatted

REMARKS: Assumes number passed is a valid
  numeric value in the rounded to 2 decimal
  places.  If not, returns original value.
*************************************************/
  var objRegExp = /-?[0-9]+/;
  var minusRegExp = /^-/;

    if( objRegExp.test(strValue)) {
      strValue = addCommas(strValue);
      return '$' + strValue;
    }
    else
      return strValue;
}

function ensureDecimals(strValue)
{
	var num;
	if (typeof(strValue) == "string")
	{
	    if (strValue == "")
	        num = 0.0;
	    else
    		num = getFloat(strValue);
    }
	else
		num = strValue;
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num % 100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	return ((sign) ? '' : '-') + num + '.' + cents;
}

function addCurrency2( strValue ) {
/************************************************
DESCRIPTION: Formats a number as currency.

PARAMETERS:
  strValue - Source string to be formatted

REMARKS: Assumes number passed is a valid
  numeric value in the rounded to 2 decimal
  places.  If not, returns original value.
*************************************************/
  objRegExp1 = /-?[0-9]+\.[0-9]{2}$/;

    if( objRegExp1.test(strValue)) {
      objRegExp2 = /'^-'/;
      strValue = addCommas(strValue);
      if (objRegExp2.test(strValue)){
        strValue = '(' + strValue.replace(objRegExp1,'') + ')';
      }
      return '$' + strValue;
    }
    else
      return strValue;
}
function removeCommas( strValue ) {
/************************************************
DESCRIPTION: Removes commas from source string.

PARAMETERS:
  strValue - Source string from which commas will
    be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /,/g; //search for commas globally

  //replace all matches with empty strings
  return strValue.replace(objRegExp,'');
}

function addCommas( strValue ) {
/************************************************
DESCRIPTION: Inserts commas into numeric string.

PARAMETERS:
  strValue - source string containing commas.

RETURNS: String modified with comma grouping if
  source was all numeric, otherwise source is
  returned.

REMARKS: Used with integers or numbers with
  2 or less decimal places.
*************************************************/
  var objRegExp  = new RegExp('(-?[0-9]+)([0-9]{3})');

    //check for match to search criteria
    while(objRegExp.test(strValue)) {
       //replace original string with first group match,
       //a comma, then second group match
       strValue = strValue.replace(objRegExp, '$1,$2');
    }
  return strValue;
}

function removeCharacters( strValue, strMatchPattern ) {
/************************************************
DESCRIPTION: Removes characters from a source string
  based upon matches of the supplied pattern.

PARAMETERS:
  strValue - source string containing number.

RETURNS: String modified with characters
  matching search pattern removed

USAGE:  strNoSpaces = removeCharacters( ' sfdf  dfd',
                                '\s*')
*************************************************/
 var objRegExp =  new RegExp( strMatchPattern, 'gi' );

 //replace passed pattern matches with blanks
  return strValue.replace(objRegExp,'');
}

function fmtCurrencyStr(str)
{
	var val = getFloat(str);
	if (val != 0)
		tb.value = addCurrency2(ensureDecimals(val.toString()));
}

function fmtCurrency(tb)
{
	var val = getFloat(tb.value);
	if (val != 0)
		tb.value = addCurrency2(ensureDecimals(val.toString()));
}

function fmtCurrency0(tb)
{
	var val = Math.round(getFloat(tb.value));
	if (val != 0)
		tb.value = addCurrency(val.toString());
}

function SetNodeValue(node, nodeName, nodeValue)
{
	if (node.nodeName == "INPUT" || node.nodeName == "SELECT" || node.nodeName == "TEXTAREA")
	{
		if (node.id && node.id.indexOf(nodeName) > -1)
			node.value = nodeValue;
	}

	if (node.childNodes)
	{
		var i;
		for(i = 0; i < node.childNodes.length; i++)
			SetNodeValue(node.childNodes[i], nodeName, nodeValue);
	}
}

function GetNodeValue(node, nodeName)
{
	if (node.nodeName == "INPUT" || node.nodeName == "SELECT" || node.nodeName == "TEXTAREA")
	{
		if (node.id && node.id.indexOf(nodeName) > -1)
			return node.value;
	}

	if (node.childNodes)
	{
		var i;
		for(i = 0; i < node.childNodes.length; i++)
		{
			val = GetNodeValue(node.childNodes[i], nodeName);
			if (val)
				return val;
		}
	}
	return null;
}

function GetNodeTagValue(node, tagName, nodeName)
{
	node = FindNodeTag(node, tagName, nodeName);
	if (node && node.id && node.id.indexOf(nodeName) > -1)
		return node.value;
	else
		return null;
}

function FindNodeTag(node, tagName, nodeName)
{
	var els;
	var i;
	if (node.nodeName == tagName && node.id && node.id.indexOf(nodeName) > -1)
		return node;
	
	if (node.getElementsByTagName)
	{
		els = node.getElementsByTagName(tagName);
		for(i = 0; i < els.length; i++)
		{
			var node = els[i];
			if (node.id && node.id.indexOf(nodeName) > -1)
				return node;
		}
	}
	else
	{
		for(i = 0; i < node.childNodes.length; i++)
		{
			var foundNode = FindNode(node.childNodes[i], nodeName);
			if (foundNode)
				return foundNode;
		}

	}
	return null;
}

function FindNode(node, nodeName)
{
	var foundNode = document.getElementById(nodeName);
	if (foundNode)
		return foundNode;
		
	if (node.id && node.id.indexOf(nodeName) > -1)
		return node;

	if (node.childNodes)
	{
		var i;
		for(i = 0; i < node.childNodes.length; i++)
		{
			var foundNode = FindNode(node.childNodes[i], nodeName);
			if (foundNode)
				return foundNode;
		}
	}
	return null;
}

function FindTag(node, tagName)
{
	if (node.tagName == tagName)
		return node;

	if (node.childNodes)
	{
		var i;
		for(i = 0; i < node.childNodes.length; i++)
		{
			var foundNode = FindTag(node.childNodes[i], tagName);
			if (foundNode)
				return foundNode;
		}
	}
	return null;
}

function GetTable(node) {
    var row = node;
    while (row.nodeName != "TABLE")
        row = row.parentNode;
    return row;
}

function GetRow(node)

{
	var row = node;
	while(row.nodeName != "TR")
		row = row.parentNode;
	return row;
}	

function GetCell(node)
{
	var row = node;
	while(row.nodeName != "TD")
		row = row.parentNode;
	return row;
}	

function setAttr(oNode, name, value)
{
	// In IE when nodes are cloned the items in the attribute list are references to the original list
	if (value == -1 && oNode.attributes[name])
		oNode.attributes.removeNamedItem(name);
		
	if (oNode.attributes[name])
		oNode.attributes[name].value = value;
	else
	{
		var att = document.createAttribute(name);
		att.value = value;
		oNode.attributes.setNamedItem(att);
	}
}

function getAttr(oNode, name, defaultValue)
{
	var val;
	if (oNode.attributes[name])
		val = oNode.attributes[name].value;
	else
		val = defaultValue;
	if (val == "")
		val = defaultValue;
	return val;
}

function GetLabel(node, ctrl)
{
	if (node.tagName == "LABEL" && node.htmlFor == ctrl.id)
		return node;
	if (node.childNodes)
	{
		var i;
		for(i = 0; i < node.childNodes.length; i++)
		{
			val = GetLabel(node.childNodes[i], ctrl);
			if (val)
				return val;
		}
	}
	return null;
}

function SetReadOnly(node, readOnly)
{
	if ((node.nodeName == "INPUT" || node.nodeName == "SELECT" || node.nodeName == "TEXTAREA") && node.type != "button")
	{
		if (node.nodeName == "SELECT")
			node.disabled = readOnly;
		else
			node.readOnly = readOnly;
		//node.className = readOnly ? readOnlyClass : editClass;
	}

	if (node.childNodes)
	{
		var i;
		for(i = 0; i < node.childNodes.length; i++)
			SetReadOnly(node.childNodes[i], readOnly);
	}
}

function SetNodeDisplay(node, tag, disp)
{
	if (node.nodeName == tag)
	{
		node.style.display = disp;
	}

	if (node.childNodes)
	{
		var i;
		for(i = 0; i < node.childNodes.length; i++)
			SetNodeDisplay(node.childNodes[i], tag, disp);
	}
}

function countchars(tb, ccName, maxLength)
{
	if (tb.value.length < maxLength)	
	{
		var cc = document.getElementById(ccName);
		cc.innerHTML = maxLength - tb.value.length + " characters remaining"; 
	}
	else
	{
		alert("Maximum number of characters has been reached");
		tb.value = tb.value.substr(0, maxLength);
	}
}

function hideshowcovered(obj, doc, showhide)
{
	if (!doc.all)
		return;
	
	var version = parseFloat(navigator.appVersion.split("MSIE")[1]);
	if (version >= 7)
		return;

	function getVisib(obj){
		var value = obj.style.visibility;
		if (!value) {
			if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") { // Gecko, W3C
				if (!Calendar.is_khtml)
					value = document.defaultView.
						getComputedStyle(obj, "").getPropertyValue("visibility");
				else
					value = '';
			} else if (obj.currentStyle) { // IE
				value = obj.currentStyle.visibility;
			} else
				value = '';
		}
		return value;
	};

	var tags = new Array("applet", "iframe", "select");
	var el = obj;

	var p = getPageXY(el);
	var EX1 = p.x;
	var EX2 = el.offsetWidth + EX1;
	var EY1 = p.y;
	var EY2 = el.offsetHeight + EY1;

	for (var k = tags.length; k > 0; ) {
		var ar = doc.getElementsByTagName(tags[--k]);
		var cc = null;

		for (var i = ar.length; i > 0;) {
			cc = ar[--i];

			p = getPageXY(cc);
			var CX1 = p.x;
			var CX2 = cc.offsetWidth + CX1;
			var CY1 = p.y;
			var CY2 = cc.offsetHeight + CY1;

			if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
				if (!cc.__msh_save_visibility) {
					cc.__msh_save_visibility = getVisib(cc);
				}
				cc.style.visibility = cc.__msh_save_visibility;
			} else {
				if (!cc.__msh_save_visibility) {
					cc.__msh_save_visibility = getVisib(cc);
				}
				cc.style.visibility = showhide;
			}
		}
	}
}

function getPageXY(elm)
{
  var point = { x: 0, y: 0 };
  while (elm)
  {
    point.x += elm.offsetLeft;
    point.y += elm.offsetTop;
    elm = elm.offsetParent;
  }
  return point;
}

function setPageXY(elm, x, y)
{
  var parentXY = {x: 0, y: 0 };

  if (elm.offsetParent)
  {
    parentXY = getPageXY(elm.offsetParent);
  }

  elm.style.left = (x - parentXY.x) + 'px';
  elm.style.top  = (y - parentXY.y) + 'px';
}
function elementContains(elmOuter, elmInner)
{
  while (elmInner && elmInner != elmOuter)
  {
    elmInner = elmInner.parentNode;
  }
  if (elmInner == elmOuter)
  {
    return true;
  }
  return false;
}

function getLabelForId(id) {
 var label, labels = document.getElementsByTagName('label');
 for (var i = 0; (label = labels[i]); i++) {
   if (label.htmlFor == id) {
     return label;
   }
 }
 return false;
} 

var debugWin = null;

function onDebugClose()
{
	//alert("closing"); 
	debugWin = null; 
}

function getDebugDoc()
{
	if (debugWin)
	{
		try
		{
			var testDoc = debugWin.document;
		}
		catch(e)
		{
			alert(e);
			debugWin = null;
		}
	}
	if (!debugWin)
	{
		attr = 'left=0,top=0,height=' + 600 + ',width=' + 600 + ',menubar=no,scrollbars=yes,status=yes,toolbar=no,location=no,resizeable=yes';
		debugWin = window.open("#",'popup', attr);
		debugWin.onunload = onDebugClose;
		debugWin.document.writeln("<html><body style='font-family:verdana; font-size:8pt;'>");

	}
	var doc = debugWin.document;
	return doc;
}

function writeDebugString(str)
{
	var doc = getDebugDoc();
	doc.writeln(str);
}

function writeDebugObject(obj)
{
	var doc = getDebugDoc();
	
	doc.writeln("<table style='font-family:verdana; font-size:8pt;'>");
	for(var i in obj)
	{
		doc.writeln("<tr><td>" + i + "</td><td>=</td><td>" + obj[i] + "</td></tr>");
	}
	doc.writeln("</table>");
	doc.writeln("<hr>");
}
function disableAnchor(obj, disable)
{
  if(disable)
  {
    var href = obj.getAttribute("href");
    if(href && href != "" && href != null)
    {
       obj.setAttribute('href_bak', href);
    }
    obj.removeAttribute('href');
    obj.style.color="gray";
  }
  else
  {
	if (obj.attributes['href_bak'])
	{
		obj.setAttribute('href', obj.attributes['href_bak'].nodeValue);
		obj.style.color="black";
	}
  }
}

function disableChildControls(obj, disable)
{
	var els = obj.getElementsByTagName("INPUT");
	for(var i = 0; i < els.length; i++)
		els[i].disabled = disable;
	els = obj.getElementsByTagName("SELECT");
	for(i = 0; i < els.length; i++)
		els[i].disabled = disable;
	els = obj.getElementsByTagName("A");
	for(i = 0; i < els.length; i++)
		disableAnchor(els[i], disable);
}

function disableControl(ctrl, disable)
{
	ctrl.disabled = disable;
	// Fix Anthem checkboxes surrounding SPAN element also disabled if checkbox is disabled at page load.
	if (!disable && ctrl.parentNode && ctrl.parentNode.tagName == 'SPAN')
		ctrl.parentNode.disabled = diable;
}

function Anthem_Error(result) {
	if (result.error)
		alert(result.error);
}

function getUniqueValues(inArray)
{
	var hash = new Object();
	for (j = 0; j < inArray.length; j++) 
	{
		hash[inArray[j]] = hash[inArray[j]] + 1;
	}
	var outArray = new Array();
	for (value in hash) 
	{
		outArray.push(value)
	};
	return outArray;
}

function openCenteredWindow(name, url, w, h, showBrowserControls)
{
    var left = (screen.width - w) / 2;
    var top = (screen.height - h) / 2;
    if (showBrowserControls)
        var args = 'location=yes,menubar=yes,titlebar=yes,toolbar=yes,scrollbars=yes,status=yes,height=' + h + ',width=' + w + ',left=' + left + ',top=' + top;
    else
        var args = 'location=no,menubar=no,titlebar=no,toolbar=no,scrollbars=no,status=no,height=' + h + ',width=' + w + ',left=' + left + ',top=' + top;
    return window.open(url, name, args);
}

function openCenteredWindowOpts(name, url, w, h, options) {
    var left = (screen.width - w) / 2;
    var top = (screen.height - h) / 2;
    var args = options + ',height=' + h + ',width=' + w + ',left=' + left + ',top=' + top;
    return window.open(url, name, args);
}

function selectItemCallBack(result, context)
{
	if (result.error) 
		alert(result.error);
	else
	{
		if (context && context.row)
		{
			clearSelectedRow(context.row.parentNode)
			context.row.className += " gridSelectedRow";
		}
	}
}

function clearSelectedRow(tbody)
{
	for(var i = 0; tbody && i < tbody.rows.length; i++)
	{
		var row = tbody.rows[i];
		if (row.className.indexOf("gridSelectedRow") > -1)
		{
			row.className = row.className.replace("gridSelectedRow", "");
			return row;
		}
	}
}

function showModalShadow(elID, waitCursor)
{
	var div = document.createElement("DIV");
	var tbl = document.getElementById(elID);
	div.style.position = 'absolute';
	var pt = getPageXY(tbl);
	div.style.left = '0px';
	div.style.top = '0px';
	div.style.width = '100%';
	div.style.height = '100%';
	div.className = "modal";
	div.style.zIndex = "500";
	div.id = "divModal";
	if (waitCursor)
	{
		var img = document.createElement("IMG");
		div.appendChild(img);
		img.src = window.applicationPath + "images/ajax-loader.gif"
		img.style.position = 'absolute';
		img.style.top = tbl.offsetHeight / 2 + "px";
		img.style.left = tbl.offsetWidth / 2 + "px";
		img.style.zIndex = "501";
	}
	document.body.appendChild(div);
}

function centerDialog(elID) {
	var el = document.getElementById(elID);
	el.style.marginLeft = -el.offsetWidth / 2 + 'px';
	el.style.marginTop = -el.offsetHeight / 2 + 'px';
}

function clearModalShadow()
{
	var div = document.getElementById("divModal");
	if (div)
		div.parentNode.removeChild(div);
}
function removeClass(obj, className)
{
	obj.className = obj.className.replace(className, "");
	obj.className = obj.className.replace("  ", " ");
}

function addClass(obj, className)
{
	if (obj.className.indexOf(className) == -1)
		obj.className += " " + className;
}

function uncheckOthers(tableID, rb) {
    var els = document.getElementById(tableID).getElementsByTagName('INPUT');
    for (var i = 0; i < els.length; i++) {
        var el = els[i];
        if (el.type == "radio" && el != rb)
            el.checked = false
    }
}

// Simulates PHP's date function
Date.prototype.format = function(format) {
    var returnStr = '';
    var replace = Date.replaceChars;
    for (var i = 0; i < format.length; i++) {
        var curChar = format.charAt(i);
        if (replace[curChar]) {
            returnStr += replace[curChar].call(this);
        } else {
            returnStr += curChar;
        }
    }
    return returnStr;
};
Date.replaceChars = {
    shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
    longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],

    // Day
    d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
    D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
    j: function() { return this.getDate(); },
    l: function() { return Date.replaceChars.longDays[this.getDay()]; },
    N: function() { return this.getDay() + 1; },
    S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
    w: function() { return this.getDay(); },
    z: function() { return "Not Yet Supported"; },
    // Week
    W: function() { return "Not Yet Supported"; },
    // Month
    F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
    m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
    M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
    n: function() { return this.getMonth() + 1; },
    t: function() { return "Not Yet Supported"; },
    // Year
    L: function() { return "Not Yet Supported"; },
    o: function() { return "Not Supported"; },
    Y: function() { return this.getFullYear(); },
    y: function() { return ('' + this.getFullYear()).substr(2); },
    // Time
    a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
    A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
    B: function() { return "Not Yet Supported"; },
    g: function() { return this.getHours() % 12 || 12; },
    G: function() { return this.getHours(); },
    h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
    H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
    i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
    s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
    // Timezone
    e: function() { return "Not Yet Supported"; },
    I: function() { return "Not Supported"; },
    O: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00'; },
    T: function() { var m = this.getMonth(); this.setMonth(0); var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1'); this.setMonth(m); return result; },
    Z: function() { return -this.getTimezoneOffset() * 60; },
    // Full Date/Time
    c: function() { return "Not Yet Supported"; },
    r: function() { return this.toString(); },
    U: function() { return this.getTime() / 1000; }
};

function SizeWindowToContents(hmargin, vmargin)
{
    var DisplayDiv = document.body;
    var nAvailHeight = screen.availHeight;
    var nAvailWidth = screen.availWidth;
    var nInitialHeight = window.document.body.clientHeight;
    var nInitialWidth = window.document.body.clientWidth;
    
    //var nDisplayHeight = DisplayDiv.clientHeight;
    //var nDisplayWidth = DisplayDiv.clientWidth;
    var nDisplayHeight = DisplayDiv.offsetHeight;
    var nDisplayWidth = DisplayDiv.offsetWidth;

    var ChromeWidth = 0;
    var ChromeHeight = 0;
    // If this value is not null, then we are dealing with a netscape type browser
    if(self.innerHeight != null)
    {
          ChromeWidth = self.outerWidth - self.innerWidth;
          ChromeHeight = self.outerHeight - self.innerHeight;
          // Add 20 to make sure there is enough room for Netscapes scroll bars
          ChromeHeight +=20;
          ChromeWidth +=20;
    
    }
    else
    {
          // Resize the window to a known value
          window.resizeTo( 640, 480);
          // Now compute how big the chrome is
          ChromeWidth = 640 - window.document.body.clientWidth;
          ChromeHeight = 480 - window.document.body.clientHeight;
    }

    
    // Make sure that the window isn't bigger than the screen size
    var nNewWindowHeight = Math.min( nAvailHeight, nDisplayHeight+ChromeHeight  ) + vmargin;
    var nNewWindowWidth = Math.min( nAvailWidth, nDisplayWidth+ChromeWidth  ) + hmargin;
    
    
    window.resizeTo( nNewWindowWidth, nNewWindowHeight );
}
                  
                        

