/*	FUNCTION: AutoFocus
	ARGUMENTS:
		item (string)
	RETURNS: n/a
	SUMMARY: focuses on a formfield element
*/
function AutoFocus(item) {
	item.focus();
}

/*
	FUNCTION: SelectAll
	ARGUMENTS: n/a
	RETURNS: n/a
	SUMMARY: selects all checkboxes on a bag
*/
	function SelectAll(checkAll, chkarray) {
		var numChecks = chkarray.length;
		for (i = 0; i < numChecks; i++) {
			if (checkAll.checked == true) {
				chkarray[i].checked = true;
			}
			else {
				chkarray[i].checked = false;
			}
		}
	}

/*	FUNCTION: Redirect
	ARGUMENTS:
		url (string)
	RETURNS: n/a
	SUMMARY: redirects the user to a new page
*/
function Redirect(url) {
	location.href = url;
}

/*	FUNCTION: ValidateCurrency
	ARGUMENTS:
		_field (formfield)
	RETURNS: boolean
	SUMMARY: validates any currency value, including up to 2 decimal places
*/
function ValidateCurrency(x) {
	var thisField = x;
	var curOK = false;
	var curRegEx = "^\\$?([1-9]{1}[0-9]{0,2}(\\,[0-9]{3})*(\\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,}(\\.[0-9]{0,2})?|0(\\.[0-9]{0,2})?|(\\.[0-9]{1,2})?)$"

	if (thisField.value.length > 0) {
		if (thisField.value.match(curRegEx) != null) {
			curOK = true;
		}
		else {
			alert("Please enter a currency value.\nDo not include any of the following symbols ($, ',').\nUp to 2 decimal places are allowed.");
			curOK = false;
		}
	}
	return curOK;
}

/*	FUNCTION: ValidateZip
	ARGUMENTS:
		zip (string)
	RETURNS: boolean
	SUMMARY: validates any five digit number, including zip codes
*/
function ValidateZip(zip) {
	var zipOK = false;
	var zipRegEx = "\d{5}$";
	
	if (zip.length > 0) {
		if (zip.match(zipRegEx)) {
			zipOK = true;
		}
		else {
			zipOK = false;
		}
	}
	
	return zipOK;
	
}

/*	FUNCTION: ValidateSSN
	ARGUMENTS:
		ssn (string)
	RETURNS: boolean
	SUMMARY: validates social security numbers
*/
function ValidateSSN(ssn) {
	var ssnOK = false;
	var ssnRegEx = "^(?!000)([0-6]\d{2}|7([0-6]\d|7[012]))([ -])?(?!00)\d\d\3(?!0000)\d{4}$";

	if (ssn.length > 0) {
		if (ssn.match(ssnRegEx)) {
			ssnOK = true;
		}
		else {
			ssnOK = false;
		}
	}
	
	return ssnOK;
}

/*	FUNCTION: ValidateLogin
	ARGUMENTS:
		username (string)
		password (string)
	RETURNS: boolean
	SUMMARY: calls functions which validate username and password supplied
*/
function ValidateLogin(username, password) {
	var loginValid = false;
	var unOK, pOK = false;
   	/* 
		using this method of calling each of the functions into
		their own status variable, all alert boxes will appear.
	*/
	unOK = UsernameFormatValid(username);
	pOK = PasswordFormatValid(password);
	// are the both username and password correctly formatted?
	loginValid = unOK && pOK;
	
	if (loginValid) {
		return true;
	}
	else {
   		return false;
	}
}

/*	FUNCTION: UsernameFormatValid
	ARGUMENTS:
		username (string)
	RETURNS: boolean
	SUMMARY: checks username for valid format based on regular expression
*/
function UsernameFormatValid(username) {
	var REGEX_username = "(?!^[0-9]*$)^([a-zA-Z0-9]{6,15})$";
//	var REGEX_username = "(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{6,15})$";
	var usernameValid = username.match(REGEX_username);
	
	if ((usernameValid != null) && (usernameValid.length > 0)) {
		return true;
	}
	else if (usernameValid == null) {
	//	alert("Please enter a valid username.");
		return false;
	}
	else {
		return false;
	}
}

/*	FUNCTION: PasswordFormatValid
	ARGUMENTS:
		password (string)
	RETURNS: boolean
	SUMMARY: checks password for valid format based on regular expression
*/
function PasswordFormatValid(password) {
	var REGEX_password = "(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{6,15})$";
	var passwordValid = password.match(REGEX_password);

	if ((passwordValid != null) && (passwordValid.length > 0)) {
		return true;
	}
	else if (passwordValid == null) {
	//	alert("Please enter a valid password.");
		return false;
	}
	else {
		return false;
	}
}

/*	FUNCTIONS: ValidateUsername & ValidatePassword from Troy
	ARGUMENTS:
	RETURNS: 
	SUMMARY:
*/

function ValidateUsername(obj) {
	if (obj.value.length > 0) {
		if (!UsernameFormatValid(obj.value)) {
			window.alert("Username is not a valid format");
			obj.focus();
		}
	}
}

function ValidatePassword(obj) {
	if (obj.value.length > 0) {
		if (!PasswordFormatValid(obj.value)) {
			if (obj.value.length < 6) {
				window.alert("Password must be at least 6 characters");
				obj.focus();
			} else {
				window.alert("Password is not a valid format");
			}
		}
	}
}


/*	FUNCTION: TxtBoxLimiter
	ARGUMENTS:
		element (string)
	RETURNS: boolean
	SUMMARY: checks the length of a textbox
*/
function TxtBoxLimiter(element) {
	var tempVal = element.value;
	var max = 300;
	if (tempVal.length > max) {
		alert("The maximum number of characters is " + maxCharsMsg + "\nPlease edit your response.");
		return false;
	}
	else {
		return true;
	}
}

/*	FUNCTION: PhoneNumberChecker
	ARGUMENTS:
		element (string)
	RETURNS: boolean
	SUMMARY: checks the format of a phone/fax number
*/
function PhoneNumberChecker(element) {
	var FieldToCheck = new Array();
	var PhoneRegEx_old = "^[2-9]\d{2}-\d{3}-\d{4}$";
	var PhoneRegEx = /^1?\s*-?\s*(\d{3}|\(\s*\d{3}\s*\))\s*-?\s*\d{3}\s*-?\s*\d{4}$/;
	var pnOK = false;
	var tempElem = element;
	var i;
	
	FieldToCheck[0] = tempElem.value;
	
	for (i = 0; i < FieldToCheck.length; i++) {
		if (FieldToCheck[i].length > 0) {
			var tempString = FieldToCheck[i];
			
			if (tempString.match(PhoneRegEx)) {
				pnOK = true;
			}
			else {
				alert("Please enter a valid telephone/fax number in the following format: \n999-999-9999");
				pnOK = false;
			}
		}
		else {
			if (tempElem.getAttribute('required') == "true") {
				pnOK = false;
			}
			else {
				pnOK = true;
			}
		}
	}
	return pnOK;
}

/*
        FUNCTION: validRequired
        ARGUMENTS:
                formField (object)
				fieldLabel (string)
        RETURNS: boolean
        SUMMARY: validates required fields
		SOURCE: http://javascript.about.com/library/scripts/blccvalid.htm
*/
function validRequired(formField,fieldLabel)
{
	var result = true;
	
	if (formField.value == "")
	{
		alert('Please enter a value for the "' + fieldLabel +'" field.');
		formField.focus();
		result = false;
	}
	
	return result;
}

/*
        FUNCTION: SimpleDateCheck
        ARGUMENTS:
                _date (date/time)
        RETURNS: boolean
        SUMMARY: checks whether a date (formatted as MM/YYYY) occurs in the past
		SOURCE: http://javascript.about.com/library/scripts/blccvalid.htm
*/
function SimpleDateCheck(formField, fieldLabel, required) {
var result = true;
var formValue = formField.value;

if (required && !validRequired(formField,fieldLabel))
        result = false;

if (result && (formField.value.length>0))
{
        var elems = formValue.split("/");
        
        result = (elems.length == 2); // should be two components
        var expired = false;
        
        if (result)
        {
                var month = parseInt(elems[0],10);
                var year = parseInt(elems[1],10);
                
                if (elems[1].length == 2)
                        year += 2000;
                
                var now = new Date();
                
                var nowMonth = now.getMonth() + 1;
                var nowYear = now.getFullYear();
                
                expired = (nowYear > year) || ((nowYear == year ) && (nowMonth > month));
                
                result = allDigits(elems[0]) && (month > 0) && (month < 13) &&
                                 allDigits(elems[1]) && ((elems[1].length == 2) || (elems[1].length == 4));
        }
        
        if (!result)
        {
                alert('Please enter a date in the format MM/YYYY for the ' + fieldLabel +' field.');
                formField.focus();
        }
        else if (expired)
        {
                result = false;
                alert('The date for ' + fieldLabel +' has expired.');
                formField.focus();
        }
} 

return result;
}

/*
        FUNCTION: allDigits
        ARGUMENTS:
                str (string)
        RETURNS: boolean
        SUMMARY: checks whether a string contains all digits
		SOURCE: http://javascript.about.com/library/scripts/blccvalid.htm
*/
function allDigits(str)
{
	return inValidCharSet(str,"0123456789");
}

/*	FUNCTION: CheckDateValue
	ARGUMENTS:
		_date (date/time)
	RETURNS: boolean
	SUMMARY: checks whether a date (formatted as MM/DD/YYYY) occurs in the past
*/
function CheckDateValue (_date) {
	var now = new Date();
	var today = now.getDate();	// get current date
	var strDate = _date;
	var div = "/";

	// if the user has entered a correct date
	if (isDate(strDate)) {
		// get the locations of the dividers, in this case "/"
		var pos1 = strDate.indexOf(div);
		var pos2 = strDate.indexOf(div, pos1+1) 
		// parse the month, date and year from a date formatted like MM/YYYY
		var cYear = strDate.substring(pos2+1);
		var cMonth = strDate.substring(0, pos1);
		var cDay = strDate.substring(pos1+1, pos2);
		// assemble the date to check
		var dateToCheck = new Date();
		dateToCheck.setYear(cYear);
		dateToCheck.setMonth(cMonth-1);
		dateToCheck.setDate(cDay);
		
		var checkDate = dateToCheck.getTime();
		// check whether the date occured in the past and alert the user
		if (now > checkDate) {
			alert("Your certificate has expired.  Please correct your entry.");
			return false;
		}
		return true;
	}
	else {
		return false;
	}
}

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var dtCh= "/";
	var minYear=1900;
	var maxYear=2100;
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}

/*	FUNCTION: ValidateForm
	ARGUMENTS:
		thisForm (Form object)
	RETURNS: boolean
	SUMMARY: checks that any fields with the required attribute set to true have not been left blank
*/ 
function ValidateForm(_form2) {
	var thisForm = _form2;
	var numElements = thisForm.length;
	var i;
	
	var errorCount = 0;
	var errFields = new Array();
	var errNote = new Array();
	var errMsg = "";
	
	for (i = 0; i < numElements; i++) {
		// Checks required fields
		if ((thisForm[i].getAttribute('required') == "true") && (thisForm[i].value.length == 0)) {
			// Check phone / fax number fields
			if (thisForm[i].getAttribute('phoneNumber') == "true") {
				if (PhoneNumberChecker(thisForm[i]) == false) {
					errFields[errorCount] = thisForm[i].getAttribute('displayName');
					errNote[errorCount] = "Please enter a valid phone / fax number in the following format: 999-999-9999.";
					errorCount++;
				}
			}
			else {
				errFields[errorCount] = thisForm[i].getAttribute('displayName');
				errNote[errorCount] = "This field is required.";
				errorCount++;
			}
		}

		// Check numeric value fields
		// The Javascript function isNaN(), "Is Not a Number," returns true if the passed
		// argument IS NOT A NUMBER
		if (thisForm[i].getAttribute('numeric') == "true") {
			if (isNaN(thisForm[i].value) == true) {
				errFields[errorCount] = thisForm[i].getAttribute('displayName');
				errNote[errorCount] = "Please enter a valid numeric value.";
				errorCount++;
			}
		}

        if (thisForm[i].getAttribute('username') == "true") {
            if (thisForm[i].value.length == 0) {
                errFields[errorCount] = thisForm[i].getAttribute('displayName');
                errNote[errorCount] = "Field is required.";
                errorCount++;
            }
			else {
				if (UsernameFormatValid(thisForm[i].value) == false) {
					errFields[errorCount] = thisForm[i].getAttribute('displayName');
					errNote[errorCount] = "Please enter a valid username.";
					errorCount++;
				}
			}
        }

        if (thisForm[i].getAttribute('password') == "true") {
            if (thisForm[i].value.length == 0) {
                errFields[errorCount] = thisForm[i].getAttribute('displayName');
                errNote[errorCount] = "Field is required.";
                errorCount++;
            }
			else {
				if (PasswordFormatValid(thisForm[i].value) == false) {
					errFields[errorCount] = thisForm[i].getAttribute('displayName');
					errNote[errorCount] = "Please enter a valid password.";
					errorCount++;
				}
			}
        }
	} // end for loop

	if (errorCount > 0) {
		// Loop through each of the error fields and create an HTML list which will
		// be added to the error message.
		for (i = 0; i < errFields.length; i++) {
			errMsg = errMsg + "<li>" + errFields[i] + " - " + errNote[i] + "</li>"; 
		}
		// Show an error message alerting the user which fields need to be updated
		document.getElementById("errorMsg").innerHTML = 
			"Please complete the following fields:<ul>" + errMsg + "</ul>";
		// Add focus to the first field of the form
		AutoFocus(thisForm[1]);	
		// Return false.  This halt the form from submitting
		return false;
	}
	else {
		// Return true.  Proceed.
		return true;
	}
}

/*	FUNCTION: FillAddress
	ARGUMENTS:
		_elem (Form element)
	RETURNS: void
	SUMMARY: if the use has selected the "mailing address same as physical checkbox, 
				fills the mailing address values using data from the physical address, or
				if the checkbox is de-selected, clears the mailing address fields.
*/
function FillAddress(_elem) {
	var isChecked = document.getElementById("chk1").checked;
	if (isChecked) {
		DuplicateAd(_elem);
	}
	else {
		ClearAd(_elem);
	}
}

function DuplicateAd(_obj) {
	with (_obj) {
		mail_ad1.value = Phys_ad1.value;
		mail_city.value = Phys_city.value;
		mail_state.value = Phys_state.options[Phys_state.selectedIndex].value;
		mail_zip.value = Phys_zip.value;
	}
}

function ClearAd(_obj1) {
	with (_obj1) {
		mail_ad1.value = "";
		mail_city.value = "";
		// reset the selected state for the mailing address
		mail_state.value = mail_state.options[0].value;
		mail_zip.value = "";
	}
}

/*	FUNCTION: frmDisabler
	ARGUMENTS:
		elem1, elem2 (form elements)
	RETURNS: VOID
	SUMMARY: enables or disables a specified form field.  The first element
		 submitted will be disabled.
*/
	function frmDisabler(elem1, elem2) {
		var f1 = elem1;
		var f2 = elem2;
		
		f1.disabled = false;
		f1.style.background = 'FFFFFF';
		f2.value = "";
		f2.disabled = true;
		f2.style.background = 'C1C1C1';
	}

	function frmDisabler2(elem1, elem2, elem3, elem4) {
		var f1 = elem1;
		var f2 = elem2;
		var f3 = elem3;
		var f4 = elem4;

		f3.value = "";
		f4.value = "";

		f1.disabled = false;
		f2.disabled = false;
		f3.disabled = true;
		f4.disabled = true;
		
		f1.style.background = 'FFFFFF';
		f2.style.background = 'FFFFFF';
		f3.style.background = 'C1C1C1';
		f4.style.background = 'C1C1C1';
}