
/* ###### GENERAL HELPER FUNCTIONS ######  */

function validationAlert(strAlert, hField) {
	// Displays an alert, focuses a form field, and returns false.
	alert(strAlert);
	try { hField.focus(); } catch(ex) {}
	return false;
}


/* ####### STRING VALIDATION ####### */

function isValidFirstName(strName) {
	if (/[^A-Za-z -]/.test(strName)) { return false; }
	return true;
}

function isValidLastName(strName) {
	if (/[^A-Za-z -]/.test(strName)) { return false; }
	return true;
}

function isValidStreetAddress(strAddress) {
	if (strAddress.length < 3) { return false; }
	if (strAddress.replace(/[^0-9]/g, "").length < 1) { return false; }
	if (strAddress.replace(/[^A-Za-z]/g, "").length < 1) { return false; }
	return true;
}

function isValidCity(strCity) {
	if (strCity.length < 2) { return false; }
	if (/[^A-Za-z -]/.test(strCity)) { return false; }
	return true;
}

function isValidEntirePhone(strPhone) {
	var bparsedStr = trimString(strPhone);
	var parsedStr = getParsedPhoneStr(bparsedStr);
	if (parsedStr.length < 10) { return false; }
	if (parsedStr.length > 17) { return false; }
	if (/^[01]/.test(parsedStr)) { return false; }
	var npa = parsedStr.substring(0,3);
	if (!isValidPhoneNPA(npa)) {
		return false;
	}
	var nxx = parsedStr.substring(3,6);
	if (!isValidPhoneNXX(nxx)) {
		return false;
	}
	
	return true;
}

function isValidPhoneNPA(strNPA) {
	if (strNPA.length < 3) { return false; }
	if (/[^0-9]/.test(strNPA)) { return false; }
	if (/^[01]/.test(strNPA)) { return false; }
	if ("200,222,300,333,400,444,500,555,600,666,700,777,900,999".indexOf(strNPA) != -1) { return false; }
	return true;
}

function isValidPhoneNXX(strNXX) {
	if (strNXX.length < 3) { return false; }
	if (/[^0-9]/.test(strNXX)) { return false; }
	if (/^[01]/.test(strNXX)) { return false; }
	return true;
}

function isValidEmail(strEmail) {
	var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

	if (strEmail.length < 5) { return false; }

	if (!strEmail.match(re)) { return false; }
	
	return true;
}

/* ####### GENERIC FORM VALIDATORS ####### */

function validateInput(hInput, minLength, inputDescription) {
	if (hInput.value.length == 0) {
		return validationAlert("Please enter " + inputDescription + ".", hInput);
	} else if (hInput.value.length < minLength) {
		return validationAlert("Please re-enter " + inputDescription + ".\n(The information you entered is incomplete.)", hInput);
	}
	return true;
}

function validateSelectbox(hSelectbox, strAlert) {
	if (hSelectbox.value.length == 0) {
		return validationAlert(strAlert, hSelectbox);
	}
	return true;
}

function validateComparison(hInput, strCompare, inputDescription, extraDescription) {
	if (hInput.value != strCompare) {
		return validationAlert("Please re-enter " + inputDescription + " " + extraDescription + ".", hInput);
	}
	return true;
}

function validateNumbersOnly(hInput, strAlert) {
	if (/[^0-9]/.test(hInput.value)) {
		return validationAlert(strAlert, hInput);
	}
	return true;
}

function validateIntegerInput(hInput, minLength, inputDescription) {
	if (!validateInput(hInput, minLength, inputDescription)) { return false; }
	if (!validateNumbersOnly(hInput, inputDescription)) { return false; }
	return true;
}


/* ####### FORM VALIDATION STRING CONSTANTS ####### */

var ErrorMsg = new Object();
	ErrorMsg.VAR1 = "%VAR1%";
	ErrorMsg.EMPTY_FIRSTNAME = "Please enter your First Name.";
	ErrorMsg.INVALID_FIRSTNAME = "Your First Name may only contain letters, hyphens, or spaces. Please update your entry.";
	ErrorMsg.EMPTY_LASTNAME = "Please enter your Last Name.";
	ErrorMsg.INVALID_LASTNAME = "Your Last Name may only contain letters, hyphens, or spaces. Please update your entry.";
	ErrorMsg.EMPTY_ADDRESS = "Please enter your Address.";
	ErrorMsg.INVALID_ADDRESS = "Your Address must contain letters and numbers. Please update your entry.";
	ErrorMsg.EMPTY_CITY = "Please enter your City.";
	ErrorMsg.INVALID_CITY = "Your City may only contain letters, hyphens, or spaces. Please update your entry.";
	ErrorMsg.UNSELECTED_STATE = "Please select your State.";
	ErrorMsg.EMPTY_ZIPCODE = "Please enter your Zip Code.";
	ErrorMsg.INVALID_ZIPCODE = "Your Zip Code must be at least five numbers. Please update your entry.";
	ErrorMsg.INVALID2_ZIPCODE = "Your Zip Code may only contain numbers. Please update your entry.";
	ErrorMsg.EMPTY_PRI_PHONE = "Please enter your Primary Phone Number";
	ErrorMsg.INVALID_PRI_PHONE = "Please enter your valid Primary Phone Number";
	ErrorMsg.INVALID_SEC_PHONE = "Please enter your valid Secondary Phone Number";
	ErrorMsg.EMPTY_PHONE_NPA = "Please enter your " + ErrorMsg.VAR1 + " Phone Number Area Code";
	ErrorMsg.INVALID_PHONE_NPA = "Your " + ErrorMsg.VAR1 + " Phone Number Area Code must be a valid three-digit area code. Please update your entry.";
	ErrorMsg.EMPTY_PHONE_NXX = "Please enter the first three digits of your " + ErrorMsg.VAR1 + " Phone Number.";
	ErrorMsg.INVALID_PHONE_NXX = "Your " + ErrorMsg.VAR1 + " Phone Number must begin with three numbers. Please update your entry.";
	ErrorMsg.INVALID2_PHONE_NXX = "Your " + ErrorMsg.VAR1 + " Phone Number may not begin with a \"1\" or a \"0\". Please update your entry.";
	ErrorMsg.EMPTY_PHONE_STATION = "Please enter the last four digits of your " + ErrorMsg.VAR1 + " Phone Number.";
	ErrorMsg.INVALID_PHONE_STATION = "Your " + ErrorMsg.VAR1 + " Phone Number must end with four numbers. Please update your entry.";
	ErrorMsg.EMPTY_EMAIL = "Please enter your Email Address.";
	ErrorMsg.INVALID_EMAIL = "You must enter a valid Email Address. Please update your entry.";
	ErrorMsg.EMPTY_STREET_NUMBER = "Please enter your Street Number.";
	ErrorMsg.EMPTY_STREET_NAME = "Please enter your Street Name.";
    ErrorMsg.UNSELECTED_BEST_CALL_TIME = "Please select Best Time to Call.";
    ErrorMsg.EMPTY_PREMATCH_NPA = "Please enter the area code where you currently live.";
    ErrorMsg.INVALID_PREMATCH_NPA = "Please enter the area code where you currently live. No 800 or 888 numbers please.";
    ErrorMsg.RESTRICTED_PREMATCH_NPA = "Please enter the area code where you currently live. No 800 or 888 numbers please.";

/* ####### SPECIFIC-USE FORM VALIDATORS ####### */

function validateFirstNameInput(hInput) {
	if (hInput.value.length == 0) { return validationAlert(ErrorMsg.EMPTY_FIRSTNAME, hInput); }
	if (!isValidFirstName(hInput.value)) { return validationAlert(ErrorMsg.INVALID_FIRSTNAME, hInput); }
	return true;
}

function validateLastNameInput(hInput) {
	if (hInput.value.length == 0) { return validationAlert(ErrorMsg.EMPTY_LASTNAME, hInput); }
	if (!isValidLastName(hInput.value)) { return validationAlert(ErrorMsg.INVALID_LASTNAME, hInput); }
	return true;
}

function validateStreetAddressInput(hInput) {
	if (hInput.value.length == 0) { return validationAlert(ErrorMsg.EMPTY_ADDRESS, hInput); }
	if (!isValidStreetAddress(hInput.value)) { return validationAlert(ErrorMsg.INVALID_ADDRESS, hInput); }
	return true;
}

function validateStreetNumberInput(hInput) {
	if (hInput.value.length == 0) { return validationAlert(ErrorMsg.EMPTY_STREET_NUMBER, hInput); }
	return true;
}

function validateStreetNameInput(hInput) {
	if (hInput.value.length == 0) { return validationAlert(ErrorMsg.EMPTY_STREET_NAME, hInput); }
	return true;
}

function validateCityInput(hInput) {
	if (hInput.value.length == 0) { return validationAlert(ErrorMsg.EMPTY_CITY, hInput); }
	if (!isValidCity(hInput.value)) { return validationAlert(ErrorMsg.INVALID_CITY, hInput); }
	return true;
}

function validateZipCodeInput(hInput) {
	if (hInput.value.length == 0) { return validationAlert(ErrorMsg.EMPTY_ZIPCODE, hInput); }
	if (hInput.value.length < 5) { return validationAlert(ErrorMsg.INVALID_ZIPCODE, hInput); }
	if (/[^0-9]/.test(hInput.value)) { return validationAlert(ErrorMsg.INVALID2_ZIPCODE, hInput); }
	return true;
}

function validatePropZipCodeInput(hInput) {
	if (hInput.value.length == 0) { return true; }
	if (hInput.value.length < 5) { return validationAlert(ErrorMsg.INVALID_ZIPCODE, hInput); }
	if (/[^0-9]/.test(hInput.value)) { return validationAlert(ErrorMsg.INVALID2_ZIPCODE, hInput); }
	return true;
}

function validatePrematchNPAInput(hInput) {
	if (hInput.value.length == 0) { return validationAlert(ErrorMsg.EMPTY_PREMATCH_NPA, hInput); }
	if (hInput.value.length < 3) { return validationAlert(ErrorMsg.INVALID_PREMATCH_NPA, hInput); }
	if (!isValidPhoneNPA(hInput.value)) { return validationAlert(ErrorMsg.INVALID_PREMATCH_NPA, hInput); }
	if ((hInput.value == "800") || (hInput.value == "888")) { return validationAlert(ErrorMsg.RESTRICTED_PREMATCH_NPA, hInput); }
	return true;
}

function validatePhoneNPAInput(hInput, strPhoneType) {
	if (hInput.value.length == 0) { return validationAlert(ErrorMsg.EMPTY_PHONE_NPA.replace(ErrorMsg.VAR1, strPhoneType), hInput); }
	if (hInput.value.length < 3) { return validationAlert(ErrorMsg.INVALID_PHONE_NPA.replace(ErrorMsg.VAR1, strPhoneType), hInput); }
	if (!isValidPhoneNPA(hInput.value)) { return validationAlert(ErrorMsg.INVALID_PHONE_NPA.replace(ErrorMsg.VAR1, strPhoneType), hInput); }
	return true;
}

function validatePhoneNXXInput(hInput, strPhoneType) {
	if (hInput.value.length == 0) { return validationAlert(ErrorMsg.EMPTY_PHONE_NXX.replace(ErrorMsg.VAR1, strPhoneType), hInput); }
	if (hInput.value.length < 3) { return validationAlert(ErrorMsg.INVALID_PHONE_NXX.replace(ErrorMsg.VAR1, strPhoneType), hInput); }
	if (/[^0-9]/.test(hInput.value)) { return validationAlert(ErrorMsg.INVALID_PHONE_NXX.replace(ErrorMsg.VAR1, strPhoneType), hInput); }
	if (/^[01]/.test(hInput.value)) { return validationAlert(ErrorMsg.INVALID2_PHONE_NXX.replace(ErrorMsg.VAR1, strPhoneType), hInput); }
	return true;
}

function validatePhoneStationInput(hInput, strPhoneType) {
	if (hInput.value.length == 0) { return validationAlert(ErrorMsg.EMPTY_PHONE_STATION.replace(ErrorMsg.VAR1, strPhoneType), hInput); }
	if (hInput.value.length < 4) { return validationAlert(ErrorMsg.INVALID_PHONE_STATION.replace(ErrorMsg.VAR1, strPhoneType), hInput); }
	if (/[^0-9]/.test(hInput.value)) { return validationAlert(ErrorMsg.INVALID_PHONE_STATION.replace(ErrorMsg.VAR1, strPhoneType), hInput); }
	return true;
}

function validateEmailInput(hInput) {
	hInput.value = trimString(hInput.value);
	if (hInput.value.length == 0) { return validationAlert(ErrorMsg.EMPTY_EMAIL, hInput); }
	if (!isValidEmail(hInput.value)) { return validationAlert(ErrorMsg.INVALID_EMAIL, hInput); }
	return true;
}

function validatePrimaryPhoneInput(hInput) {
	if (hInput.value.length == 0) { return validationAlert(ErrorMsg.EMPTY_PRI_PHONE, hInput); }
	if (!isValidEntirePhone(hInput.value)) { return validationAlert(ErrorMsg.INVALID_PRI_PHONE, hInput); }
	return true;
}

function validateSecondaryPhoneInput(hInput) {
	if (hInput.value.length == 0) { return true; }
	if (!isValidEntirePhone(hInput.value)) { return validationAlert(ErrorMsg.INVALID_SEC_PHONE, hInput); }
	return true;
}
	

/* ####### DYNAMIC FORM FIELD FUNCTIONS ####### */


function initOtherField(hHidden, hSelectbox, hTextbox, strOtherFormBlock) {
	// Initialize an "other value" selectbox/textbox combo (on page load).
	hSelectbox.value = hHidden.value;
	if (hSelectbox.value == hHidden.value) {
		hTextbox.value = "";
	} else {
		hSelectbox.value = "other";
		hTextbox.value = hHidden.value;
	}
	toggleOtherField(hSelectbox, strOtherFormBlock);
}

function toggleOtherField(hSelectbox, strOtherFormBlock) {
	// Shows another form block if an option with value "other" is selected in a SELECT form element.
	if (hSelectbox.value == "other") {
		showElement(strOtherFormBlock);
	} else {
		hideElement(strOtherFormBlock);
	}
}

function focusOtherField(hSelectbox, hTextbox) {
	// Focuses the appropriate field in a selectbox/textbox combo (for "other value" form validation).
	if (hSelectbox.value != "other") {
		hSelectbox.focus();
	} else {
		hTextbox.focus();
	}
}

function focusFirstEmptyField(form) {
	var hField;
	for (var i=0; i < form.elements.length; i++) {
		hField = form.elements[i];
		try {
			if (isNotHiddenFormField(form, hField.name) && (getFormFieldValue(hField) == "")) {
				hField.focus();
				return;
			}
		} catch(ex) {}
	}
}

function toggleElementBasedOnField(element, field, listOfValues) {
	// Toggles the visibility of the specified element, checking the value of the specified field against
	// the list of specified values.  If any values in the list match the field value, the field is made
	// visible--otherwise, the field is hidden
	var fieldValue = getFormFieldValue(field);
	var show = false;
	for (var i=0;i<listOfValues.length;i++) {
		if (listOfValues[i] == fieldValue) {
			show = true;
			break;
		}
	}
	
	if (show) {
		showElement(element);
	}
	else {
		hideElement(element);
	}
}

function setFieldNumbers(nextNum) {
	if (arguments.length < 2) { return nextNum; }
	var element;
	for (var i=1; i < arguments.length; i++) {
		element = document.getElementById(arguments[i]);
		if (!element) { continue; }
		try {
			element.innerHTML = nextNum;
			nextNum++;
		} catch(ex) {}
	}
	return nextNum;
}


function validateForm(form) {

	// remove elements from the dhtml when using dynamic display to avoid 
	// multiple values of the same element name
	if (form.PRODUCT != null) {
		typeEle = form.PRODUCT;
		if (typeEle.type == "select-one") {
			loanType = typeEle.options[typeEle.selectedIndex].value;
			if (loanType == 'PP_NEWHOME') {
				// remove all field from the GEN_MORT table
				var tableElem = document.getElementById("tblOthers");
				if (tableElem != null) {
					tableElem.parentNode.removeChild(tableElem);
				}
			} else {
				// remove all fields from the NEWHOME table
				var tableElem = document.getElementById("tblPurchase");
				if (tableElem != null) {
					tableElem.parentNode.removeChild(tableElem);
				}
			}
		}
	}		
	
	var productElement = form.PRODUCT;
	
	if (productElement != null && ((productElement.type == "select-one" && productElement.options[productElement.selectedIndex].value == "PP_HOME_EQUITY") || (productElement.type == "hidden" && productElement.value == "PP_HOME_EQUITY"))) {
		// make sure BAL_TWO and ADD_CASH is at least 15k
		var balTwo = form.BAL_TWO;
		var addCash = form.ADD_CASH;
		
		// only check when both parameters are present
		if (balTwo != null && addCash != null) {
			
			// only check when both parameters are not hidden
			if (balTwo.type != "hidden" && addCash.type != "hidden") {
				
				if (getInteger(getFormFieldValue(balTwo)) + getInteger(getFormFieldValue(addCash)) < 15000) {
					validationAlert("Minimum Home Equity line is $15,000", balTwo);
					return false;
				}				
			}
		}
	}
	
	var fieldName;
	/* validate only the fields defined in the form */
	for (var i=0; i < form.elements.length; i++) {
		
		fieldName = form.elements[i].name.toUpperCase();

		if (fieldName == "EST_VAL") {
			if (form.elements[i].type != "hidden") {
				if (!validateSelectbox(form.elements[i], "Please select the Estimated Property Value.")) {
        			return false;
				}
			}
		} else if (fieldName == "EST_VAL2") {
			if (form.elements[i].type != "hidden") {
				if (!validateSelectbox(form.elements[i], "Please select the Estimated Property Value.")) {
        			return false;
				}
			}
		} else if (fieldName == "PROP_ZIP") {
			if (form.elements[i].type != "hidden") {
				if (!validatePropZipCodeInput(form.elements[i])) {
        			return false;
				}
			}
		} else if (fieldName == "FNAME") {
			if (form.elements[i].type != "hidden") {
				if (!validateFirstNameInput(form.elements[i])) {
					return false;
				}
			}
		} else if (fieldName == "LNAME") {
			if (form.elements[i].type != "hidden") {
				if (!validateLastNameInput(form.elements[i])) {
					return false;
				}
			}
		} else if (fieldName == "ZIP") {
			if (form.elements[i].type != "hidden") {
				if (!validateZipCodeInput(form.elements[i])) {
					return false;
				}
			}
		} else if (fieldName == "EMAIL") {
			if (form.elements[i].type != "hidden") {
				if (!validateEmailInput(form.elements[i])) {
					return false;
				}
			}
		} else if (fieldName == "ADDRESS") {
			if (form.elements[i].type != "hidden") {
				if (!validateStreetAddressInput(form.elements[i])) {
					return false;
				}
			}	
		} else if (fieldName == "CITY") {
			if (form.elements[i].type != "hidden") {
				if (!validateCityInput(form.elements[i])) {
					return false;
				}
			}
		} else if (fieldName == "STATE") {
			if (form.elements[i].type != "hidden") {
				if (!validateSelectbox(form.elements[i], "Please select the State.")) {
					return false;
				}
			}
		} else if (fieldName == "PROP_ST") {
			
			var productElement = form.PRODUCT;

			if (productElement != null && productElement.type == "select-one") {
				if (!validateSelectbox(form.elements[i], "Please select the Property State.")) {
					return false;
				}
			} 
		} else if (fieldName == "BAL_ONE") {

			var productElement = form.PRODUCT;
			
			if (productElement != null && ((productElement.type == "select-one" && productElement.options[productElement.selectedIndex].value != "PP_NEWHOME") || (productElement.type == "hidden" && productElement.value != "PP_NEWHOME"))) {
				if (form.elements[i].type != "hidden") {
					if (!validateSelectbox(form.elements[i], "Please select the Mortgage Balance.")) {
						return false;
					}
				}
			}
		} else if (fieldName == "MTG_ONE_INT") {
			
			var productElement = form.PRODUCT;
			
			if (productElement != null && ((productElement.type == "select-one" && productElement.options[productElement.selectedIndex].value != "PP_NEWHOME") || (productElement.type == "hidden" && productElement.value != "PP_NEWHOME"))) {
				if (form.elements[i].type != "hidden") {
					if (!validateSelectbox(form.elements[i], "Please select the Interest Rate.")) {
						return false;
					}
				}
			}
		} else if (fieldName == "CRED_GRADE") {
			if (!validateSelectbox(form.elements[i], "Please select the Credit Profile.")) {
				return false;
			}
		} else if (fieldName == "LOAN_TYPE") {
			if (form.elements[i].type != "hidden") {
				if (!validateSelectbox(form.elements[i], "Please select the Rate Type.")) {
					return false;
				}
			}
		} else if (fieldName == "PROP_DESC") {
			if (form.elements[i].type != "hidden") {
				if (!validateSelectbox(form.elements[i], "Please select the Property Description.")) {
					return false;
				}
			}
		} else if (fieldName == "PREF_CALLTIME") {
			if (form.elements[i].type != "hidden") {
				if (!validateSelectbox(form.elements[i], "Please select the Best Contact Time.")) {
					return false;
				}
			}	
		} else if (fieldName == "PROP_PURP") {
			if (form.elements[i].type != "hidden") {
				if (!validateSelectbox(form.elements[i], "Please select the Purpose of Property.")) {
					return false;
				}
			}
		} else if (fieldName == "PRI_PHON") {
			if (form.elements[i].type != "hidden") {
				if (!validatePrimaryPhoneInput(form.elements[i])) {
					return false;
				}
			}
		} else if (fieldName == "SEC_PHON") {
			if (form.elements[i].type != "hidden") {
				if (!validateSecondaryPhoneInput(form.elements[i])) {
					return false;
				}
			}
		} else if (fieldName == "DOWN_PMT_PERCENT") {
		
			var productElement = form.PRODUCT;
			
			if (productElement != null && ((productElement.type == "select-one" && productElement.options[productElement.selectedIndex].value == "PP_NEWHOME") || (productElement.type == "hidden" && productElement.value == "PP_NEWHOME"))) {
				if (form.elements[i].type != "hidden") {
					if (!validateSelectbox(form.elements[i], "Please select Your Down Payment amount.")) {
						return false;
					}
				}	
			}
		}/* else if (fieldName == "ADD_CASH") {
			
			var productElement = form.PRODUCT;
			
			if (productElement != null && ((productElement.type == "select-one" && productElement.options[productElement.selectedIndex].value == "PP_HOME_EQUITY") || (productElement.type == "hidden" && productElement.value == "PP_HOME_EQUITY"))) {
				if (form.elements[i].type != "hidden") {
					if (!validateSelectbox(form.elements[i], "Please select how much You want to Borrow.")) {
						return false;
					}
				}
			}
		}*/
	}
	
	return true;
}


function balTwoEmptyCheck(b) {
	if (b.options.length < 2) {
   		addOption("You cannot borrow more than", "xx", b);
   		addOption("your Estimated Home Value", "xx", b);
   	} else if (b.options.length > 2) {
   		if (b.options[1].value == 'xx' && b.options[2].value == 'xx') {
   			b.remove(1);b.remove(1);
   		}
   	}
}

