var loggedIn 							= false;
var anchorsFixed 						= false;
var hideLeftNav 						= false;
var customFieldEnabled 					= false;
var emailRoutingEnabled 				= false;
var fieldsThatNeedValidating 			= new Array();
var fieldsThatNeedValidatingFunctions 	= new Array();
var fieldsThatAreRequiredFunctions		= new Array();
var phoneFieldsToFormat					= new Array();
var customField							= new Array();
var indexOfField						=0;
var indexOfField2						=0;
var phoneFieldIndex						=0;
var customFieldCounter 					= 0;
var addCustomFieldIndex					=2;
var emailRoutingKey 					= "";
var phoneFieldsToFormat					= new Array();

var pageNumber = "(866) 746-7238";
function getPageNumber() {
	var imgTagName = document.getElementsByName("Page_Image_Number");
	var phonePat =/(\d{3})[-,.]?(\d{4})/;
	
	if ( imgTagName[0] != null ) {

		var matchArray=imgTagName[0].alt.match( phonePat );
		if ( matchArray != null ) {
			pageNumber = Trim(imgTagName[0].alt.substr( imgTagName[0].alt.indexOf(": ") + 1));
		} 
	}

	document.write( pageNumber );
}



function getLanguage() {
	var language = document.getElementById("Language");
	if ( language != null && language.value != null && language.value != "ENG" ) {
		return language.value;
	} else {
		return "";
	}
}

// Added by Walter for RETRIEVE CART LINK
function setStoreRedirect()
{
	document.cookie="redirection=viewCart; path=/;";
	if (location.href.indexOf("small_business") > -1)
	{
		document.cookie="storeRedirect=smBiz; path=/;";
	}
	else
	{
		document.cookie="storeRedirect=resi; path=/;";
	}
}
// End of addition for RETRIEVE CART LINK


function decodeAllFields() {
	var fieldRefNames = document.getElementById("leadForm");
	for (var myCounter=0; myCounter < fieldRefNames.length; myCounter++) {
		fieldRefNames[myCounter].value = decodeURI(fieldRefNames[myCounter].value);
	}
}

//removed getPerformicsURL() function because this functionality is server side. See previous archive version for function details
//08/01/2007

function needToValidate(fieldToValidate, validateFunction, requiredFunction){

	fieldsThatNeedValidating[indexOfField] = fieldToValidate;
	fieldsThatNeedValidatingFunctions[indexOfField] = validateFunction;
	fieldsThatAreRequiredFunctions[indexOfField] = requiredFunction;

	indexOfField++;

}

function addCustomFieldName( fieldToAdd ) {
	customField[customFieldCounter++] = fieldToAdd;
}


function updateFormLabel( idOfLabel, toggle) {

	if ( !toggle ) {
		changeText( idOfLabel + "Label", "#DC344D");
	} else {
		changeText( idOfLabel + "Label", "#000000");
	}
}

function validateFields() {

	var allFieldsValid 	= true;
	var isValidField 	= true;
	phoneFieldIndex		= 0;

	if ( emailRoutingEnabled && !wasEmailPopulated ( emailRoutingKey ) ){
		return false;
	}
	
	//Check for required fields
	for( validateIndex=0; validateIndex < fieldsThatNeedValidating.length; validateIndex++ ) {

		//First check if required, if so check that value exists
		if (fieldsThatAreRequiredFunctions[validateIndex] != null){
			var reqFncStr = 	fieldsThatAreRequiredFunctions[validateIndex]	+ "('" +
							fieldsThatNeedValidating[validateIndex] + "');"

			isValidField = eval(reqFncStr);
		}

		if ( !isValidField ) {
			allFieldsValid 		= false;

			updateFormLabel( fieldsThatNeedValidating[validateIndex], isValidField);
			//Don't check for valid, reset valid flag for next field
			isValidField = true;
			continue;
		}

		//Call the validation function registered for this field
		if ( fieldsThatNeedValidatingFunctions[validateIndex] != null ){
			var valFncStr = 	fieldsThatNeedValidatingFunctions[validateIndex] + "('" +
						fieldsThatNeedValidating[validateIndex] + "');"

			isValidField = eval(valFncStr);
		}

		if ( !isValidField ) {
			allFieldsValid = false;

			updateFormLabel( fieldsThatNeedValidating[validateIndex], isValidField);
			//Move on to next field, reset valid flag for next field
			isValidField = true;
			continue;
		}

		//Let form label toggle back to normal is validation checking passes
		if ( isValidField == true){
			updateFormLabel( fieldsThatNeedValidating[validateIndex], isValidField);
		}
	}

	if ( !allFieldsValid ) {
		var div_ref = document.getElementById("errorMessage" + getLanguage());
		div_ref.style.display = "";

		return false;
	}

	//Modify FormName if necessary
	if ( emailRoutingEnabled ){
		addRoutingKeyToFormName();
	}

	phoneFieldFormatting();
	formatCustomFormFields();
	setCommerceParams();

	//Allow submission to continue
	//Disable submit button before continuing to prevent double submission
	if(document.getElementById("imgFormSubmit") != null){
		document.getElementById("imgFormSubmit").disabled=true;
	}

	return true;
}


function checkRequiredRadioButtons( fieldIdToCheck ) {

	var radioButtonSelected = false;
	var fieldRefName2 = document.getElementsByName( document.getElementById( fieldIdToCheck ).name );
	for (var myCounter2=0; myCounter2 < fieldRefName2.length; myCounter2++ ) {

		if ( fieldRefName2[myCounter2].checked ) {
			radioButtonSelected = true;
		}
	}

	if ( !radioButtonSelected ) {
		return false
	}

	return radioButtonSelected;
}


function checkRequiredCheckbox( fieldIdToCheck ) {

	var checkBoxFieldValid = true;
	if ( document.getElementById( fieldIdToCheck ).checked != 1 ) {
		checkBoxFieldValid=false;
	}

	return checkBoxFieldValid;
}


function checkRequiredText( fieldIdToCheck ){

	var allFieldsValid = true;
	if ( ( Trim( document.getElementById( fieldIdToCheck ).value ) ).length <= 0 ) {
		allFieldsValid=false;
	}

	return allFieldsValid;
}

/***************************************************************** UPDATED THIS *****************************************************/
function formatPhoneField( fieldIdToCheck ) {

	//document.getElementById( fieldIdToCheck ).maxLength=12;

	var phoneField 			= Trim( document.getElementById( fieldIdToCheck ).value );
	var phoneNumberDelimiters 	= /^[-\.\s]+$/;
	var phonePat			= /^\d{3}([-\.\s])?(\d{3})([-\.\s])?(\d{4})$/;
	var phoneFieldValue 		= "";
	var phoneExtDelimiters		= /^[0-9]+$/;

	if ( phoneField.length == 0) {
		return true;
	}


	var matchArray=phoneField.match( phonePat );
	if ( matchArray == null) {
		eval ( "alert" + getLanguage() + "IncorrectFormatPhoneMSG()");

		document.getElementById( fieldIdToCheck ).focus();
		return false;
	}

	if ( Trim( removeNonDigits( phoneField, phoneNumberDelimiters ) ).length < 10 ) {
		eval( "alert" + getLanguage() +"IncorrectFormatPhoneMSG()" );

		document.getElementById( phoneFieldsToFormat [ index ] ).focus();
		return false;
	}


	var extFieldValue = document.getElementById( fieldIdToCheck + "Ext" );
	if ( extFieldValue != null && Trim( extFieldValue.value ).length > 0 ) {

		for (var i=0; i < extFieldValue.value.length; i++) {
			temp = "" + extFieldValue.value.substring(i,i+1);

			matchExtension =temp.match( phoneExtDelimiters );
			if( matchExtension == null){
				eval( "alert" + getLanguage() +"IncorrectFormatEXTPhoneMSG()" );
				return false;
			}
		}
	}


	phoneFieldsToFormat [ phoneFieldIndex++ ] = fieldIdToCheck;
	return true;
}

function formatCAFRPhoneField( fieldIdToCheck ) {

	//document.getElementById( fieldIdToCheck ).maxLength=12;

	var phoneField 			= Trim( document.getElementById( fieldIdToCheck ).value );
	var phoneNumberDelimiters 	= /^[-\.\s]+$/;
	var phonePat			= /^\d{3}([-\.\s])?(\d{3})([-\.\s])?(\d{4})$/;
	var phoneFieldValue 		= "";
	var phoneExtDelimiters		= /^[0-9]+$/;

	if ( phoneField.length == 0) {
		return true;
	}


	var matchArray=phoneField.match( phonePat );
	if ( matchArray == null) {
		eval ( "alert" + getLanguage() + "CAFRIncorrectFormatPhoneMSG()");

		document.getElementById( fieldIdToCheck ).focus();
		return false;
	}

	if ( Trim( removeNonDigits( phoneField, phoneNumberDelimiters ) ).length < 10 ) {
		eval( "alert" + getLanguage() +"CAFRIncorrectFormatPhoneMSG()" );

		document.getElementById( phoneFieldsToFormat [ index ] ).focus();
		return false;
	}


	var extFieldValue = document.getElementById( fieldIdToCheck + "Ext" );
	if ( extFieldValue != null && Trim( extFieldValue.value ).length > 0 ) {

		for (var i=0; i < extFieldValue.value.length; i++) {
			temp = "" + extFieldValue.value.substring(i,i+1);

			matchExtension =temp.match( phoneExtDelimiters );
			if( matchExtension == null){
				eval( "alert" + getLanguage() +"CAFRIncorrectFormatEXTPhoneMSG()" );
				return false;
			}
		}
	}


	phoneFieldsToFormat [ phoneFieldIndex++ ] = fieldIdToCheck;
	return true;
}

function phoneFieldFormatting() {
	var phoneNumberDelimiters 	= /^[-\.\s()]+$/;

	for( index=0; index < phoneFieldIndex; index++ ) {
		var phoneField 	= Trim( document.getElementById( phoneFieldsToFormat [ index ] ).value );

		document.getElementById( phoneFieldsToFormat [ index ] ).value = removeNonDigits( phoneField, phoneNumberDelimiters );
		if ( document.getElementById( phoneFieldsToFormat [ index ] + "Ext" ) != null &&
								 Trim( document.getElementById( phoneFieldsToFormat [ index ] + "Ext" ).value ).length > 0 ) {

			document.getElementById( phoneFieldsToFormat [ index ] ).maxLength=15;
			document.getElementById( phoneFieldsToFormat [ index ] ).value = 	document.getElementById( phoneFieldsToFormat [ index ] ).value +
																Trim( document.getElementById( phoneFieldsToFormat [ index ] + "Ext" ).value);
			document.getElementById( phoneFieldsToFormat [ index ] + "Ext" ).value = "";
		}
	}

	return true;
}
/*************************************************************************************************************************************/



function removeNonDigits( phoneField, delimeters ){

    var returnString = "";
	for ( var phoneFieldIndex=0; phoneFieldIndex < phoneField.length; phoneFieldIndex++ ) {
		temp = phoneField.substring(phoneFieldIndex, phoneFieldIndex+1);
		matchPhone=temp.match( delimeters );
		if( matchPhone == null){
			returnString += temp;
		}
	}

    return returnString;
}

function formatCustomFormFields(){

	var customCounter = 1;
	var fieldRefNames 	= document.getElementById("leadForm");
	for (var myCounter=0; myCounter< customField.length; myCounter++) {
		var fieldRefLabel = "";

		// In order to append long strings we need to remove the imposing maxLength.
		document.getElementById( customField[ myCounter ] ).removeAttribute('maxLength');

		if ( document.getElementById( customField[ myCounter ] ).type == "radio") {
			fieldRefLabel = document.getElementById( customField[ myCounter ] + "Label");
			var fieldRefName2 = document.getElementsByName( document.getElementById( customField[ myCounter ] ).name );
			var referenceName = document.getElementById( customField[ myCounter ] ).name
			var testLength= fieldRefName2.length
			for (var myCounter2=0; myCounter2< testLength; myCounter2++) {
				var temp = document.getElementById( referenceName + "Radio" + (myCounter2+1) );

				temp.name = "Request_Custom_" + customCounter;
				temp.id = "Request_Custom_" + + customCounter + "Radio" + (myCounter2+1);
				if ( Trim(temp.value).length > 0 ) {
					temp.value = ReplaceTags(fieldRefLabel.innerHTML) + ": " + temp.value;
				}
			}

		} else if ( document.getElementById( customField[ myCounter ] ).type == "checkbox") {

			fieldRefLabel = document.getElementById( customField[ myCounter ] + "Label");

			document.getElementById( customField[ myCounter ] ).name = "Request_Custom_" + customCounter;
			document.getElementById( customField[ myCounter ] ).id = "Request_Custom_" + customCounter;

			if ( document.getElementById( "Request_Custom_" + customCounter ).checked == 1 ) {
				document.getElementById( "Request_Custom_" + customCounter ).value = ReplaceTags(fieldRefLabel.innerHTML) + ": true";
			} else {
				document.getElementById( "Request_Custom_" + customCounter ).value = ReplaceTags(fieldRefLabel.innerHTML) + ": false";
			}

		} else if ( document.getElementById( customField[ myCounter ] ).type == "select-one" ) {

			if ( Trim(document.getElementById( customField[ myCounter ] ).value).length > 0 ) {
				fieldRefLabel = document.getElementById( customField[ myCounter ] + "Label");

				document.getElementById( customField[ myCounter ] ).name = "Request_Custom_" + customCounter;
				document.getElementById( customField[ myCounter ] ).id = "Request_Custom_" + customCounter;

				var select = document.getElementById( "Request_Custom_" + customCounter );
				select.options[ select.selectedIndex ].value = ReplaceTags(fieldRefLabel.innerHTML) + ": " + select.options[ select.selectedIndex ].value;
			}

		} else {

			fieldRefLabel = document.getElementById( customField[ myCounter ] + "Label");
			document.getElementById( customField[ myCounter ] ).name 	= "Request_Custom_" + customCounter;
			document.getElementById( customField[ myCounter ] ).id 		= "Request_Custom_" + customCounter;
			if ( Trim(document.getElementById( "Request_Custom_" + customCounter ).value).length > 0 ) {
				var temp = ReplaceTags(fieldRefLabel.innerHTML) + document.getElementById( "Request_Custom_" + customCounter ).value;

				document.getElementById( "Request_Custom_" + customCounter ).value 	= ReplaceTags(fieldRefLabel.innerHTML) + ": " +
																				Trim(document.getElementById( "Request_Custom_" + customCounter ).value);
			}
		}

		customCounter++;
	}
}


function setCommerceParams() {
	
		setCommerceParamsNew();

}



function setCommerceParamsNew() {

	var form = document.getElementById("leadForm");
	var theCommerceParams = "";
	var fieldExpression=/%[C,D,E,F][0,1,2,3,5,8,9,A,C,D]/; // | %u01[5B,5A,38,06,07,39,7A,79]/;
	
	for (i=0; i < form.length; i++){

		if (form[i].name == "commerceParams"){
			continue;
		}

		theCommerceParams += "," + form[i].name;

		if ( form[i].type == "select-one" ){
			var select = document.getElementById( form[i].id );
			
		} else if ( form[i].name != "ru" ){
		
			/**** Convert French accented chars ****/
			form[i].value = CAFRScrub( form[i].value );
	
			var temp = escape( form[i].value );
			var charUpdates = false;
			
			while ( temp.search( fieldExpression ) != -1 ){
				
				var matchArray = temp.match( fieldExpression );
				if ( matchArray != null ) {
					temp = temp.replace( matchArray, replaceSpecialChar( matchArray ) );
					charUpdates = true;
				}
			}
			
			if( charUpdates ) {
				form[i].value = temp;
			}
						
		}

	}

	theCommerceParams = theCommerceParams.substring(1,theCommerceParams.length);
	form["commerceParams"].value = theCommerceParams;
}


function setCommerceParamsOld() {

	var form = document.getElementById("leadForm");
	var theCommerceParams = "";
	var fieldExpression=/%[C,D,E,F][0,1,2,3,5,8,9,A,C,D]/; // | %u01[5B,5A,38,06,07,39,7A,79]/;
	
	for (i=0; i < form.length; i++){

		if (form[i].name == "commerceParams"){
			continue;
		}

		theCommerceParams += "," + form[i].name;

		if ( form[i].type == "select-one" ){
			var select = document.getElementById( form[i].id );
			select.options[ select.selectedIndex ].value = escape(select.options[ select.selectedIndex ].value);

		} else if ( form[i].name != "ru" ){
			
			form[i].value = escape(form[i].value);
			while ( form[i].value.search( fieldExpression ) != -1 ){

				var matchArray = form[i].value.match( fieldExpression );
				if ( matchArray != null ) {
					form[i].value = form[i].value.replace( matchArray, replaceSpecialChar( matchArray ) );
				}
			}
		}
	}

	theCommerceParams = theCommerceParams.substring(1,theCommerceParams.length);
	form["commerceParams"].value = theCommerceParams;
}


function enableOtherField( fieldID, fieldToDisable ) {

	var choice = document.getElementById( fieldID );
	if ( choice.options[choice.selectedIndex].value  == "Other" ) {
		document.getElementById( fieldToDisable ).disabled = false;
	} else {
		document.getElementById( fieldToDisable ).disabled = true;
	}
}

function needToHandleInquiryType ( fieldID ) {

	var choice = document.getElementById( fieldID );
	if ( choice.options[choice.selectedIndex].value  == "Other" ) {
		document.getElementById( fieldID + "Other" ).disabled = false;
		choice.options[choice.selectedIndex].value = document.getElementById( fieldID + "Other" ).value;
	}

	return true;
}


function addRoutingKeyToFormName(){

	var formName =	Trim(document.getElementById("Form_Name").value);
	formName = decodeURI(formName);

	//If routing based on a single choice select box, append the value
	var select = document.getElementById(emailRoutingKey);
//
//	if ( select.type == "select-one"){
//		if ( select.value == "Other" && Trim(document.getElementById( emailRoutingKey + "Other").value).length > 0 ) {
//			document.getElementById("Form_Name").value =
//				formName + "-" + document.getElementById( emailRoutingKey + "Other").value;
//
//		} else if ( select.value != "Other" && select.options[select.selectedIndex].value.length > 0)  {
//			document.getElementById("Form_Name").value =
//				formName + "-" + select.options[select.selectedIndex].value;
//
//		}
//	}

	if ( select.type == "select-one"){
		if ( select.options[select.selectedIndex].value.length > 0)  {
			document.getElementById("Form_Name").value =
				formName + "-" + select.options[select.selectedIndex].value;

		}
	}

}


function isValidEmail (emailName) {

	var emailStr = Trim(document.getElementById( emailName ).value);

	//Check for 0 length and return in the case when field is not required
	if ( emailStr <= 0){
		return true;
	}


	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^(\d{1,3})[.](\d{1,3})[.](\d{1,3})[.](\d{1,3})$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom + ")*$");
	var matchArray=emailStr.match(emailPat);
	if (matchArray == null) {
		eval( "alert" + getLanguage() +"IncorrectEmailAddressMSG()" );

		document.getElementById( emailName ).focus();
		return false;
	}


	var user=matchArray[1];
	var domain=matchArray[2];
	if (user.match(userPat) == null) {
		//alert(user.match(userPat));
		eval( "alert" + getLanguage() +"IncorrectEmailAddressMSG()" );

		document.getElementById( emailName ).focus();
		return false;
	}

	var IPArray = domain.match(ipDomainPat);
	if (IPArray != null) {
		for (var i = 1; i <= 4; i++) {
			if (IPArray[i] > 255) {
				updateFormLabel( emailName, false);
				eval( "alert" + getLanguage() +"IncorrectEmailAddressMSG()" );

				document.getElementById( emailName ).focus();
				return false;
			}
		}

		return true;
	}

	var domainArray=domain.match(domainPat);
	if (domainArray == null) {
		eval( "alert" + getLanguage() +"IncorrectEmailAddressMSG()" );

		document.getElementById( emailName ).focus();
		return false;
	}

	var atomPat=new RegExp(atom,"g");
	var domArr=domain.match(atomPat);
	var len=domArr.length;
	if ((domArr[domArr.length-1].length < 2) || (domArr[domArr.length-1].length > 3)) {
		eval( "alert" + getLanguage() +"IncorrectEmailAddressMSG()" );

		document.getElementById( emailName ).focus();
		return false;
	}

	if (len < 2) {
		eval( "alert" + getLanguage() +"IncorrectEmailAddressMSG()" );

		document.getElementById( emailName ).focus();
		return false;
	}

	return true;
}


function isValidCAFREmail (emailName) {

	var emailStr = Trim(document.getElementById( emailName ).value);

	//Check for 0 length and return in the case when field is not required
	if ( emailStr <= 0){
		return true;
	}


	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^(\d{1,3})[.](\d{1,3})[.](\d{1,3})[.](\d{1,3})$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom + ")*$");
	var matchArray=emailStr.match(emailPat);
	if (matchArray == null) {
		eval( "alert" + getLanguage() +"CAFRIncorrectEmailAddressMSG()" );

		document.getElementById( emailName ).focus();
		return false;
	}


	var user=matchArray[1];
	var domain=matchArray[2];
	if (user.match(userPat) == null) {
		//alert(user.match(userPat));
		eval( "alert" + getLanguage() +"CAFRIncorrectEmailAddressMSG()" );

		document.getElementById( emailName ).focus();
		return false;
	}

	var IPArray = domain.match(ipDomainPat);
	if (IPArray != null) {
		for (var i = 1; i <= 4; i++) {
			if (IPArray[i] > 255) {
				updateFormLabel( emailName, false);
				eval( "alert" + getLanguage() +"CAFRIncorrectEmailAddressMSG()" );

				document.getElementById( emailName ).focus();
				return false;
			}
		}

		return true;
	}

	var domainArray=domain.match(domainPat);
	if (domainArray == null) {
		eval( "alert" + getLanguage() +"CAFRIncorrectEmailAddressMSG()" );

		document.getElementById( emailName ).focus();
		return false;
	}

	var atomPat=new RegExp(atom,"g");
	var domArr=domain.match(atomPat);
	var len=domArr.length;
	if ((domArr[domArr.length-1].length < 2) || (domArr[domArr.length-1].length > 3)) {
		eval( "alert" + getLanguage() +"CAFRIncorrectEmailAddressMSG()" );

		document.getElementById( emailName ).focus();
		return false;
	}

	if (len < 2) {
		eval( "alert" + getLanguage() +"CAFRIncorrectEmailAddressMSG()" );

		document.getElementById( emailName ).focus();
		return false;
	}

	return true;
}


function compareEmailFields( emailName ) { 

	var originalEmailField 		= Trim( document.getElementById( "email" ).value ); 
	var emailFieldToCompareStr 	= Trim( document.getElementById( emailName ).value ); 
	var areFieldsSimilar 		= true;
	
	if ( originalEmailField.length > 0 || emailFieldToCompareStr.length > 0 ){
		if ( originalEmailField.toLowerCase() != emailFieldToCompareStr.toLowerCase() ) { 
			eval( "alert" + getLanguage() +"IncorrectMatchingEmailAddressMSG()" );
			areFieldsSimilar = false; 
		} 
	} 
	
	//updateFormLabel( emailName, areFieldsSimilar ); 
//	updateFormLabel( "email", areFieldsSimilar ); 
	return areFieldsSimilar; 
}

function compareCAFREmailFields( emailName ) { 

	var originalEmailField 		= Trim( document.getElementById( "email" ).value ); 
	var emailFieldToCompareStr 	= Trim( document.getElementById( emailName ).value ); 
	var areFieldsSimilar 		= true;
	
	if ( originalEmailField.length > 0 || emailFieldToCompareStr.length > 0 ){
		if ( originalEmailField.toLowerCase() != emailFieldToCompareStr.toLowerCase() ) { 
			eval( "alert" + getLanguage() +"CAFRIncorrectMatchingEmailAddressMSG()" );
			areFieldsSimilar = false; 
		} 
	} 
	
	//updateFormLabel( emailName, areFieldsSimilar ); 
//	updateFormLabel( "email", areFieldsSimilar ); 
	return areFieldsSimilar; 
}


function validateOptIn ( fieldIdToCheck ) {
	var optInSelected = document.getElementById( fieldIdToCheck ).checked;
	var emailStr = Trim ( document.getElementById( "email" ).value );
	var areFieldsSimilar 		= true;
	
	if ( optInSelected ){
		//Check for 0 length and return in the case when field is not required
		if ( emailStr <= 0 ){
			eval( "alert" + getLanguage() + "RequiredEmailAddressMSG()" );
	
			document.getElementById( "email" ).focus();
			areFieldsSimilar = false;
			updateFormLabel( "email", areFieldsSimilar ); 
		}
	}
	
	// Update only if false
	//updateFormLabel( "email", areFieldsSimilar ); 
	return areFieldsSimilar;
}


function wasEmailPopulated ( fieldIdToCheck ) {
	var typeSelected = document.getElementById( fieldIdToCheck ).value;
	var emailStr = Trim ( document.getElementById( "email" ).value );
	var emailPopulated 		= true;
	
	if ( typeSelected == "Billing" ){
		if ( emailStr <= 0 ){
			eval( "alert" + getLanguage() + "NeedEmailAddressForBillingMSG()" );
	
			document.getElementById( "email" ).focus();
			emailPopulated = false;
		}
		
	}
	
	updateFormLabel( "email", emailPopulated ); 
	return emailPopulated;
}


function isValidPostal( fieldIdToCheck ) {

	var postalField		= Trim( document.getElementById( fieldIdToCheck ).value );
	var postalPattern	=/^\d{5}([-\.\s])?(\d{4})?$/;
	var postalDelimiters 	= /^[-\.\s]+$/;
	var postalAcceptedChars = /^[0-9,-]/;
	
	if ( postalField.length <= 0){
		return true;
	}

	invalidChars = postalField.match( postalAcceptedChars );
	if ( invalidChars == null ) {
		eval( "alert" + getLanguage() +"InvalidZipCodeCharsMSG()" );
		return false;
	}
	
	
	matchPostal=postalField.match( postalPattern );
	if(matchPostal == null){
		eval( "alert" + getLanguage() +"IncorrectZipCodeMSG()" );
		return false;
	}
	
	document.getElementById( fieldIdToCheck ).value = removeNonDigits( postalField, postalDelimiters );
	return true;
}



function isValidCAPostal( fieldIdToCheck ) {

	var postalField		= Trim( document.getElementById( fieldIdToCheck ).value );
	var postalPattern	= /^[a-zA-Z]\d[a-zA-Z]\d[a-zA-Z]\d$/;
	var postalAcceptedChars = /^[0-9,a-zA-Z]/;
	
	if ( postalField.length <= 0){
		return true;
	}
	
	postalField = postalField.replace(/\s/g, "");
	
	matchPostal=postalField.match( postalPattern );
	if(matchPostal == null){
		eval( "alert" + getLanguage() +"IncorrectPostalCodeMSG()" );
		return false;
	}
	
	document.getElementById( fieldIdToCheck ).value = postalField;
	return true;
}


function isValidCAFRPostal( fieldIdToCheck ) {

	var postalField		= Trim( document.getElementById( fieldIdToCheck ).value );
	var postalPattern	= /^[a-zA-Z]\d[a-zA-Z]\d[a-zA-Z]\d$/;
	var postalAcceptedChars = /^[0-9,a-zA-Z]/;
	
	if ( postalField.length <= 0){
		return true;
	}
	
	postalField = postalField.replace(/\s/g, "");
	
	matchPostal=postalField.match( postalPattern );
	if(matchPostal == null){
		eval( "alert" + getLanguage() +"CAFRIncorrectPostalCodeMSG()" );
		return false;
	}
	
	document.getElementById( fieldIdToCheck ).value = postalField;
	return true;
}




var regExp = /<\/?[^>]+>/gi;
function ReplaceTags(xStr){
	xStr = xStr.replace(regExp,"");
	return xStr;
}


function changeText (textToChange, colorVal) {
	var x = new getObj(textToChange);
	x.style.color = colorVal;
}


function getObj(name){

  if (document.getElementById)  {
  	this.obj = document.getElementById(name);
	this.style = document.getElementById(name).style;

  } else if (document.all) {
	this.obj = document.all[name];
	this.style = document.all[name].style;

  } else if (document.layers) {
   	this.obj = document.layers[name];
   	this.style = document.layers[name];

  }
}



function fixPortalAnchors(){

	if(anchorsFixed == false){

		//Need to handle hrefs from AREA tags also.
		//Becuse getElementByTagName doesn't return an array
		//we can't just get a list of A and AREA and concatenate
		//Instead create a third array and push the nodes on
		//one by one.

		var anchors = new Array();
		var as = document.getElementsByTagName('a');
		var areas = document.getElementsByTagName('area');

		for (var i=0; i<as.length; i++){
			anchors.push(as[i]);
		}

		for (var i=0; i<areas.length; i++){
			anchors.push(areas[i]);
		}

		for(var x=0 ; x<anchors.length ; x++){
			if(anchors[x].href) {
			var h = anchors[x].href.toString();

			if(loggedIn && loggedIn == true) {
				//URL Optimization - leave this for legacy support
				if(h.match(/\/portal\//) != null){
					h = h.replace(/\/portal\//, "/myportal/");
				}
				else if(h.match(/\/myportal\//) != null){
					//Do nothing
				}
				else{
					//Can't just prepend to any URL because /wps/wcm and microsite urls need to be
					//ignored.  Do positive matching instead.
					//Entry for "" represents authenticated home e.g. www.adt.com/auth/ -> www.adt.com/auth/wps/myportal/adt/

					//Check for special case of homepage URL first
					if (h.substr(h.length-1-4,h.length-1) == "auth/"){
						h = h.replace(/\/auth\//, "/auth/wps/myportal/adt/");						
					}
					
					var contexts = ["/for_your_home/",
										"/small_business/",
										"/medium_large_business/",
										"/government/",
										"/about_adt/",
										"/contact/",
										"/customer_service/",
										"/community/",
										"/global/",
										"/newsletter/",
										"/news/",
										"/coloradocareers/",
										"/dealer_licenses/",
										"/legal/",
										"/licenses/",
										"/privacy/",
										"/ratechange/",
										"/safecity/",
										"/security_products/",
										"/sitemap/",
										"/terms_of_use/",
										"/trademark/"];
					
					for (var i=0; i<contexts.length; i++){
						//Match /auth/ plus context to be sure context is at begninning of path													^[5]
						if(h.indexOf("/auth"+contexts[i]) > -1){
							h = h.replace(/\/auth\//, "/auth/wps/myportal/adt/");
						}
					}

				}
				
			}
			if(h.indexOf("http://sy00059")==0){
				h = h.substring(h.indexOf("/wps"));
			}

			/* Defer fix - authors typically don't navigate using this method
			//Add only /wps/myportal/adt on sy00059 when logged in
			if(window.location.href.indexOf("http://sy00059") == 0){
				if(loggedIn && loggedIn == true) {
					if(h.match(/\/myportal\//) != null){
					//Do nothing
					}
					else{
						h = h.replace(new RegExp("/"+location.hostname+"/"), location.hostname + "/wps/myportal/adt/");
					}
				}
			}
			*/

			if(window.location.href.indexOf("http://sy00087.adt.com/public") == 0){
				if(h.indexOf("/wps")==0){
					h = "/public"+h;
				}
			}

			anchors[x].href = h.toString();
			}
		}

		//Process form actions also
		//Don't worry about environmental exceptions
		var forms = document.getElementsByTagName('form');

		for(var x=0 ; x<forms.length ; x++){
			if(forms[x].action) {
				var h = forms[x].action.toString();
	
				if(loggedIn && loggedIn == true) {
				 	h = h.replace(/\/portal\//, "/myportal/");
				}
	
				forms[x].action = h.toString();
			}
		}
		//Also fix the thank you url that commerce will use
		if(loggedIn && loggedIn == true) {
			if(document.getElementById("thank_you_url")){
				var tu_url = document.getElementById("thank_you_url").value;
			 	tu_url = tu_url.replace(/\/portal\//, "/myportal/");
			 	document.getElementById("thank_you_url").value = "/auth" + tu_url;
			 }
		}
		
		//End form action processing update
		
		anchorsFixed = true;
	}
}


function Trim(TRIM_VALUE){
	if(TRIM_VALUE.length < 1){
		return"";
	}
	TRIM_VALUE = RTrim(TRIM_VALUE);
	TRIM_VALUE = LTrim(TRIM_VALUE);
	if(TRIM_VALUE==""){
	return "";
	}
	else{
	return TRIM_VALUE;
	}
	} //End Function

	function RTrim(VALUE){
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	if(v_length < 0){
	return"";
	}
	var iTemp = v_length -1;

	while(iTemp > -1){
	if(VALUE.charAt(iTemp) == w_space){
	}
	else{
	strTemp = VALUE.substring(0,iTemp +1);
	break;
	}
	iTemp = iTemp-1;

	} //End While
	return strTemp;

	} //End Function

	function LTrim(VALUE){
	var w_space = String.fromCharCode(32);
	if(v_length < 1){
	return"";
	}
	var v_length = VALUE.length;
	var strTemp = "";

	var iTemp = 0;

	while(iTemp < v_length){
	if(VALUE.charAt(iTemp) == w_space){
	}
	else{
	strTemp = VALUE.substring(iTemp,v_length);
	break;
	}
	iTemp = iTemp + 1;
	} //End While
	return strTemp;
	} //End Function


function getTodaysDate(){
	var todaysDate = new Date()
	var month = todaysDate.getMonth() + 1
	var day = todaysDate.getDate()
	var year = todaysDate.getFullYear()
	var separator = ","

	var newDate = year + separator +  month + separator +  day;
	return newDate;

}

function createDateDropdown() {

	var ddbox = document.forms["leadForm"].apptDate;
	if (ddbox.length > 1)
	{
		return;
	}
	//var field = document.getElementById("date").value;
	var field = getTodaysDate();

	//Create array of year, month, day
	var datePars = field.split(",");
	var today = new Date(datePars[0], datePars[1], datePars[2]);
//	alert("Pars: " + datePars[0] + datePars[1] + datePars[2]);
	//create list of days between two and ten business days out
	var dayList = new Array(9);
	var tempDate = new Date(today);
	var tempDateMs = tempDate.getTime();	//use ms as basis for calculating time

	//For date arithmetic
	var oneMinute = 60 * 1000;
	var oneHour = oneMinute * 60;
	var oneDay = oneHour * 24;

	var startRange = 3;
	var endRange = 19;
	var i = startRange;
	var j =	startRange;
	while(j < endRange){
		tempDate.setTime( tempDateMs + ( i*oneDay ) );
//		alert( i*oneDay );
		day = tempDate.getDay();
		if (day != 0){ //Don't allow scheduling on Sunday
			var date = tempDate.getDate();
			var month = tempDate.getMonth();
			var year = tempDate.getYear();
//alert("YEAR: " + year);
			var optionText = getDay(day) + " ";
			optionText = optionText + getMonth(month) + " ";
			optionText = optionText + date + ", " + year;

			var optionValue;
			if (month < 10){
				optionValue = "0" + (month+1) + "/";
			}
			else {
				optionValue = (month+1) + "/";
			}

			if (date < 10){
				optionValue = optionValue + "0" + date + "/";
			}
			else {
				optionValue = optionValue + date + "/";
			}
			optionValue = optionValue + year;

			ddbox.options[ddbox.length] =
				new Option(optionText, optionValue);

			j++;
		}
		else{
			ddbox.options[ddbox.length] =
				new Option("", "");
		}
		i++;
	}
}



function validateApptDate( field ){

	var field = Trim(document.getElementById( field ).value);

	//var dateRegExpression = "";///\d\d[/]\d\d[/]\d\d\d\d/;
	var dateRegExpression = /^([0-9]){2}(\/|-){1}([0-9]){2}(\/|-)([0-9]){4}$/;

	if (!field.match(dateRegExpression)){
		alert('Please enter appointment date according to format mm/dd/yyyy.');
		return false;
	}

	//Check month, day, year for a real date
	var tmp = null;
	tmp = field.split("/");

	var month = parseInt(tmp[0],10);
	if (month < 1 || month > 12){
		alert('Please enter an appointment month between 1 and 12.');
		return false;
	}

	var day = parseInt(tmp[1],10);
	var monthMax = new Array(31,29,31,30,31,30,31,31,30,31,30,31);
	if (day < 1 || day > monthMax[month-1]){
		alert('Please enter an appointment day between 1 and ' + monthMax[month-1] + '.');
		return false;
	}

	var year = parseInt(tmp[2],10);
	if (year < 2005){
		alert('Please enter an appointment year 2005 or greater.');
		return false;
	}

	return true;
}



function validateApptTime( field ){
	var field = Trim(document.getElementById( field ).value);

	var dateRegExpression = /\d\d[:]\d\d/;
	if (!field.match(dateRegExpression)){
		alert('Please enter appointment time in 24-hour time format 00:00.');
		return false;
	}

	//Check hour, minute for valid 24-hour time
	var tmp = null;
	tmp = field.split(":");

	var hour = parseInt(tmp[0],10);
	if (hour > 24){
		alert('Please enter an appointment time hour between 0 and 24.');
		return false;
	}

	var minute = parseInt(tmp[1],10);
	if (minute > 59){
		alert('Please enter an appointment time minute between 00 and 59');
		return false;
	}

	return true;
}

function validateMemberID ( field ){
	var field = Trim(document.getElementById( field ).value);

	var dateRegExpression = /\d/;
	if 	(field.length > 8){
		alert('Please enter USAA member number eight digits or less');
		return false;
	}
	var valid = "0123456789";
	for (var i=0; i < field.length; i++) {
		temp = "" + field.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") {
			alert('Please enter USAA member number as numeric digits');
			return false;
		}
	}

	return true;
}

function getMonth(month){

	var months = new Array(12);
	months[0] = "Jan";
	months[1] = "Feb";
	months[2] = "Mar";
	months[3] = "Apr";
	months[4] = "May";
	months[5] = "Jun";
	months[6] = "Jul";
	months[7] = "Aug";
	months[8] = "Sep";
	months[9] = "Oct";
	months[10] = "Nov";
	months[11] = "Dec";

	return months[month];
}

function getDay(day){

	var days = new Array(7);
	days[0] = "Sun";
	days[1] = "Mon";
	days[2] = "Tue";
	days[3] = "Wed";
	days[4] = "Thu";
	days[5] = "Fri";
	days[6] = "Sat";

	return days[day];
}

/**************** Alert message for the required field. ***************/
function alertRequiredPhoneMSG() {
	alert('Please enter the correct phone field format.\nexample, 333-333-4444');
}

function alertSPNRequiredPhoneMSG() {
	alert('Por favor entre un numero telef\363nico con formato correcto.\nPor ejemplo 333-333-4444');
}
/**************** END Alert message for the required field. ***************/


/**************** Alert message for the incorrect field. ***************/
function alertIncorrectFormatPhoneMSG() {
	alert('Please enter the correct phone field format.\nexample, 333-333-4444');
}

function alertSPNIncorrectFormatPhoneMSG() {
	alert('Por favor entre un numero telef\363nico con formato correcto.\nPor ejemplo 333-333-4444');
}
/**************** Alert message for the incorrect field. ***************/

/**************** Alert message for the incorrect field. ***************/
function alertIncorrectFormatEXTPhoneMSG() {
	alert('The extension field should be numeric. Please amend and try again.');
}

function alertSPNIncorrectFormatEXTPhoneMSG() {
	alert('La extensi\363n telef\363nica debe ser num\351rica. Por favor corrija y trate otra vez.');
}
/**************** Alert message for the incorrect field. ***************/


/**************** Alert message for the incorrect email address field. ***************/
function alertIncorrectMatchingEmailAddressMSG() {
	alert('The e-mail addresses do not match. Please try again.');
}

function alertSPNIncorrectMatchingEmailAddressMSG() {
	alert('Las direcciones de correo electr\363nico no coinciden. Intente otra vez por favor.');
}
/**************** Alert message for the incorrect email address field. ***************/

/**************** Alert message for the incorrect email address field. ***************/
function alertIncorrectEmailAddressMSG() {
	alert('A valid e-mail address is required.Please try again.');
}

function alertSPNIncorrectEmailAddressMSG() {
	alert('Una direcci\363n de e-mail es requerido. Por favor corrija y trate otra vez.');
}
/**************** Alert message for the incorrect email address field. ***************/


/**************** Alert message for the required email address field. ***************/
function alertNeedEmailAddressForBillingMSG() {
	alert("You have selected the billing inquiry. A valid e-mail address is \nrequired for this process. Please try again.");
}

function alertSPNNeedEmailAddressForBillingMSG() {
	alert("You have selected the billing inquiry. A valid e-mail address is \nrequired for this process. Por favor corrija y trate otra vez.");
}
/**************** Alert message for the incorrect email address field. ***************/


/**************** Alert message for the required email address field. ***************/
function alertRequiredEmailAddressMSG() {
	alert("You have selected to recieve email offers but have not provided an \ne-mail address. Please try again.");
}

function alertSPNRequiredEmailAddressMSG() {
	alert("Usted ha escogido recibir las ofertas de correo electr\363nico pero no ha proporcionado una direcci\363n \nde correo electr\363nico. Proporcione por favor una direcci\363n v\341lida de correo electr\363nico.");
}
/**************** Alert message for the incorrect email address field. ***************/


/**************** Alert message for the incorrect zip code field. ***************/
function alertIncorrectZipCodeMSG() {
	alert("Please enter 5 digit zip code\nor 9 digit zip code with the dash.");
}

function alertSPNIncorrectZipCodeMSG() {
	alert('Por favor entre un correo postal de 5 o 9 d\355gitos incluyendo guiones.');
}
/**************** Alert message for the incorrect zip code field. ***************/

	/**************** Alert message for the incorrect zip code field. ***************/
function alertInvalidZipCodeCharsMSG() {
	alert("Invalid characters in your zip code.  Please try again.");
}

function alertSPNInvalidZipCodeCharsMSG() {
	alert('Hay ch\341rteres inv\341lidos en su correo postal. Por favor corrija y trate otra vez.');
}
/**************** Alert message for the incorrect postal code field. ***************/
function alertIncorrectPostalCodeMSG() {
	alert("Please enter 6 character alphanumeric postal code.");
}

function alertInvalidPostalCodeCharsMSG() {
	alert("Invalid characters in your postal code.  Please try again.");
}

/**************** Alert messages for the French Canadian Forms ***************/

function alertCAFRIncorrectPostalCodeMSG() {
	alert("Veuillez entrer 6 caract\u00E8res alphanum\u00E9riques pour le code postal.");
}

function alertCAFRIncorrectEmailAddressMSG() {
	alert('Une adresse courriel valide est n\u00E9cessaire. Veuillez essayer \u00E0 nouveau.');
}

function alertCAFRIncorrectMatchingEmailAddressMSG() {
	alert('Les adresses courriel ne correspondent pas. Veuillez essayer \u00E0 nouveau.');
}

function alertCAFRIncorrectFormatPhoneMSG() {
	alert('Veuillez entrer le format de num\u00E9ro de t\u00E9l\u00E9phone ad\u00E9quat. \nExemple. 333-333-4444');
}

function alertCAFRIncorrectFormatEXTPhoneMSG() {
	alert('L\u0027extension doit \u00EAtre num\u00E9rique. Veuillez corriger et essayer \u00E0 nouveau.');
}


/**************** TEMPORARY FORMATTING SPECIAL CHARACTERS **********************************/
var specialCharList = new Object();

specialCharList["%C0"]="A";
specialCharList["%C1"]="A";
specialCharList["%C8"]="E";
specialCharList["%C9"]="E";
specialCharList["%CC"]="I";
specialCharList["%CD"]="I";
specialCharList["%D2"]="O";
specialCharList["%D3"]="O";
specialCharList["%D9"]="U";
specialCharList["%DA"]="U";
specialCharList["%E0"]="a";
specialCharList["%E1"]="a";
specialCharList["%E8"]="e";
specialCharList["%E9"]="e";
specialCharList["%EC"]="i";
specialCharList["%ED"]="i";
specialCharList["%F2"]="o";
specialCharList["%F3"]="o";
specialCharList["%F9"]="u";
specialCharList["%FA"]="u";
specialCharList["%C3"]="A";
specialCharList["%D1"]="N";
specialCharList["%D5"]="O";
specialCharList["%E3"]="a";
specialCharList["%F1"]="n";
specialCharList["%F5"]="o";

specialCharList["%u015A"]="S";
specialCharList["%u015B"]="s";
specialCharList["%u0106"]="C";
specialCharList["%u0107"]="c";
specialCharList["%u0139"]="L";
specialCharList["%u0138"]="l";
specialCharList["%u017A"]="Z";
specialCharList["%u0179"]="z";


// Function used to replace the special characters with value located in list.
function replaceSpecialChar( valueToReplace ) {

	if (specialCharList [ valueToReplace ] == null ){
		return valueToReplace;
	}
	
	return specialCharList [ valueToReplace ];
}

/**************** TEMPORARY FORMATTING FRENCH CANADIAN SPECIAL CHARACTERS **********************************/

function CAFRScrub(str)
{
var s=str;

var rExps=[ /[\xC0-\xC4]/g, /[\xE0-\xE4]/g,
	/[\xC8-\xCB]/g, /[\xE8-\xEB]/g,
	/[\xCC-\xCF]/g, /[\xEC-\xEF]/g,
	/[\xD2-\xD6]/g, /[\xF2-\xF6]/g,
	/[\xD9-\xDC]/g, /[\xF9-\xFC]/g,
	/\xC7/g, /\xE7/g ];

var repChar=['A','a','E','e','I','i','O','o','U','u','C','c'];

for(var i=0; i<rExps.length; i++)
s=s.replace(rExps[i],repChar[i]);

return s;
}