//* Bryan Glenn: Global function used to return a form error then 
//* set the focus to the form field that needs to be altered\enetered.
function formError(reason,focusElement)
{
 	alert(reason);

	if (focusElement != ''){
	focusElement.focus();
	}
}

//* Bryan Glenn: Function for validating U.S. State codes.
// Valid U.S. Postal Codes for states, territories, armed forces, etc.
// See http://www.usps.gov/ncsc/lookups/abbr_state.txt.
function validateStateCode(stateCode){
	var USStateCodes = /"AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|AE|AA|AE|AE|AP"/i
	return stateCode.match(USStateCodes)
}
	
//* Bryan Glenn: Generic function for opening a new window.
function openWindow(strURL, strWindowName, strParams)
{
        window.open(strURL, strWindowName, strParams)
}

//* Bryan Glenn: This will strip out the $'s and commas from a string.
//* Used to make sure we don't stick nasty data in the db.
function numberStrip(str)
{
	re = /^\$|,/g;
	// remove "$" and ","
	return str.replace(re, "");
}

//* Bryan Glenn: Generic function to catch a custum error and display it. If 
//* customError is a 0 length string then we go ahead and submit the form.
function displayErrorOrSubmitForm(customError, formToSubmit)
 {
   if (customError != "")
	{
		alert(customError);
	}
	else if (customError == "")
	{
		formToSubmit.submit(); 
	}
} // end method displayErrorOrSubmitForm

// * Bryan Glenn:
// * validateTextField will check the text of the specified text object
// * for blank values (zero length or white space) and optionally to
// * verify that the value of the field IS numeric.
// *
function validateTextField(obj,blnIsNumeric) {

	var strTextValue = obj.value;

	strTextValue = strTextValue.replace(/\s+/,"");

	if((blnIsNumeric == false) && strTextValue.length == 0) {
		obj.focus();
		obj.select();
		return false;
	} else if ((blnIsNumeric == true) && (isNaN(strTextValue) == true)){
		obj.focus();
		obj.select();
		return false;
	} else {
		return true;
	}
} // end method validateTextField

//Tripp Bishop:
function submitOnEnter(evt) {
	var objTempForm;
	var keyCode;
	var formName;

	if(objBrowserCheck.isIE == "1" && objBrowserCheck.isIE6 != "1") {
		keyCode = window.event.keyCode;
		//alert("got to here.");
		objTempForm = window.event.srcElement.parentElement;
	} else if(objBrowserCheck.isN == "1") {
		keyCode = evt.which;
		objTempForm = evt.target.form;
	}

	if(objBrowserCheck.isIE == "1" && objBrowserCheck.isIE6 != "1") {

		if(objTempForm.type != null && keyCode == 13) {
			objTempForm.submit();
		} else if(objTempForm.type == null && keyCode == 13) {
			formName = checkFormsForData();
			if(formName.length != 0) {
				eval("document.forms." + formName + ".submit();");
			}
		}

	} else if(objBrowserCheck.isN == "1") {

		if(objTempForm != null && keyCode == 13 && evt.target.type != 'textarea') {
			objTempForm.submit();
		} else if(objTempForm == null && keyCode == 13 && evt.target.type != 'textarea') {
			formName = checkFormsForData();
			if(formName.length != 0) {
				eval("document.forms." + formName + ".submit();");
			}
		}
	}

} // end method submitOnEnter

// Tripp Bishop:
function checkFormsForData() {

	var formCount = document.forms.length;
	var checkDataArray = new Array(formCount);
	var populatedFormCounter = 0;
	var formName;

	for(var i = 0; i < formCount; i++) {
		for(var j = 0; j < document.forms[i].elements.length; j++) {
			checkDataArray[i] = '';
			if(document.forms[i].elements[j].type.toLowerCase() == 'text') {
				if(document.forms[i].elements[j].value != '') {
					checkDataArray[i] = document.forms[i].name;
					break;
				}
			}
		}
	}

	for(var i = 0; i < checkDataArray.length; i++) {
		if(checkDataArray[i] != '') {
			formName = checkDataArray[i];
			populatedFormCounter ++;
		}
	}

	if(populatedFormCounter == 1)  {
		return formName;
	} else {
		return '';
	}

} // end method checkFormsForData


//* Bryan Glenn: Used for validating form fields for SQL server compatability.
function validateForSQL(strFormName, strFieldName) {
	var strFormFieldValue = eval('document.forms.' + strFormName + '.' + strFieldName + '.value');
	var objRegExp = /[;%<>=]/;

	if (strFormFieldValue != '' && objRegExp.test(strFormFieldValue)) {
		var objFormField = eval('document.forms.' + strFormName + '.' + strFieldName);
		objFormField.focus();
		return false;
	}
	else {
		return true;
	}
}

//* Bryan Glenn: Used for validating phone numbers.
function validatePhoneNumber(strFormFieldValue) {
	//var strFormFieldValue = eval('document.forms.' + strFormName + '.' + strFieldName + '.value');

	alert(strFormFieldValue);
	
	var objRegExp = /[a-d|f-s|u-w|y-z]+|[A-D|F-S|U-W|Y-Z]+|[&\*@%\$,:;\{\}\[\]\?'"\|\=#\^\!~_\/\\`]+/g;
	
	if (strFormFieldValue != '' && objRegExp.test(strFormFieldValue)) {
		return false;
	}
	else
	{
		return true;
	}
}

//* Bryan Glenn: Used for basic email address validation.
function validateEmailAddress(strEmailAddress) {

	var objRegExp = /[\d+|\D+]+@[\d+|\D+]+\.[\d+|\D+]/gi;
	
	if(objRegExp.test(strEmailAddress)) {
		return true;
	} else {
		return false;
	}

}


function clearForm(objThis)
{
	for (var i=0; i<objThis.length; i++)
	{
		if (objThis.elements[i].type == 'text')
		{
			objThis.elements[i].value = '';
		}
		else if (objThis.elements[i].type == 'select-one')
			objThis.elements[i].selectedIndex = 0;
	}
}

/* Tripp Bishop:
 *use this function inconjunction with the onKeyUp event handler to prevent the specified textarea
 *from exceeding a certain size.
 */
function checkLengthOfTextArea(objTextArea, maxlength) {

	if (objTextArea.value.length > maxlength) {
		objTextArea.value = objTextArea.value.substring(0,maxlength);
		alert("You have exceeded the size limit for this field.");
	}

}

function isAlpha(string)
{
	var isAlpha = true;
	sValidChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

	for (i = 0; i < string.length; i++)
	{
		if ( (sValidChars.indexOf(string.charAt(i))) == -1 )
		{
			isAlpha = false;
		}
	}
	return isAlpha;
}

function trim(text)
{
	while(text.charAt(text.length-1) == " ")
	{
		text = text.substring(0, text.length-1);
	}
	while(text.charAt(0)==" ")
	{
		text = text.substring(1);
	} 
	return text;
}

function isValidPolicyNumber(policy) {
	isValid = true;

	for (a = 0; a < 2; a++) {
		if (isNaN(policy.charAt(a)))
			isValid = false;
	}
	
	for (a = 3; a < 13; a++) {
		if (isNaN(policy.charAt(a)))
			isValid = false;
	}
	
	if ( isNaN(policy.charAt(14)) && !isAlpha(policy.charAt(14)) )
		isValid = false;
		
	for (a = 16; a < 18; a++) {
		if (isNaN(policy.charAt(a)))
			isValid = false;
	}
	
	if (!(policy.charAt(2) == '-' && policy.charAt(13) == '-' && policy.charAt(15) == '-'))
		isValid = false;
		
	return isValid;
}

//* Original:  Cyanide_7 (leo7278@hotmail.com)
//* Web Site:  http://www7.ewebcity.com/cyanide7

//* This script and many more are available free online at
//* The JavaScript Source!! http://javascript.internet.com
function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	
	if(isNaN(num))
	num = "0";
	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;
	
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
		num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num + '.' + cents);
}

//* Bryan Glenn:  This function just uses the formatCurrency function above
//* to quickly format a currency field.  Mostly this is used via an onBlur event.
function displayCurrency(thisElement)
{	
	if (thisElement.value != "")
	{
		thisElement.value = formatCurrency(thisElement.value);
	}			
}

// This is just a morphed version of formatCurrency.
function formatNumber(num) {
	num = num.toString().replace(/\$|\,/g,'');
	
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	num = Math.floor(num/100).toString();
	
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
		num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num);
}

//* Bryan Glenn:  This function just uses the formatNumber function above
//* to quickly format a number field.  Mostly this is used via an onBlur event.
function displayNumber(thisElement)
{
	if (thisElement.value != "")
	{
		thisElement.value = formatNumber(thisElement.value);
	}			
}

//** Bryan Glenn: Generic function to move the cursor from area code to 
//** the 3 digit prefix to the last 4 digits of a phone number.
//**
//** The assumptions are that the 3 phone number fields are named
//** Phone1, Phone2, and Phone3.
function movePhoneCursor(thisElement,thisForm)
{
	if(thisElement.name == "Phone1" && thisElement.value.length == 3){
		thisForm.Phone2.focus();
	}
	else if(thisElement.name == "Phone2" && thisElement.value.length == 3){
		thisForm.Phone3.focus();
	}								
}

//** Bryan Glenn: Takes a text area input and max length.
//** Once a max length is reached an alert is thrown and it 
//** truncates the text back to the max length.
function checkLength(thisElement, length, fieldName)
{
	if(thisElement.value.length >= length){				
	var lossDescription = new String(thisElement.value);
		thisElement.value = lossDescription.slice(0,length);
		alert("You have reached the maximum length of the " + fieldName + " field.")
	}
}


function validateEmail(emailstring)
{

	//Declare and initialize email string
    var emailStr;
    emailStr = emailstring;    
    
    /* The following variable tells the rest of the function whether or not
    to verify that the address ends in a two-letter country or well-known
    TLD.  1 means check it, 0 means don't. */
    var checkTLD=1;
    
    /* The following is the list of known TLDs that an e-mail address must end with. */
    var knownDomsPat=/^(COM|NET|ORG|EDU|MIL|GOV|ARPA|BIZ|AERO|NAME|COOP|INFO|PRO|com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
    
    /* The following pattern is used to check if the entered e-mail address
    fits the user@domain format.  It also is used to separate the username
    from the domain. */
    var emailPat=/^(.+)@(.+)$/;
    
    /* The following string represents the pattern for matching all special
    characters.  We don't want to allow special characters in the address. 
    These characters include ( ) < > @ , ; : \ " . [ ] */
    var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
    
    /* The following string represents the range of characters allowed in a 
    username or domainname.  It really states which chars aren't allowed.*/
    var validChars="\[^\\s" + specialChars + "\]";
    
    /* The following pattern applies if the "user" is a quoted string (in
    which case, there are no rules about which characters are allowed
    and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
    is a legal e-mail address. */
    var quotedUser="(\"[^\"]*\")";
    
    /* The following pattern applies for domains that are IP addresses,
    rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
    e-mail address. NOTE: The square brackets are required. */
    var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    
    /* The following string represents an atom (basically a series of non-special characters.) */
    var atom=validChars + '+';
    
    /* The following string represents one word in the typical username.
    For example, in john.doe@somewhere.com, john and doe are words.
    Basically, a word is either an atom or quoted string. */
    var word="(" + atom + "|" + quotedUser + ")";
    
    // The following pattern describes the structure of the user
    var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
    
    /* The following pattern describes the structure of a normal symbolic
    domain, as opposed to ipDomainPat, shown above. */
    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
    
    /* Finally, let's start trying to figure out if the supplied address is valid. */
    /* Begin with the coarse pattern to simply break up user@domain into
    different pieces that are easy to analyze. */
    var matchArray=emailStr.match(emailPat);
    if (matchArray==null) {
    /* Too many/few @'s or something; basically, this address doesn't
    even fit the general mould of a valid e-mail address. */
      alert("Email address syntax is incorrect (check @ and .'s)");
      Email.focus();
      return false;
    }
    
    var user=matchArray[1];
    var domain=matchArray[2];
    
    // Start by checking that only basic ASCII characters are in the strings (0-127).
    for (i=0; i<user.length; i++) {
      if (user.charCodeAt(i)>127) {
        alert("Ths username contains invalid characters.");
        Email.focus();
        return false;
      }
      if (user.charCodeAt(i)==32) {
        alert("Ths username may not contain spaces.");
        Email.focus();
        return false;
      }      
    }
    for (i=0; i<domain.length; i++) {
      if (domain.charCodeAt(i)>127) {
        alert("Ths domain name contains invalid characters.");
        Email.focus();
        return false;
      }
    }
    
    // See if "user" is valid 
    if (user.match(userPat)==null) {
    // user is not valid
      alert("The username doesn't seem to be valid.");
      Email.focus();
    	return false;
    }
    
    /* if the e-mail address is at an IP address (as opposed to a symbolic
    host name) make sure the IP address is valid. */
    var IPArray=domain.match(ipDomainPat);
    if (IPArray!=null) {
      // this is an IP address
      for (var i=1;i<=4;i++) {
        if (IPArray[i]>255) {
          alert("Destination IP address is invalid!");
        	Email.focus();
    	    return false;
        }
      }
      return true;
    }
    
    // Domain is symbolic name.  Check if it's valid.
    var atomPat=new RegExp("^" + atom + "$");
    var domArr=domain.split(".");
    var len=domArr.length;
    for (i=0;i<len;i++) {
      if (domArr[i].search(atomPat)==-1) {
        alert("The domain name does not seem to be valid.");
      	Email.focus();
      	return false;
      }
    }
    
    /* domain name seems valid, but now make sure that it ends in a
    known top-level domain (like com, edu, gov) or a two-letter word,
    representing country (uk, nl), and that there's a hostname preceding 
    the domain or country. */
    if (checkTLD && domArr[domArr.length-1].length!=2 && 
      domArr[domArr.length-1].search(knownDomsPat)==-1) {
      alert("The address must end in a well-known domain or two letter " + "country.");
    	Email.focus();
    	return false;
    }
    
    // Make sure there's a host name preceding the domain.
    if (len<2) {
      alert("This address is missing a hostname!");
    	Email.focus();
    	return false;
    }
	
	return true;
}

// Used for swapping out the left and ride sides of the fake buttons.
function fakeButtonMouseOver(thisElement,name,action)
{				
	var leftside = name + "_left";
	var rightside = name + "_right";				
	
	if(action == 'mouseover'){				
		eval("document." + leftside + ".src = '/images/generic/btn_left_button_on.gif';")
		eval("document." + rightside + ".src = '/images/generic/btn_right_button_on.gif';")
		thisElement.bgColor='black';
	}
	else if(action == 'mouseout'){
		eval("document." + leftside + ".src = '/images/generic/btn_left_button_off.gif';")
		eval("document." + rightside + ".src = '/images/generic/btn_right_button_off.gif';")
		thisElement.bgColor='DC0341';								
	}
}

// This function is used by the BuildFromDateDropDowns and the BuildToDateDropDowns subroutines
// in /resourcecenter/i_page_layout.asp.  It's used to call the function daysInMonth to dynamically
// generate the correct number of days in a given month and year.
function calldaysInMonth(thisForm, identifyingValue){	
	
	var objMonth = eval("thisForm" + ".Month" + identifyingValue);
	var objDay = eval("document." + thisForm.name + ".Day" + identifyingValue);
	var objYear = eval("document." + thisForm.name + ".Year" + identifyingValue);

	daysInMonth(thisForm, objMonth.options[objMonth.selectedIndex].value, objYear.options[objYear.selectedIndex].value, objDay);
	
}

// This function will dynamically rebuild the days drop down menu and
// set the selected value to whatever was previously selected.
function changeDays(numberOfDays, oldDayTo, dayToChange)
{
	dayToChange.options[0] = new Option('Day', 0);
	var dayValue
	for (var i = 1; i <= numberOfDays; i++)
	{
		// If the i value is less then 10 we need to append a 0 to displayText.
		if (i < 10)
		{
			dayValue = "0" + i
		}
		else
		{
			dayValue = i
		}
		dayToChange.options[i] = new Option(dayValue, dayValue);
	}
	// If the new number of days in the drop down is less than what the user originally
	// selected we will just set the selected day to '00'.
	if (numberOfDays < oldDayTo )
	{
		dayToChange.options[numberOfDays].selected = true;
	}
	// Here we are checking to see the new date was 29 and the old date is 28.  If
	// it is then we want to set the selected value to 29.
	else if (numberOfDays == 29 && oldDayTo == 28)
	{
		dayToChange.options[numberOfDays].selected = true;
	}
	else
	{
		dayToChange.options[oldDayTo].selected = true;
	}
} // End changeDays

// This function will determine how many days need to be placed in the days drop down menu.
function daysInMonth(thisForm, whichMonth, whichYear, dayToChange)
{
	// Setting oldDayTo to the value currently selected in the days drop down menu.  We need
	// set the selected value to the oldDayTo value after we've regenerated the drop down.
	
	var oldDayTo = parseInt(dayToChange.options[dayToChange.options.selectedIndex].value);

	// If we come in without the year selected set it to a non-leap year value.
	if (whichYear == "0000") whichYear = "1997"

  	if (whichMonth == "04" || whichMonth == "06" || whichMonth == "09" || whichMonth == "11")
	{
		dayToChange.length = 30;
		changeDays(30, oldDayTo, dayToChange)
	}
	else if (whichMonth == "02")
	{
		dayToChange.length = 28;
		changeDays(28, oldDayTo, dayToChange)
	}
	else
	{
		dayToChange.length = 32;
		changeDays(31, oldDayTo, dayToChange)
	}

	// It's not a leap year.
	if (whichMonth == "02" && (whichYear/4) != Math.floor(whichYear/4))
	{
		dayToChange.length = 28;
		changeDays(28, oldDayTo, dayToChange)
	}
	// It is a leap year.
	if (whichMonth == "02" && (whichYear/4) == Math.floor(whichYear/4))
	{
		dayToChange.length = 29;
		changeDays(29, oldDayTo, dayToChange)
	}
} // End daysInMonth

function validateDateRanges(yearTo, yearFrom, monthTo, monthFrom, dayTo, dayFrom)
{
	// Let's check to see if the date range even makes sense before we continue.
	if ( (yearTo == "0000" || yearFrom == "0000" || monthTo == "00" || monthFrom == "00" || dayTo == "00" || dayFrom == "00")
	  && (yearTo != "0000" || yearFrom != "0000" || monthTo != "00" || monthFrom != "00" || dayTo != "00" || dayFrom != "00" ) )
	{
		alert("Please check to make sure a valid date range is entered.");
		return false;
	}
	// If the year values don't make sense let the user know.
	else if ( yearFrom > yearTo )
	{
		alert("Please check to make sure a valid YEAR range is entered.");
		return false;
	}
	// If the year values are the same we need to make sure the month and day are valid.
	else if ( yearFrom == yearTo )
	{
		if ( monthFrom > monthTo )
		{
			alert("Please check to make sure a valid MONTH range is entered.");
			return false;
		}
		else if ( monthFrom == monthTo )
		{
			// So far we've seen that the year values and the month values match so let's make sure
			// we have a valid day.
			if ( dayFrom > dayTo )
			{
				alert("Please check to make sure a valid DAY range is entered.");
				return false;
			}
			// If we ended up here it means that they haven't entered a date so return true and move on.
			else
			{
				return true;
			}
		}
		else
		{
			return true;
		}
	}
	else
	{
		return true;
	}
} // End validateDateRanges

// Bryan Glenn - Used for swapping out the background colors of table cells.
function cellMouseOver(thisElement,action,cellColor)
{   
    // If cellColor isn't defined default it to white.
    if(!cellColor){
        cellColor = 'ffffff';   
    }
    
    if(action == 'mouseover'){
        thisElement.bgColor = cellColor;
    }
    else if(action == 'mouseout'){
        thisElement.bgColor = cellColor;                                
    }
}