// 2009.07.15 DSL setRadio, getRadio
// 2009.08.26 DSL added return false to openhelpWindow - bug in IE
// 2009.09.16 DSL added tmrKeepAlive, session_timer_reset
var wndEmail;
function closeEmailWindow() {
	if (wndEmail) {
		wndEmail.close();
	}
}
function clickSendEmailFax(id, blnFax) {
	var strURL;

	strURL = "../common/email.asp?id=" + id;
	if (blnFax) {
		strURL += "&method=F&fax_type=EFS";
	}
	else {
		strURL += "&method=E";
	}

	if (wndEmail && !wndEmail.closed) {
		wndEmail.focus();
	}
	else {
		wndEmail = window.open(strURL,"wndEmail","statusbar, scrollbars, resizable");
	}
}

var blnCheckForEditsBeforeUnload = false;
function checkForEditsBeforeUnload() {
	var frm, obj, blnChanged = false, blnTemp, strTemp, objTemp;

	for (var i = 0; i < document.forms.length && !blnChanged && blnCheckForEditsBeforeUnload; ++i) {
		frm = document.forms[i];
		for (var j = 0; j < frm.elements.length && !blnChanged; ++j) {
			obj = frm.elements[j];
			switch(obj.type) {
				case "checkbox":
					if (obj.checked != obj.defaultChecked) {
						obj.focus();
						blnChanged = true;
					}
					break;
				case "password":
				case "file":
				case "text":
				case "textarea":
					if (obj.value != obj.defaultValue) {
						obj.focus();
						obj.select();
						blnChanged = true;
					}
					break;
				case "select-one":
					blnTemp = false;
					//have to check if any were selected to begin with
					//this is to workaround no "default" selected
					//since the browser auto assigns the first option as being selected
					for (var k = 0; k < obj.options.length; ++k) {
						if (obj.options[k].defaultSelected) {
							blnTemp = true;
						}
					}
					//since no default selection, make the first option the default.
					if (!blnTemp) {
						obj.options[0].defaultSelected = true;
						blnTemp = true;
					}
					for (var k = 0; k < obj.options.length && blnTemp; ++k) {
						if (obj.options[k].selected != obj.options[k].defaultSelected) {
							obj.focus();
							blnChanged = true;
						}
					}
					break;
				case "select-multiple":
					for (var k = 0; k < obj.options.length; ++k) {
						if (obj.options[k].selected != obj.options[k].defaultSelected) {
							obj.focus();
							blnChanged = true;
						}
					}
					break;
				case "radio":
					strTemp = "";
					//have to check if multiple values were checked by default
					//if multiple values are selected, the last one will be the "default" checked
					for (var k = 0; k < frm.elements.length; ++k) {
						objTemp = frm.elements[k];
						if (objTemp.name == obj.name) {
							if (objTemp.defaultChecked) {
								strTemp = objTemp.value;
							}
						}
					}
					//if checked and the value doesn't match the default, the value was changed.
					if (obj.checked && obj.value != strTemp) {
						obj.focus();
						blnChanged = true;
					}
					break;
				case "hidden":
				case "submit":
				case "reset":
				case "button":
					break;
				default:
					alert(obj.type);
			}
		}
	}

	if (blnChanged) {
		return "You have made changes to the page that have not been posted."
	}
}

function isValidCode(str) {
	var re = /^[a-zA-Z0-9_]*$/;

	if (str != "" && str.search(re) == -1)
		return false;
	return true;
}

function validateCode(str) {
	if (!isValidCode(str)) {
		alert("Error: This field may only contain letters, numbers, or underscores.");
		return false;
	}
	return true;
}
	

function setStatus(msg) {
		 status = msg
		 return true
} 

function upperThis(field) {
		 field.value = field.value.toUpperCase()
}

var wndCalendar
function checkCalendarWindow(strForm, strField, strCall) {
 closeCalendarWindow();
 openCalendarWindow(strForm, strField, strCall);
 return false;
}

function openCalendarWindow(strForm, strField, strCall) {
 var objField = eval("document." + strForm + "." + strField);
 var strDate = objField.value;

 var str = "../utilities/calendar.asp?form=" + strForm + "&field=" + strField + "&date=" + strDate + "&call=" + strCall
 wndCalendar = window.open(str, "wndCalendar", "resizable=no,scrollbars=no,width=300,height=320");
}

function closeCalendarWindow() {
 if (wndCalendar)
  wndCalendar.close();
}

function format_the_number(expr, decplaces) {
		 var str = "" + Math.round(eval(expr) * Math.pow(10,decplaces))
		 while (str.length <= decplaces) {
		 	   str = "0" + str
		 }
		 var decpoint = str.length - decplaces
		 return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
}

var theHelpWindow
function closehelpWindow() {
		 if (theHelpWindow)	 {
		 	theHelpWindow.close()
		 }
}

function openhelpWindow(view_str) {
	closehelpWindow();
	theHelpWindow = window.open(view_str, "subHelp", "height=1200, width=1500, scrollbars, resizable");
	theHelpWindow.focus();
	return false;
}
function changeStyle(obj, bgColor, bdColor, ftColor) {
   	if (document.getElementById) {
		obj.style.backgroundColor = bgColor;
		obj.style.borderColor = bdColor;
		obj.style.color = ftColor;
	}
}	

function chooseISSILink(view_str) {
		 self.location.href = view_str
}

function checkCard(card_str) {
		var ok = "Y"	
		var the_num = 0 
		var the_f = 1
		var the_nstr = ""
		var chr2 = "" 	
		var the_total  = 0
		var sz = card_str.length
		if ((sz < 13) || (sz > 20)) {
			ok = "N"
			alert("Error: Invalid Card Number.")
		}

		if (card_str.indexOf("x") < 0 && ok == "Y") {
			var chr =""
			for (var i = (sz-1); i >= 0; i--) {
				chr =  card_str.charAt(i)				

				if (isNaN(chr)) {
					alert("Error: Invalid Card Number. All characters in the credit card number must be numeric.")
					ok = "N"
					break
				}
				if (ok == "Y") {
					the_num = parseFloat(chr) * parseFloat(the_f)
				
					the_nstr = String(the_num)
				
					n_sz = the_nstr.length


					for (var j = 0; j < n_sz; j++) {
						if (j > 1) { break };
						chr2 =  the_nstr.charAt(j)
						the_total = parseFloat(the_total) + parseFloat(chr2) 
					}
					if (parseFloat(the_f) == 1) {
						the_f = 2
					} else {
						the_f = 1
					}
				}

			}
			if (ok == "Y") {
				the_total = parseFloat(the_total/10)

				var the_answer = (parseFloat(the_total ) - parseInt(the_total))

				if ((parseFloat(the_total ) - parseInt(the_total )) != 0) {
//					alert("Error: Invalid Card Number. " + String(the_answer))
					alert("Error: Invalid Card Number. ")
					ok = "N";
				}
				
			}

		}
		

		if (ok == "Y") {
		return true
		} else {
		return false
		}
}
function locktrueie(myform){
	myform.ie.checked = true;
}
function lockfalsenet(myform){
	myform.nets.checked = true;
}
function goToURL(str) { 
	try {
		window.location = str;
	}
	catch(e) {
	}
}

function nochange(mycheckbox){
	if (mycheckbox.checked == true){ 
		mycheckbox.checked = false;
	}
	else {
		mycheckbox.checked = true;
	}
} 

//call traverse_html_nodes(document.body)
function traverse_html_nodes(node, func) {
	func(node);

	for (var i = 0; i < node.childNodes.length ; ++i)
		traverse_html_nodes(node.childNodes[i], func);
}

function onload_check_all_elements() {
	mod_all_textboxes();

	check_disabled("input");
	check_disabled("textarea");
	check_disabled("select");
}

function check_disabled(strTag) {
	var ary = document.getElementsByTagName(strTag);

	for (var i = 0; i < ary.length; ++i) {
		// check disabled attribute
		if (ary[i].disabled) {
			ary[i].className += " disabled";
		}

		bln = (typeof ary[i].ondblclick == "function");
		if(bln) {
			ary[i].className += " dblclick";
		}
	}
}

function mod_all_textboxes(){

	var ary = document.getElementsByTagName("textarea"), bln;
	var old_onfocus;

	//loop all textarea tags
	for (var i=0;i<ary.length;i++){
		// check readonly attribute
		if (ary[i].hasAttribute)
			bln = ary[i].hasAttribute("readonly");
		else
			bln = ary[i].getAttribute("readonly");

		if(bln) {
			make_readonly(ary[i]);
		}
	}

	ary = document.getElementsByTagName("input");

	//loop all input tags
	for (var i=0;i<ary.length;i++){
		// check readonly attribute
		if (ary[i].hasAttribute)
			bln = ary[i].hasAttribute("readonly");
		else
			bln = ary[i].getAttribute("readonly");

		if(bln) {
			make_readonly(ary[i]);
		}

		//check for a masktype attribute
		strMaskType = ary[i].getAttribute("masktype");
		if (strMaskType) {
			strId = get_element_id(ary[i]);
			switch(strMaskType.toLowerCase()) {
				case "date":
					$("#" + strId).unmask().mask("99/99/9999", {placeholder:"?"});
					break;
				case "time":
					$("#" + strId).unmask().mask("99:99", {placeholder:"?"});
					break;
				case "creditcard":
					$("#" + strId).unmask().mask("9999 9999 9999 9999", {placeholder:"?"});
					break;
				case "ssn":
					$("#" + strId).unmask().mask("999-99-9999", {placeholder:"?"});
					break;
				case "year":
					$("#" + strId).unmask().mask("9999", {placeholder:"?"});
					break;
				case "phone":
					strCountryId = get_phone_attribute(ary[i], "country");
					strStateId = get_phone_attribute(ary[i], "state");

					//setup onchange function for country and state, to mask or unmask based on selections
					if (strCountryId) {
						eval('$("#" + strCountryId).change(function() {check_phone_masks("' + strId + '", "' + strCountryId + '", "' + strStateId + '");});');
					}
					if (strStateId) {
						eval('$("#" + strStateId).change(function() {check_phone_masks("' + strId + '", "' + strCountryId + '", "' + strStateId + '");});');
					}

					//setup masking / unmasking onload
					check_phone_masks(strId, strCountryId, strStateId);

					break;
				case "zipcode":
					strCountryId = get_phone_attribute(ary[i], "country");

					//setup onchange function for country, to mask or unmask based on selections
					if (strCountryId) {
						eval('$("#" + strCountryId).change(function() {check_zip_masks("' + strId + '", "' + strCountryId + '");});');
					}

					//setup masking / unmasking onload
					check_zip_masks(strId, strCountryId);

					break;
				default:
					alert("Error: Unknown mask type on field " + ary[i].name + " -> " + strMaskType);
					break;
			}
		}
	}
}

//will also accept actual value instead of id
function check_phone_masks(strPhoneId, strCountryId, strStateId) {
	var strCountry, strState;

	strCountry = "";
	strState = "";
	if (strCountryId) {
		strCountry = $("#" + strCountryId).val();
		if (strCountry == null) {
			strCountry = strCountryId;
		}
	}
	if (strStateId) {
		strState = $("#" + strStateId).val();
		if (strState == null) {
			strState = strStateId;
		}
	}

	if ((strCountry.is_blank() || strCountry.toLowerCase() == "canada") && (strState != "AA" && strState != "AE" && strState != "AP")) {
		$("#" + strPhoneId).unmask().mask("999-999-9999",{placeholder:"?"});
	}
	else {
		$("#" + strPhoneId).unmask();
	}
}
function check_zip_masks(strZipId, strCountryId) {
	if ((!$("#" + strCountryId).val() || ($("#" + strCountryId).val().is_blank()))) {
		$("#" + strZipId).unmask().mask("99999?-9999",{placeholder:"?"});
	}
	else if ($("#" + strCountryId).val().toLowerCase() == "canada") {
		$("#" + strZipId).unmask().mask("a9a 9a9",{placeholder:"?"});
	}		
	else {
		$("#" + strZipId).unmask();
	}
}
function get_phone_attribute(elmPhone, strWhich) {
	var strId, elm;

	strName = elmPhone.getAttribute(strWhich);
	if (strName) {
		elm = document.getElementById(strName);
		if (!elm) {
			elm = eval("elmPhone.form." + strName);
		}
		if (elm) {
			strId = get_element_id(elm);
		}
		if (!strId) {
			alert("Error: " + strWhich + ":" + strName + " not found for input " + elmPhone.name);
		}
	}
	return strId;
}
var _autoid = 0;
//check if the element has an id, otherwise generate new one
function get_element_id(elm) {
	var strId;
	if (elm.id) {
		strId = elm.id;
	}
	else {
		strId = "autoid_" + (++_autoid);
		elm.id = strId;
	}
	return strId;
}
function setSelect(objSelect, values) {
	for (var i = 0; i < objSelect.options.length; ++i) {
		bln = false;
		switch (typeof(values)) {
			case "string":
				if (objSelect.options[i].value == values)
					bln = true;
				break;
			case "array":
				for (var j = 0; j < values.length; ++j)
					if (values[j] == objSelect.options[i].value)
						bln = true;
				break;
		}
		objSelect.options[i].selected = bln;
	}
}
function setRadio(objRadio, strValue) {
	if (objRadio.length) {
		for (var i = 0; i < objRadio.length; ++i) {
			objRadio[i].checked = (objRadio[i].value == strValue);
		}
	}
	else {
		objRadio.checked = (objRadio.value == strValue);
	}
}
function getRadio(objRadio) {
	var strReturn;

	strReturn = null;

	if (objRadio.length) {
		for (var i = 0; i < objRadio.length; ++i) {
			if (objRadio[i].checked) {
				strReturn = objRadio[i].value;
			}
		}
	}
	else {
		if (objRadio.checked) {
			strReturn = objRadio.value;
		}
	}

	return strReturn;
}
function DateToJavascriptDate(strDate) {
	dt = null;
	re = /^((1[0-2])|(0?[1-9]))\/[0-3]?[0-9]\/[0-9]{1,4}/;

	str = strDate.match(re);
	if (str) {
		str = str[0];
		intSlash1 = str.indexOf("/");
		intSlash2 = str.indexOf("/", intSlash1 + 1);
		intMonth = parseInt(str.substring(0, intSlash1), 10);
		intDay = parseInt(str.substring(intSlash1 + 1, intSlash2), 10);
		intYear = parseInt(str.substring(intSlash2 + 1, str.length), 10);
		if (intYear < 100)
			intYear += 2000;
		dt = new Date(MonthName(intMonth) + " " + intDay + ", " + intYear);
	}
	return dt;
}
function MonthName(intMonth) {
	var ary = new Array("", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
	return ary[intMonth];
}

function removeElement(obj) {
	objParent = obj.parentNode;
	objParent.removeChild(obj);
}

function body_load() {
	onload_check_all_elements();

	session_timer();
}
function body_unload() {
	if (blnKeep_Alive && wndKeep_Alive) {
		wndKeep_Alive.close();
	}
}
var wndKeep_Alive = null, blnKeep_Alive = true, tmrKeepAlive = null;
function session_keep_alive() {
	if (blnKeep_Alive) {
		if (wndKeep_Alive) {
			wndKeep_Alive.close();
		}
		wndKeep_Alive = window.open("../utilities/keepalive.asp", "", "width=650, height=300");
		wndKeep_Alive.focus();
	}
}
function session_timer() {
	tmrKeepAlive = setTimeout("session_keep_alive();", 17 * 60 * 1000);
}
function session_timer_reset() {
	clearTimeout(tmrKeepAlive);
	session_timer();
}
function parseDate(str) {
	var dt, ary;

	ary = str.split("/");
	dt = null;
	if (ary.length == 3) {
		if (ary[2] < 100)
			if (ary[2] < 75)
				ary[2] += 2000;
			else
				ary[2] += 1900;
		dt = new Date(ary[2], ary[0] - 1, ary[1]);
	}
	return dt;
}
function Show_Date(dt) {
	if (typeof(dt) == "string") {
		dt = parseDate(dt);
	}
	return pad_string_left(dt.getMonth() + 1, "0", 2) + "/" + pad_string_left(dt.getDate(), "0", 2) + "/" + dt.getFullYear();
}
/********************************************************************************************/

function fillDummyData(){
	var x = document.getElementsByTagName("input"), bln;
    var i, sType, bln;
    var s = new String();
    var functionReference;
    
	for (i=0;i<x.length;i++){
	    if (x[i].hasAttribute)
			bln = x[i].hasAttribute("readonly");
		else
			bln = x[i].getAttribute("readonly");
	
        if(!bln){
            if (x[i].hasAttribute)
			    sType = x[i].hasAttribute("type");
		    else
			    sType = x[i].getAttribute("type");
            
            switch(sType){
                case "text":
                    s = x[i].name.toUpperCase();  
                    
                    if(s.indexOf("EMAIL",0) != -1){
                        x[i].value = "email@email.com";
                    } else if((s.indexOf("PHONE",0) != -1) || (s.indexOf("FAX",0) != -1)){
                        x[i].value = "555-555-5555";
                    } else if(s.indexOf("ZIP",0) != -1){
                        x[i].value = "90210";
                    } else {
                        x[i].value = "aaaaaa";
                    }                    
                    
                    break;
            }
        }        
	}
    
    x = document.getElementsByTagName("select"), bln;
    
	for (i=0;i<x.length;i++){
	    s = x[i].name.toUpperCase();         
        if(s.indexOf("COUNTRY",0) == -1){
            x[i].selectedIndex = 1;
            
            if (x[i].hasAttribute)
			    bln = x[i].hasAttribute("onchange");
		    else
			    bln = x[i].getAttribute("onchange");
               
            if(bln){
                functionReference = x[i].onchange;
                functionReference();
            }
        }
	}
    
    return true;
}
function force_zip_code(strCountry) {
	var bln = false;

	if (strCountry.is_blank() || strCountry.toUpperCase() == "UNITED STATES" || strCountry.toUpperCase() == "CANADA")
		bln = true;

	return bln;
}
function ajax_benefit_message(strModule, strId, strAff, strDivId) {
	fnHandler = function(ajx) {
		json = eval("(" + ajx._response_text + ")");

		elm = document.getElementById(strDivId);
		elm.innerHTML = json.message;
	}

	var strURL = "../utilities/pickbenefit.asp?action=ajax_message&module=" + strModule + "&id=" + strId + "&af=" + strAff;
	ajax_request("get", strURL, "", fnHandler);
}
function close_modal() {
	wnd = window.opener;
	if (wnd) {
		wnd.focus();
	}
	window.close();
}
function focus_next(event, elm) {
	if (!event) {
		event = window.event;
	}

	intLength = elm.form.elements.length;
	if (event.shiftKey) {
		//allows shift+tab, doesn't work in Firefox
		intStart = intLength;
		intEnd = 0;
		intStep = -1;
	}
	else {
		intStart = 0;
		intEnd = intLength;
		intStep = 1;
	}

	blnNext = false;
	blnFound = false;
	elm.blur();
	for (var i = intStart; elm && elm.form && !blnFound && i != intEnd; i += intStep) {
		elmTemp = elm.form.elements[i];
		if (blnNext) {
			if (elmTemp.type == "hidden") {
			}
			else {
				blnFound = true;
				return elmTemp.focus();
			}
		}
		else if (elmTemp == elm) {
			blnNext = true;
		}
	}
	return false;
}

function resetFormValues(frm) {
	var obj;
	for (var i = 0; i < frm.elements.length; ++i) {
		obj = frm.elements[i];
		switch (obj.type) {
			case "checkbox":
				obj.checked = obj.defaultChecked;
				break;
			case "hidden":
			case "password":
			case "file":
			case "text":
			case "textarea":
				obj.value = obj.defaultValue;
				break;
			case "select-one":
			case "select-multiple":
				for (var k = 0; k < obj.options.length; ++k) {
					obj.options[k].selected = obj.options[k].defaultSelected;
				}
				break;
			case "radio":
				strTemp = "";
				//have to check if multiple values were checked by default
				//if multiple values are selected, the last one will be the "default" checked
				for (var k = 0; k < frm.elements.length; ++k) {
					objTemp = frm.elements[k];
					if (objTemp.name == obj.name) {
						if (objTemp.defaultChecked) {
							strTemp = objTemp.value;
						}
					}
				}
				//if checked and the value doesn't match the default, the value was changed.
				if (obj.value == strTemp) {
					obj.checked = true;
				}
				break;
			case "submit":
			case "reset":
			case "button":
				break;
			default:
				alert(obj.type);
		}
	}
}
function absolute_offsettop(obj) {
	return offset_absolute(obj, "offsetTop");
}
function absolute_offsetleft(obj) {
	return offset_absolute(obj, "offsetLeft");
}
function offset_absolute(obj, str_attribute) {
	var parent_position = 0;
	while(obj) {
		parent_position += obj[str_attribute];
		obj = obj.offsetParent;
	}
	return parent_position;
}
function setCurrentTab(strTabHeader, blnSkipScroll) {
	var elmTabHeader = document.getElementById(strTabHeader);
	var elmTabBody = document.getElementById(strTabHeader.replace(/^tabh/, "tabb"));

	var elmList = elmTabHeader.parentNode;
	var aryItems = elmList.childNodes;
	for (var i = 0; i < aryItems.length; ++i) {
		if (aryItems[i].id) {
			elmTabHeaderCurrent = aryItems[i];
			elmTabBodyCurrent = document.getElementById(elmTabHeaderCurrent.id.replace(/^tabh/, "tabb"));
			elmTabHeaderCurrent.className = "inactivetab";
			elmTabBodyCurrent.style.display = "none";
		}
	}
	elmTabHeader.className = "activetab";
	elmTabBody.style.display = "";
	if (!blnSkipScroll) {
		window.scrollTo(0, absolute_offsettop(elmTabHeaderCurrent));
	}

	return false;
}
function make_readonly(elm) {
	elm.readOnly = true;
	elm.className += " readonlyshade";
	old_onfocus = elm.onfocus;
	if (typeof old_onfocus == "function") {
		elm.onfocus = function(event) {
			old_onfocus();
			focus_next(event, this);
		}
	}
	else {
		elm.onfocus = function(event) {
			focus_next(event, this);
		}
	}
	if (typeof elm.ondblclick == "function") {
		elm.className += " dblclick_readonlyshade";
	}
}
function remove_readonly(elm) {
	elm.readOnly = false;
	elm.className = elm.className.replace(/(^|\s)readonlyshade(\s|$)/, "");
	eval("elm.onfocus = " + elm.onfocus.toString().replace(/[^A-Za-z0-9_]focus_next[^)]*\);?/, ""));
}
function set_single_select(elm, blnChange) {
	var bln;
	if (elm) {
		bln = true;
		switch (elm.type) {
			case "select-one":
				if (elm.options.length == 2 && elm.options[0].value.is_blank()) {
					elm.options[1].selected = true;
				}
				break;
			case "select-multiple":
				if (elm.options.length == 1) {
					elm.options[0].selected = true;
				}
				else if (elm.options.length == 2 && elm.options[0].value.is_blank()) {
					elm.options[0].selected = false;
					elm.options[1].selected = true;
				}
				break;
			default:
				bln = false;
				break;
		}
		if (blnChange && bln) {
			elm.onchange();
		}
	}	
}
function pad_string_left(strToPad, strPadChar, intLength) {
	var strTemp = replicate(strPadChar, intLength) + strToPad;
	return strTemp.substring(strTemp.length - intLength, strTemp.length);
}
function replicate(strChar, intLength) {
	var strDone = "";
	for (var i = 0; i < intLength; ++i) {
		strDone += strChar;
	}
	return strDone
}
function pause(millis) {
	var date = new Date();
	var curDate = null;

	do { curDate = new Date(); } 
	while(curDate-date < millis)
}
