﻿function el(id)
{
	return document.getElementById(id);
}

// 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;
	}
}

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, tagName, 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 monthArray = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
var dayArray = new Array("Sunday", "Monday", "Tuesday","Wednesday","Thursday", "Friday","Saturday");

function formatDateWithDay(dt)
{
	var strDate = dayArray[dt.getDay()].substr(0, 3) + " " + dt.getDate() + " " + monthArray[dt.getMonth()] + " " + dt.getFullYear();
	return (strDate);
}

function formatDate(dt)
{
	var strDate = dt.getDate() + " " + monthArray[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 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")
		num = parseFloat(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 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 GetRow(node)
{
	var row = node;
	while(row.nodeName != "TR")
		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;
} 

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);
}


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 Viewport()
{ 
	var vp = new Object();
	vp.windowX = (document.documentElement && document.documentElement.clientWidth) || window.innerWidth || self.innerWidth || document.body.clientWidth; 
	vp.windowY = (document.documentElement && document.documentElement.clientHeight) || window.innerHeight || self.innerHeight || document.body.clientHeight; 
	vp.scrollX = (document.documentElement && document.documentElement.scrollLeft) || window.pageXOffset || self.pageXOffset || document.body.scrollLeft; 
	vp.scrollY = (document.documentElement && document.documentElement.scrollTop) || window.pageYOffset || self.pageYOffset || document.body.scrollTop; 
	vp.pageX = (document.documentElement && document.documentElement.scrollWidth) ? document.documentElement.scrollWidth : (document.body.scrollWidth > document.body.offsetWidth) ? document.body.scrollWidth : document.body.offsetWidth; 
	vp.pageY = (document.documentElement && document.documentElement.scrollHeight) ? document.documentElement.scrollHeight : (document.body.scrollHeight > document.body.offsetHeight) ? document.body.scrollHeight : document.body.offsetHeight;
	return vp;
}

function iFrameCloseHelp()
{
	document.innerHTML = "";
	//adjustIFrameSize(window);
	parent.hideHelp();
}

function showAccountHelp(helpLinkID, accountID)
{
	var options = 'toolbar=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,modal=yes';
			
	openCenteredWindow('help.aspx?acc=' + accountID, 'hlp', 430, 450, options);
}

function showHelp(helpLinkID, helpFieldName)
{
	var options = 'toolbar=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,modal=yes';
			
	openCenteredWindow('help.aspx?hfn=' + helpFieldName, 'hlp', 430, 450, options);

//	var lnk = el(helpLinkID);
//	var div = el("divHelp");
//	
//	if (div.style.display == "")
//	{
//		hideHelp();
//	}
//	else
//	{
////		var xy = getPageXY(lnk);
//		var y;
//		var vp = Viewport();

//		div.style.visibility = "hidden";
//		div.style.display=""; // So the div's offsetHeight & offsetWidth get initialized
//		var h = lnk.offsetHeight + 3;
//		if (xy.y + h + div.offsetHeight > vp.windowY && xy.y - div.offsetHeight >= 0)
//			y = xy.y - h;
//		else
//			y = xy.y + lnk.offsetHeight;

//		if (xy.x + div.offsetWidth > vp.windowX)
//			x = vp.windowX - div.offsetWidth;
//		else
//			x = xy.x + lnk.offsetWidth;
//		
		
//		div.style.position="absolute";
//		div.style.top = y + "px";
//		div.style.left = x + "px";

//		var frm = el("ifrHelp");
//		frm.src = "help.aspx?hfn=" + helpFieldName;
//		div.style.visibility = "visible";
//	}
}

function hideHelp(doc)
{
	var div = el("divHelp");
	
	div.style.display="none";

}

function confirmDelete()
{
	return confirm("Are you sure you want to delete this row?");
}

function adjustIFrameSize(iframeWindow) 
{
	var iframeElement, height, width;
	if (iframeWindow.document.height) 
	{
		iframeElement = document.getElementById(iframeWindow.name);
		height = iframeWindow.document.height + 18;
		width = iframeWindow.document.width + 18;
	}
	else if (document.all) 
	{
		iframeElement = document.all[iframeWindow.name];
		if (iframeWindow.document.compatMode &&
			iframeWindow.document.compatMode != 'BackCompat') 
		{
			height = iframeWindow.document.documentElement.scrollHeight + 18;
			width = iframeWindow.document.documentElement.scrollWidth + 18;
		}
		else 
		{
			height = iframeWindow.document.body.scrollHeight + 18;
			width = iframeWindow.document.body.scrollWidth + 18;
		}
	}

	if (width < 400)
		width = 400;
	if (height < 250)
		height = 250;
	iframeElement.style.height = height + 'px';
	iframeElement.style.width = width + 'px';
/*   	var div = document.getElementById('divHelp');
   	var posy = div.srcObjPosy;
	if (posy + div.offsetHeight > document.body.offsetHeight && posy > (document.body.offsetHeight / 2))
		posy -= div.offsetHeight;
	
	if (document.documentElement && document.documentElement.scrollTop)
    	posy += document.documentElement.scrollTop; // IE6 no doctype
    else if (document.body)
    	posy += document.body.scrollTop // IE5, Mozilla, IE6 with DOCTYPE
	
	if (posy < 0)
	    posy = 0;
	div.style.top = posy + 'px';
*/
}

function selectItemCallBack(result, row)
{
	if (result.error) 
		alert(result.error);
	else
	{
		if (row)
		{
			clearSelectedRow(row.parentNode)
			row.className += " gridSelectedRow";
		}
	}
}

function clearSelectedRow(tbody)
{
	for(var i = 0; 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 IsTabKey(e)
{
    var retVal = false;
    var keycode = 0;
    if ((typeof(window.event) != "undefined") && (window.event != null))
    {
        keycode = window.event.keyCode;
    }
    else if ((typeof(e) != "undefined") && (e != null))
    {
        keycode = e.which;
    }
    if (keycode == 9)
    {
        retVal = true;
    }
    return retVal;
}

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 copySelect(src, dest, row, id)
{	
	var removeSplit = row.attributes["removeSplit"].value == "true";
	var j = 0;
	for(var i = 0; i < src.options.length; i++)
	{
		var srcopt = src.options[i];
		if (srcopt.text != "Split" || !removeSplit)
			dest.options[j++] = new Option(srcopt.text, srcopt.value);
	}
	dest.selectedIndex = row.attributes[id].value;
	
//	var saveId = src.id;
//	src.id = dest.id;
//	src.disabled = row.attributes[id + "_Enabled"].value == "false";
//	// assumes anthem dropdown lists - surrounded by a SPAN
//	src.selectedIndex = row.attributes[id].value;
//	dest.parentNode.innerHTML = src.parentNode.innerHTML;
//	dest.onchange = new Function("srcField", "onTransactionChanged(srcField)");
//	
//	src.id = saveId;
}

function populateSelects(tbl, template, id)
{
	if (tbl)
	{
		if (!tbl.rows)
			tbl = tbl.tBodies[0];
		for(var i = 1; i < tbl.rows.length; i++)
		{
			var dest = FindNodeTag(tbl.rows[i], "SELECT", id);
			if (dest)
				copySelect(template, dest, tbl.rows[i], id);
		}
	}
}

function focusNextFormField(inp, idx)
{
	var coll=document.forms[0].elements;
	for(var t=0;t<2;t++)
	{
		for(i=0;i<coll.length;i++){
			if(idx!=""){
				if(parseInt(coll[i].getAttribute("tabindex"))==idx+1 && !coll[i].disabled && coll[i].type != "hidden"){
				coll[i].focus();
			}
			}else{
				if(inp==coll[i].name){
					nextel=i+1;
					if(coll[nextel] && !coll[nextel].disabled && coll[nextel].type != "hidden"){
						coll[nextel].focus();
						return
					}
					else if (nextel < coll.length)
						inp=coll[nextel].name;
					else
						inp=coll[0].name;
				}
			}
		}
		if (idx != "")
			break;
			
		idx = "";
	}
}

function setEnterTrap()
{
	var coll=document.forms[0].elements;

	if(document.all){
		document.attachEvent("onkeydown",trapBackspace);
	}else{
		document.addEventListener("keydown",trapBackspace,false);
	}
			
	for(i=0;i<coll.length;i++){
		if(document.all){
			coll[i].attachEvent("onkeypress",tabOnEnter);
			coll[i].attachEvent("onkeydown",trapBackspace);
		}else{
			coll[i].addEventListener("keypress",tabOnEnter,false);
			coll[i].addEventListener("keydown",trapBackspace,false);
		}
	}
}

function trapBackspace(e)
{
	if(document.all){
		key=event.keyCode;
		inp=event.srcElement.name;
		t=event.srcElement.type;
		idx=parseInt(event.srcElement.getAttribute("tabindex"));
	}else{
		key=e.which;
		inp=e.target.name;
		t=e.target.type;
		idx=parseInt(e.target.getAttribute("tabindex"));
	}
    
    if (key==8 && t != 'text' && t != 'password') // Disable backspace from navigating to a previous page
    {
   		if(document.all){
			event.cancelBubble=true;
		}else{
		    e.cancelBubble=true;
			e.stopPropagation();
		}
        return false;
    }
}
	
function tabOnEnter(e){
	if(document.all){
		key=event.keyCode;
		inp=event.srcElement.name;
		t=event.srcElement.type;
		idx=parseInt(event.srcElement.getAttribute("tabindex"));
	}else{
		key=e.which;
		inp=e.target.name;
		t=e.target.type;
		idx=parseInt(e.target.getAttribute("tabindex"));
	}
    
    trapBackspace(e);   // Opera needs this in onkeypress
       
	if(key==13){
		if(document.all){
			event.cancelBubble=true;
		}else{
			e.stopPropagation();
		}
		
		focusNextFormField(inp, idx);
		return false;
	}
}


function getPageSizeWithScroll()
{     
	if (window.innerHeight && window.scrollMaxY) 
	{// Firefox         
		yWithScroll = window.innerHeight + window.scrollMaxY;         
		xWithScroll = window.innerWidth + window.scrollMaxX;     
	} 
	else if (document.body.scrollHeight > document.body.offsetHeight)
	{ // all but Explorer Mac         
		yWithScroll = document.body.scrollHeight;         
		xWithScroll = document.body.scrollWidth;     
	} 
	else 
	{ // works in Explorer 6 Strict, Mozilla (not FF) and Safari        
		yWithScroll = document.body.offsetHeight;         
		xWithScroll = document.body.offsetWidth;       
	}     
	var pt = new Object();
	pt.x = xWithScroll;
	pt.y = yWithScroll;
	return pt;
} 

function selectItem(funcName, row, id)
{
	Anthem_InvokePageMethod(funName, [id], selectItemCallBack, row);
}

function selectItemCallBack(result, row)
{
	if (result.error) 
		alert(result.error);
	else
	{
		if (row)
		{
			clearSelectedRow(row.parentNode)
			row.className += " gridSelectedRow";
		}
	}
}

function clearSelectedRow(tbody)
{
	for(var i = 0; i < tbody.rows.length; i++)
	{
		var row = tbody.rows[i];
		if (row.className.indexOf("gridSelectedRow") > -1)
		{
			row.className = row.className.replace("gridSelectedRow", "");
			return row;
		}
	}
}