
/* ###### 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; }
	//	I'm not sure how 17 digits would ever be valid

	/* For now, require 10 digits in phone number only. 
		The snippet below counts digits and returns false
		if there are not exactly 10 digits.  It ignores 
		non-numeric data, such as hyphens, etc.
		Some of this parsing may be redundant, but if so
		it's unclear to me why original allowed
		17 digit phone number.  
	*/
	var FmtStr="";
    var index = 0;
    var LimitCheck;

    LimitCheck = parsedStr.length;
    while (index != LimitCheck) {
		if (isNaN(parseInt(parsedStr.charAt(index))))
			{ }
        else
          {FmtStr = FmtStr + parsedStr.charAt(index); }
        index = index + 1;
      }
    if (FmtStr.length != 10) {return false;}

	/*	End snippet */
	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,911,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; }
	if ("555,911".indexOf(strNXX) != -1) { 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,}))$/

	var name = /^.@/
	
	if (strEmail.length < 5) { return false; }

	if (!strEmail.match(re)) { return false; }
	
	if (strEmail.match(name)) { 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 (10 digits)";
	ErrorMsg.INVALID_SEC_PHONE = "Please enter your valid secondary phone number (10 digits)";
	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 <= 2) { 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 <= 2) { 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);
				}
			}
		}
	}		

    
/*	if (form.AGENT_NO != null){
		if (productElement.options[productElement.selectedIndex].value == "PP_NEWHOME" && form.AGENT_NO.checked && !form.TOTALMOVE_YES.checked && !form.TOTALMOVE_NO.checked){
			validationAlert("Please let us know if you would like to be contacted by Total Move.");
			return false;
		}
	}
	
    
	var propCity = getFormFieldValue(form.PROP_CITY);
	if (getFormFieldValue(form.TOTALMOVE) == 1 && (propCity == null || propCity == "")){
		validationAlert("The Property City is required if you would like to be contacted by Total Move.  Please enter the Property City.", form.PROP_CITY);
		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 propStElement = form.PROP_ST;

			if (propStElement != null && propStElement.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;
					}
				}
			}
		}
	}
	 
	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("Your current requested loan amount is below $15,000.\n\nHelpful Tip:\nAll of the lenders in our network require a minimum loan amount of $15,000 for home equity lines of credit; please enter a loan amount of $15,000 or more.  If you need to borrow less than $15,000 you may want to consider a different type of loan or credit.", balTwo);
                    return false;
				}				
			}
		}
	}
    
	if (productElement != null && ((productElement.type == "select-one" && productElement.options[productElement.selectedIndex].value != "PP_NEWHOME") || (productElement.type == "hidden" && productElement.value != "PP_NEWHOME"))) {
		// make sure total loan value does not exceed 105% of value

        var loanVal = 0;
		var balOne = form.BAL_ONE;
		var balTwo = form.BAL_TWO;
		var addCash = form.ADD_CASH;
        
		if (balOne != null){
			loanVal = loanVal + getInteger(getFormFieldValue(balOne));
		}
		if (balTwo != null){
			loanVal = loanVal + getInteger(getFormFieldValue(balTwo));
		}
		if (addCash != null){
			loanVal = loanVal + getInteger(getFormFieldValue(addCash));
		}
		

        if (form.EST_VAL){
       	   var estVal = getInteger(getFormFieldValue(form.EST_VAL));
        
		   if (loanVal > estVal) {
			   validationAlert("Your current requested loan amount exceeds your property value.\n\nHelpful Tip:\nTo match you with lenders who can provide you with more favorable loan terms, your total loan amount (mortgage balances + additional cash) should not exceed the value of the property.  To bring the numbers in line, consider the following:\n\n1. Did you accurately estimate the property value?\n2. Do you need to take out as much cash as you originally indicated?", null);
               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);
   		}
   	}
}


function handleOnChange(id) {
    switch(id) {
        case "PRODUCT":
            relevantelement();
            break;
        case "EST_VAL":
            var selEST_VAL = document.getElementById("EST_VAL");
            actualDownPayment('DOWN_PMT_PERCENT','EST_VAL','DOWN_PMT');
            limit(getInteger(selEST_VAL.options[selEST_VAL.selectedIndex].value), document.getElementById("BAL_ONE"));
            limit(getInteger(selEST_VAL.options[selEST_VAL.selectedIndex].value) - getInteger(document.getElementById("BAL_ONE").options[document.getElementById("BAL_ONE").selectedIndex].value), document.getElementById("BAL_TWO"));
            limit((getInteger(selEST_VAL.options[selEST_VAL.selectedIndex].value)*1.05) - getInteger(document.getElementById("BAL_ONE").options[document.getElementById("BAL_ONE").selectedIndex].value) - getInteger(document.getElementById("BAL_TWO").options[document.getElementById("BAL_TWO").selectedIndex].value), document.getElementById("ADD_CASH"));
            //updateDownPaymentSelectBox(document.getElementById("DOWN_PMT_PERCENT"), selEST_VAL);
            break;
        case "BAL_TWO":
            limit((getInteger(document.getElementById("EST_VAL").options[document.getElementById("EST_VAL").selectedIndex].value)*1.05) - getInteger(document.getElementById("BAL_ONE").options[document.getElementById("BAL_ONE").selectedIndex].value) - getInteger(document.getElementById("BAL_TWO").options[document.getElementById("BAL_TWO").selectedIndex].value), document.getElementById("ADD_CASH"));
            break;
        case "DOWN_PMT_PERCENT":
            actualDownPayment('DOWN_PMT_PERCENT','EST_VAL','DOWN_PMT');
            break;
        case "SPEC_YES":
            showElement('contract');
            break;
        case "SPEC_NO":
            hideElement('contract');
            break;
        case "AGENT_YES":
            showElement('agentname'); showElement('agentphone');
        /*    hideElement('totalmove');
            hideElement('prop_city');*/
            break;
        case "AGENT_NO":
            hideElement('agentname'); hideElement('agentphone');
            /*var what = fetch("PRODUCT");  //grab the select menu
            if (what.value == "PP_NEWHOME"){
                showElement('totalmove');
                var tmwhat = fetch("TOTALMOVE_YES");
                if (tmwhat.checked){
                    showElement('prop_city');
                }
            } else {
                hideElement('totalmove');
                hideElement('prop_city');
            }*/
            break;
        /*case "TOTALMOVE_YES":
            var what = fetch("PRODUCT");  //grab the select menu
            if (what.value == "PP_NEWHOME"){
                showElement('prop_city');
            } else {
                hideElement('prop_city');
            }
            break;
        case "TOTALMOVE_NO":
            hideElement('prop_city');
            break;*/
        case "MTG_TWO_YES":
            showElement('secondbalance'); showElement('monthlypaymenttwo');
            break;
        case "MTG_TWO_NO":
            hideElement('secondbalance'); hideElement('monthlypaymenttwo');
            break;
        case "DOWN_PMT_OTHER":
            filterIntegerAddCommas(document.getElementById("DOWN_PMT_OTHER"));
            document.getElementById("DOWN_PMT").value = getInteger(document.getElementById("DOWN_PMT_OTHER").value);
            break;
        default:
            break;
    }
}
//function MM_openBrWindow(theURL,winName,features)
//{
//    window.open(theURL,winName,features);
//}

function loadPage() {
    hideForm();
    relevantelement();
    loadCookie(); 
    showForm();
	Tooltip.init();
}

function hideForm() { 
    document.getElementById('preloadFormDiv').style.display = 'none';
}

function showForm() { 
    document.getElementById('preloadFormDiv').style.display = 'inline';
}


function show(el) {
    //var el = document.getElementById(id);
    if(!el) return;
    el.style.display = "";
}
function crawlback(id) {
    var el = fetch(id);
    if(!el) return;
    if (el.type == 'hidden') //don't read tags set up to pass info 
       {return;}
    else {    
        while(el.parentNode.nodeName !="TR") 
            {el = el.parentNode;}      
        return el.parentNode;  
    }  
    
    
}

function hidetr() {
    var trs = document.getElementsByTagName("tr");
    var re = /[refinance|equity|purchase]/;
    for(i=0; i<trs.length; i++) {
        if (trs[i].className.match(re)) {
            trs[i].style.display = "none";        
        }
    }
}

function resetestval() {   

            //remove the EST_VAL from the DOM
//            var ev = crawlback("EST_VAL");
//            var n = ev.parentNode.removeChild(ev);
//            put EST_VAL back into Your property info
//            var dest = crawlback("PROP_PURP");
//            dest.parentNode.appendChild(n);
    }

function relevantelement() { //this does all the work  
    var what = fetch("PRODUCT");  //grab the select menu
     //since refi and consolidate are the same logically, keep the switch simple.
    var test = (what.value == "PP_DEBTCON") ?  "PP_REFI" : what.value;
    switch(test) {    //create a new array of ids to show based upon the select's value
        case "PP_REFI":
            //put EST_VAL in its default location    
            resetestval();
            hidetr();
            var showwhat = new Array(); 
            if (document.getElementById("PRODUCT")){showwhat.push("PRODUCT");}
            if (document.getElementById("PROP_ST")){showwhat.push("PROP_ST");}
            if (document.getElementById("PROP_ZIP")){showwhat.push("PROP_ZIP");} 
            if (document.getElementById("PROP_DESC")){showwhat.push("PROP_DESC");}
            if (document.getElementById("PROP_PURP")){showwhat.push("PROP_PURP");} 
            if (document.getElementById("EST_VAL")){showwhat.push("EST_VAL");} 
            if (document.getElementById("BAL_ONE")){showwhat.push("BAL_ONE");}
            if (document.getElementById("MONTH_PMT")){showwhat.push("MONTH_PMT");}
            if (document.getElementById("MTG_ONE_INT")){showwhat.push("MTG_ONE_INT");} 
            if (document.getElementById("MTG_TWO_YES")){ 
                showwhat.push("MTG_TWO_YES");
                if(document.loanform.MTG_TWO_YES.checked) {
                   showwhat.push("BAL_TWO","MTG_TWO_INT"); //add real estate agent info if user has agent
                }
            } 
            if (document.getElementById("WHICH_REFI")){showwhat.push("WHICH_REFI");}
            if (document.getElementById("ADD_CASH")){showwhat.push("ADD_CASH");} 
            if (document.getElementById("FIXED_RATE")){showwhat.push("FIXED_RATE");}
            if (document.getElementById("ADJ_RATE")){showwhat.push("ADJ_RATE");}
            if (document.getElementById("DONT_KNOW")){showwhat.push("DONT_KNOW");}
            if (document.getElementById("LOAN_TERM")){showwhat.push("LOAN_TERM");}  
            
            break;
        case "PP_NEWHOME":  
            hidetr();
            var showwhat = new Array();
            if (document.getElementById("PRODUCT")){showwhat.push("PRODUCT");}
            if (document.getElementById("PROP_ST")){showwhat.push("PROP_ST");} 
            if (document.getElementById("PROP_AREA")){showwhat.push("PROP_AREA");}
            if (document.getElementById("PROP_ZIP")){showwhat.push("PROP_ZIP");}  
            if (document.getElementById("PROP_DESC")){showwhat.push("PROP_DESC");}
            if (document.getElementById("FB_YES")){showwhat.push("FB_YES");} 
            if (document.getElementById("SPEC_YES")){
                showwhat.push("SPEC_YES");
                if(document.loanform.SPEC_YES.checked) {
                    showwhat.push("RP_YES"); //add the contract question if user has found a home
                }
            }
            if (document.getElementById("AGENT_NO")){showwhat.push("AGENT_NO");}  
            if (document.getElementById("AGENT_YES")){
                showwhat.push("AGENT_YES");
                if(document.loanform.AGENT_YES.checked) {
                   showwhat.push("AGENT_NAME","AGENT_PHONE"); //add real estate agent info if user has agent
                }
               /* else{
                   showwhat.push("TOTALMOVE_YES", "TOTALMOVE_NO");    
                }*/
            }
           /* if (document.getElementById("TOTALMOVE_YES")){
                if(document.loanform.TOTALMOVE_YES.checked) {
                    showwhat.push("PROP_CITY"); //add city request
                }  
            }    */
            if (document.getElementById("EST_VAL")){showwhat.push("EST_VAL");}  
            if (document.getElementById("DOWN_PMT_PERCENT")){showwhat.push("DOWN_PMT_PERCENT");}
            if (document.getElementById("FIXED_RATE")){showwhat.push("FIXED_RATE");} 
            if (document.getElementById("ADJ_RATE")){showwhat.push("ADJ_RATE");}
            if (document.getElementById("DONT_KNOW")){showwhat.push("DONT_KNOW");}
            if (document.getElementById("LOAN_TERM")){showwhat.push("LOAN_TERM");}

            //remove the EST_VAL from the DOM
//            var ev = crawlback("EST_VAL");
//            var jpnode = ev.parentNode.removeChild(ev);
//            put EST_VAL above Down payment type
//            var dest = crawlback("DOWN_PMT");
//            dest.parentNode.insertBefore(jpnode,dest);
            
            break;

        case "PP_DEBTCON":
            //this is identical to Refinance -- var redefined above
            break;
    
        case "PP_HOME_EQUITY": 
            hidetr();
            resetestval();
            var showwhat = new Array();
            if (document.getElementById("PRODUCT")){showwhat.push("PRODUCT");}
            if (document.getElementById("PROP_ST")){showwhat.push("PROP_ST");} 
            if (document.getElementById("PROP_ZIP")){showwhat.push("PROP_ZIP");} 
            if (document.getElementById("PROP_DESC")){showwhat.push("PROP_DESC");} 
            if (document.getElementById("PROP_PURP")){showwhat.push("PROP_PURP");}  
            if (document.getElementById("EST_VAL")){showwhat.push("EST_VAL");} 
            if (document.getElementById("BAL_ONE")){showwhat.push("BAL_ONE");} 
            if (document.getElementById("MONTH_PMT")){showwhat.push("MONTH_PMT");} 
            if (document.getElementById("MTG_ONE_INT")){showwhat.push("MTG_ONE_INT");} 
            if (document.getElementById("MTG_TWO_YES")){
                showwhat.push("MTG_TWO_YES");
                if(document.loanform.MTG_TWO_YES.checked) {
                   showwhat.push("BAL_TWO","MTG_TWO_INT"); //add real estate agent info if user has agent
                }
            } 
            if (document.getElementById("LOAN_PREF")){showwhat.push("LOAN_PREF");} 
            if (document.getElementById("ADD_CASH")){showwhat.push("ADD_CASH");}
            if (document.getElementById("EQUITY_SIZE")){showwhat.push("EQUITY_SIZE");}
            if (document.getElementById("FIXED_RATE")){showwhat.push("FIXED_RATE");} 
            if (document.getElementById("ADJ_RATE")){showwhat.push("ADJ_RATE");}
            if (document.getElementById("DONT_KNOW")){showwhat.push("DONT_KNOW");}
            if (document.getElementById("LOAN_TERM")){showwhat.push("LOAN_TERM");}
            break;
    }

    
    if(showwhat) {
        for(i=0; i<showwhat.length; i++) {
            if (crawlback(showwhat[i])){
               var x = crawlback(showwhat[i]);
               show(x);
            }
        }
    } //end if(showwhat)
} //end relevantelement

function fetch(id) { //this is just a short cut for writing out doc.getElbyId...
    return document.getElementById(id);
    }

var madeSuggestion = false;

function makeSuggestions() {
    madeSuggestion = true; // turn off the suggestions
    if(madeSuggestion == false) {
        //if statements for suggestions
        
// comment out the downpayment textfield and work straight from the combobox
//        var downpaymentInteger = getInteger(fetch("DOWN_PMT").value); //remove commas that are auto-added
//        var estValue = fetch("EST_VAL").value;
        
//        if (fetch("PRODUCT").value=="PP_NEWHOME" && (downpaymentInteger/estValue) < 0.2) {

        if (fetch("PRODUCT").value=="PP_NEWHOME" && (fetch("DOWN_PMT_PERCENT").value) < 20) {
            var userfeedback = displaySuggestion("We can find you more loans if you increase your down payment above 20%\n\nWould you like to change your Down Payment amount?");
            if(userfeedback) {
                var el = fetch("DOWN_PMT_PERCENT");
                el.focus();
                el.className = "suggestion";
                el.onchange = function() { this.className = ""; };
                madeSuggestion = true; //prevent the script from making more suggestions
                return true;
                }
        }
        // end possible suggestions.
        
    } // end if (madeSuggestion)
} //end makeSuggestions

function displaySuggestion(suggestion) {
    return confirm(suggestion);
} // end displaySuggestion

function disableSubmit(x) {
 
    fetch("btnMatchMe").disabled = true;
    fetch("btnMatchMe").src = "/images/btnProcessing.gif"; //provide visual cue about button being disabled

     var madeSuggestion = makeSuggestions(); //since we're firing on submit, might as well take this time to make suggestions

    window.setTimeout("enableSubmit()",1000); //1000 milliseconds = 1 seconds

    if(!madeSuggestion) { //if there are no suggestions to make, then move on to validation 
        var isValid = validateForm(x);
        if(isValid) { clearCookie(); }
        return isValid;
    } else { //user followed suggestion
        return false;
    }
    
} // end disableSubmit

function enableSubmit() {
    fetch("btnMatchMe").disabled = false; //re-enable the submit button
    fetch("btnMatchMe").src = "/images/btnGetQuotesNow.gif"; //replace original graphic
} // end enableSubmit

function actualDownPayment(pctID, valID, id) {
    //arguments are the  id of the percentage, the estimated value of the home, and the id of the element to update
    
    //make sure both fields are numbers
    if(fetch(valID).value * 1 != fetch(valID).value || fetch(pctID).value*1 != fetch(pctID).value) return;

    //show the dynamic amount calculator if calculations can happen
    //if(fetch(valID).value > 0 && fetch(pctID).value > 0) fetch("calc").style.display = "inline";

    var val = (fetch(valID).value) * (fetch(pctID).value)/100;
    fetch(id).value = val.toString();
}

function showTotalMovePopUp(junk)
{
    var newWindow = window.open("http://www.lowlender.com/totalmove.php","myWin","toolbar=no,menubar=no,directories=no,location=no,status=no,scrollbars=no,resizable=no,width=450,height=350");
}


window.onload = loadPage;

