/* Show/hide method */

function showLoan(select) {

 var others = MM_findObj("tblOthers");
 var newhome = MM_findObj("tblPurchase");
 
 // reload when product has changed after hitting submit
 if (others == null || newhome == null) {
    window.location.reload();
    select.value = "PP_REFI";
	return;
 }

 if (select.value == "PP_NEWHOME") {
   others.style.display="none";
   newhome.style.display="";
 }
 else {
   others.style.display="";
   newhome.style.display="none";
 }
}


function showLoanFields(select) {

 var existingloana = MM_findObj("pzipFields");
 var existingloanb = MM_findObj("pyearFields");
 var existingloanc = MM_findObj("purpFields");
 var existingloand = MM_findObj("balanceFields");
 var existingloane = MM_findObj("addcashFields");
 var existingloanf = MM_findObj("existingRate");
 var existingloang = MM_findObj("addcashRefi");
 var existingloanh = MM_findObj("addcashEquity");
 var existingloani = MM_findObj("addcashDebtcon");
 var existingloanj = MM_findObj("secmtgquestionFields");
 var existingloank = MM_findObj("secondMortgageFields");


 var newhomeloana = MM_findObj("pareaCodeFields");
 var newhomeloanb = MM_findObj("whenbuyFields");
 var newhomeloanc = MM_findObj("foundhomeFields");
 var newhomeloand = MM_findObj("dpmtFields");
 var newhomeloane = MM_findObj("ftbFields");
 var newhomeloanf = MM_findObj("desiredRate");
 var newhomeloang = MM_findObj("agentFields");

 // reload when product has changed after hitting submit
 if (existingloana == null || newhomeloana == null) {
  window.location.reload();
  select.value = "PP_REFI";
	return;
 }

 if (select.value == "PP_NEWHOME") {
   existingloana.style.display="none";
   existingloanb.style.display="none";
   existingloanc.style.display="none";
   existingloand.style.display="none";
   existingloane.style.display="none";
   existingloanf.style.display="none";
   existingloang.style.display="none";
   existingloanh.style.display="none";
   existingloani.style.display="none";
   existingloanj.style.display="none";
   existingloank.style.display="none";   
   newhomeloana.style.display="";
   newhomeloanb.style.display="";
   newhomeloanc.style.display="";
   newhomeloand.style.display="";
   newhomeloane.style.display="";
   newhomeloanf.style.display="";
   newhomeloang.style.display="none";
}
 else if (select.value == "PP_DEBTCON") {
   existingloana.style.display="";
   existingloanb.style.display="";
   existingloanc.style.display="";
   existingloand.style.display="";
   existingloane.style.display="";
   existingloanf.style.display="";
   existingloang.style.display="none";
   existingloanh.style.display="none";
   existingloani.style.display="";
   existingloanj.style.display="";
   existingloank.style.display="";
   newhomeloana.style.display="none";
   newhomeloanb.style.display="none";
   newhomeloanc.style.display="none";
   newhomeloand.style.display="none";
   newhomeloane.style.display="none";
   newhomeloanf.style.display="none";
   newhomeloang.style.display="none";
}

 else if (select.value == "PP_REFI") {
   existingloana.style.display="";
   existingloanb.style.display="";
   existingloanc.style.display="";
   existingloand.style.display="";
   existingloane.style.display="";
   existingloanf.style.display="";
   existingloang.style.display="";
   existingloanh.style.display="none";
   existingloani.style.display="none";
   existingloanj.style.display="";
   existingloank.style.display="";
   newhomeloana.style.display="none";
   newhomeloanb.style.display="none";
   newhomeloanc.style.display="none";
   newhomeloand.style.display="none";
   newhomeloane.style.display="none";
   newhomeloanf.style.display="none";
   newhomeloang.style.display="none";   
}
 else if (select.value == "PP_HOME_EQUITY") {
   existingloana.style.display="";
   existingloanb.style.display="";
   existingloanc.style.display="";
   existingloand.style.display="";
   existingloane.style.display="";
   existingloanf.style.display="";
   existingloang.style.display="none";
   existingloanh.style.display="";
   existingloani.style.display="none";
   existingloanj.style.display="";
   existingloank.style.display="";
   newhomeloana.style.display="none";
   newhomeloanb.style.display="none";
   newhomeloanc.style.display="none";
   newhomeloand.style.display="none";
   newhomeloane.style.display="none";
   newhomeloanf.style.display="none";
   newhomeloang.style.display="none";
}
}

/*** functions for limiting values of dropdowns based on the value of another input ***/

/* Limit b's selections upto whatever a's selected value is. */
function limit(maxValue, b) {

 // the current max value in b's list.
 var bMax = getInteger(b.options[b.options.length-1].value);
 
 if (bMax > maxValue) {
  trim(b, maxValue);
 }
 else if (bMax < maxValue) {
  extend(b, bMax, maxValue);
 }
}

/* extends list from bMax to maxValue. */
function extend(b, bMax, maxValue) {
 
 var i = bMax;
 var upperlimit = false;
 while (i < maxValue) {
  
  var inc = 0;
 
  if (i < 197500) {
   inc = 5000;
   if  (!((inc+i) > maxValue)){
    i+=inc;   
   }else{
   	upperlimit = true;
   }
  }else if (i == 197500) {
   inc = 10000;
   i = 205000;
  }
  else if (i < 395000) {
   inc = 10000;
   if  (!((inc+i) > maxValue)){
    i+=inc;   
   }else{
    upperlimit= true;
   }
  }
  else if (i == 395000) {
   inc = 20000;
   i = 410000;
  }
  else if (i < 990000) {
   inc = 20000;
   if  (!((inc+i) > maxValue)){
    i+=inc;   
   }else{
    upperlimit= true;
   }
  }
  else {
   break;
  }
  if(upperlimit == true){
  	lower = upper+1;
	upper = maxValue+(inc/2);
  	addOption(toMoneyInt(lower) + ' - ' + toMoneyInt(upper), maxValue, b);  
  	break;
  }else{
  	lower = i-((inc/2)-1);
  	upper = i+(inc/2);
  	addOption(toMoneyInt(lower) + ' - ' + toMoneyInt(upper), i, b);  
  }
 }
 
}

function addOption(text,value,list) {
  var opt = document.createElement('option');
  opt.text = text;
  opt.value = value;
  
  try {
   list.add(opt, null); // standards compliant; doesn't work in IE
  }
  catch(ex) {
   list.add(opt); // IE only
  }
}

/* Trim a list down to maxValue. */
function trim(b, maxValue) {
 for(var i=0; i<b.options.length; i++) {
  if (getInteger(b.options[i].value) > maxValue) {
   cullPoint = i-1;
   break;
  }
 }

 for(var i=b.options.length; i>cullPoint; i--) {
  b.remove(i);
 }
 
}

/** Makes 10000 look like 10,000, etc. */
function toMoneyInt(num) {

 str = num + ""
 len = str.length
 s = ""
 
 for(var i=len,j=0; i>=0; i--,j++) {
  s = str.charAt(i) + s;
  
  if (j==3 && i > 0) {
   s = "," + s;
   j = 0;
  }
 }

 return s;
}


/* fixes home equity bal two and add cach to start at >=15k if est-one > 15k.  
 * est, one:  est val and bal one.
 * form:      the form to fix up.
 */
function fixHomeEquity(est, one, form) {
 if((est - one) >= 15000) {
  
  for(var i=0; i<form.BAL_TWO.options.length; i++) {
   if(form.BAL_TWO.options[i].value < 15000) {
    // alert(form.BAL_TWO.options[i].text);
    form.BAL_TWO.options[i] = null;
    // decrement counter to accomodate array re-shuffle.
    // we could iterate backwards too...
    i--;
   }
  }
  
  for(var i=0; i<form.ADD_CASH.options.length; i++) {
   if(form.ADD_CASH.options[i].value < 15000) {
    // alert(form.ADD_CASH.options[i].text);
    form.ADD_CASH.options[i] = null;
    i--;
   }
  }
 }
}


/**** util methods */

function getInteger(vNum) {
	vNum = getIntegerString(vNum.toString());
	if (vNum == "") { vNum = 0; }
	return Number(vNum);
}

function getIntegerString(strIn) {
	return strIn.replace(/[^0-9]/g, "");
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function trimString(strIn) {
	if (/^\s/.test(strIn)) { strIn = strIn.replace(/^\s{1,}/, ""); }
	if (/\s$/.test(strIn)) { strIn = strIn.replace(/\s{1,}$/, ""); }
	return strIn;
}

function getDecimalString(strIn) {
	strIn = strIn.replace(/[^0-9\.]/g, "");
	var iPoint = strIn.indexOf(".");
	if (iPoint > -1) {
		strIn = strIn.substring(0, iPoint + 1) + getIntegerString(strIn.substring((iPoint + 1), strIn.length));
	}
	return strIn;
}

function isValueInSelectbox(hSelectbox, strValue) {
	for (var i=0; i < hSelectbox.options.length; i++) {
		if (hSelectbox.options[i].value == strValue) {
			return true;
		}
	}
	return false;
}

function getParsedPhoneStr(strIn) {
	strIn = strIn.replace(/\.|-| |\(|\)/g,"");
	return strIn;
}


/*
 * DOM show/hide functions.
 * Do not set display to "block", it breaks things like table rows.
 */
function showElement(strID) {
	try { document.getElementById(strID).style.display = ""; } catch(ex) {}
}
function hideElement(strID) {
	try { document.getElementById(strID).style.display = "none"; } catch(ex) {}
}


function isNotHiddenFormField(form, strName) {
	// Tells you if a non-hidden field exists in a form.
	var type;
	var field = form.elements[strName];
	if (field && (typeof(field) == "object")) {
		try {
			type = field.getAttribute("type");
		} catch(ex) {
			// probably a radio button group (no attribute)
			return true;
		}
		if ((type) && (type.toLowerCase() == "hidden")) {
			return false;
		}
		return true;
	}
	return false;
}



function getRadioValue(hRadioGroup) {
	// Gets the selected value of a radio button group. If no radio button is selected, returns an empty string.
	for (var i=0; i < hRadioGroup.length; i++) {
		if (hRadioGroup[i].checked) { return hRadioGroup[i].value; }
	}
	return "";
}

function getMultipleSelectBoxValues(hSelect) {
	var i, option, arrSelected = new Array();
	while (hSelect.selectedIndex >= 0) {
		arrSelected[arrSelected.length] = hSelect.selectedIndex;
		hSelect.options[hSelect.selectedIndex].selected = false;
	}
	for (i=0; i < arrSelected.length; i++) {
		option = hSelect.options[arrSelected[i]];
		option.selected = true;
		arrSelected[i] = option.value;
	}
	return arrSelected;
}

function getFormFieldValue(hField) {
	if (!hField) { return undefined; }
	try {
		if (hField.type) {
			if (hField.type == "radio") {
				return getRadioValue(hField.form.elements[hField.name]);
			} else if (hField.type == "select-multiple") {
				return getMultipleSelectBoxValues(hField);
			} else {
				return hField.value;
			}
		}
	} catch (ex) {}
	try {
		if (hField.length && hField[0] && (hField[0].type == "radio")) {
			return getRadioValue(hField[0].form.elements[hField[0].name]);
		}
	} catch(ex) {}
	return undefined;
}

function addCommasToNumString(strIn) {
	var arrTemp = strIn.split("");
	var i = strIn.length - 4;
	var iPoint = strIn.indexOf(".");
	if (iPoint > -1) { i -= (strIn.length - iPoint); }
	for (i; i >= 0; i-=3) { arrTemp[i] += ","; }
	return arrTemp.join("");
}


function filterIntegerAddCommas(hField) {
	hField.value = addCommasToNumString(getIntegerString(hField.value));
}

function filterInteger(hField) {
   hField.value = getIntegerString(hField.value);
}


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 qs() {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
   var pos = parms[i].indexOf('=');
   if (pos > 0) {
      var key = parms[i].substring(0,pos);
      var val = parms[i].substring(pos+1);
      qsParm[key] = val;
      }
   }
}

function validateRadioButton(hRadioButton, strAlert){
	var selectedOption = -1;
	for(i=hRadioButton.length-1; i > -1; i--){
		if (hRadioButton[i].checked) {
			selectedOption= i;
		}
	}
	if(selectedOption == -1){
		return validationAlert(strAlert, hRadioButton[0]);
	}
	return true;
}

function validateCheckBox(hCheckBox, strAlert){
	if(!hCheckBox.checked){
		return validationAlert(strAlert, hCheckBox);
	}
	return true;
}

var downPaymentOptionLabelText = "{0}% down";

function updateDownPaymentSelectBox(hDownPaymentSelect, hHomeValueField) {
	var form = hDownPaymentSelect.form;
	var lastValue = getFormFieldValue(hDownPaymentSelect);
	var homeValue = getInteger(getFormFieldValue(hHomeValueField));
	var showDollarValue = (homeValue != 0) ? true : false;

	var opts = hDownPaymentSelect.options;
	var tmpLabel;
	var tmpDollarValue;
	for (var i=0; i < opts.length; i++) {
		if ((opts[i].value == "") || isNaN(opts[i].value)) { continue; }
		tmpLabel = downPaymentOptionLabelText.replace("{0}", opts[i].value);
		if (showDollarValue) {
			tmpDollarValue = new String(calculateDownPaymentValue(parseInt(opts[i].value), homeValue));
			tmpLabel = "$" + addCommasToNumString(tmpDollarValue) + " (" + tmpLabel + ")";
		}
		
		hDownPaymentSelect.options[i].text = tmpLabel;
	}

	var msieFix = "fixDownPaymentBoxForMSIE('" + form.name + "', '" + hDownPaymentSelect.name + "', '" + lastValue + "');";
	setTimeout(msieFix, 50);
	
	form.down_payment_other.value = homeValue;
	
}


function calculateDownPaymentValue(percent, price) {
	return Math.ceil(price * (percent / 100));
}


function fixDownPaymentBoxForMSIE(formName, fieldName, lastValue) {
	var select = document.forms[formName].elements[fieldName];
 	if (select.selectedIndex == -1) {
 	    if (isValueInSelectbox(select, lastValue)) {
 	        select.value = lastValue;
 	    } else {
 	        select.value = "";
 	    }
 	}
}

function doDownPaymentSelectBoxLogic(hSelectbox) {
	var form = hSelectbox.form;
	toggleOtherField(hSelectbox, "otherDownPaymentBlock");
	if (hSelectbox.value == "other") {
		form.down_payment_other.value = "";
		form.DOWN_PMT.value = "";
	} else {
		if (form.down_payment_other.value != 0) {
			form.DOWN_PMT.value = calculateDownPaymentValue(parseInt(hSelectbox.value), form.down_payment_other.value);
		} else {
			form.DOWN_PMT.value = calculateDownPaymentValue(parseInt(hSelectbox.value), form.EST_VAL.value);
	}
}
}

/* ###### 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;
}

function validateSSN1Input(hInput) {
	if (hInput.value.length != 3) { return validationAlert(ErrorMsg.INVALID_SSN, hInput); }
	if (/[^0-9]/.test(hInput.value)) { return validationAlert(ErrorMsg.INVALID_SSN, hInput); }
	return true;
}

function validateSSN2Input(hInput) {
	if (hInput.value.length != 2) { return validationAlert(ErrorMsg.INVALID_SSN, hInput); }
	if (/[^0-9]/.test(hInput.value)) { return validationAlert(ErrorMsg.INVALID_SSN, hInput); }
	return true;
}

function validateSSN3Input(hInput) {
	if (hInput.value.length != 4) { return validationAlert(ErrorMsg.INVALID_SSN, hInput); }
	if (/[^0-9]/.test(hInput.value)) { return validationAlert(ErrorMsg.INVALID_SSN, hInput); }
	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.";
    ErrorMsg.INVALID_SSN = "Please correct your Social Security Number.";
    

/* ####### 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 validationAlert('Please enter Property Zip Code', 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 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;
}
	
function validatePhoneInput(hInput,text) {
	if (hInput.value.length == 0) { return validationAlert('Please enter '+text+'.', hInput); }
	if (!isValidEntirePhone(hInput.value)) { return validationAlert('The '+text+' you entered seems to be erroneous.', 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(form.elements[i].value<80000){
					return validationAlert('Minimum Estimated Value must be at least $80,000.', form.elements[i]);
				}
			}
		} 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(form.elements[i].value<80000){
					return validationAlert('Minimum Estimated Value must be at least $80,000.', form.elements[i]);
				}
			}
		} 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(form.elements[i].value<10){
						return validationAlert("Please enter at least 10% down payment to receive new home purchase mortgage quotes", form.elements[i]);
						
					}
				}	
			}
		} 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;
}

/* EQF Page One Validation */
function validatePageOne(form)
{
	// We only have to check for a proper state to be set
	if (!validateSelectbox(form.PROP_ST, "Please select the Property State."))
	{
		return false;
	}
	return true;
}

/* EQF Page Two Validation */
function validatePageTwo(prod,form)
{
	/* Validate for a new mortgage */
	if(prod == "PP_NEWHOME")
	{
		if(!validatePhoneNPAInput(form.PROP_AREA, ""))
		{
			return false;
		}
		if(!validateSelectbox(form.BUY_TIMEFRAME, "Please select when you might be buying your house."))
		{
			return false;
		}
		/* Check Variable Fields */
		if(getRadioValue(form.SPEC_HOME) == "yes")
		{
			if(!getRadioValue(form.PURCHASE_CONTRACT))
			{
				alert('Please select if you have signed a home purchase contract.')
				return false;
			}
		}
		if(getRadioValue(form.AGENT_FOUND) == "yes")
		{
			if(!validateInput(form.AGENT_NAME,'5', 'your agent\'s name'))
			{
				return false;
			}
			if(!validatePhoneInput(form.AGENT_PHONE, 'agent\'s phone number'))
			{
				return false;
			}
			if(!validateInput(form.AGENT_COMPANY, '3', 'agent\'s Company'))
			{
				return false;
			}
		}
		return validateForm(form);
	}
	/* Validate for a refinance */
	else if(prod == "PP_REFI")
	{
		if (!validatePropZipCodeInput(form.PROP_ZIP)) {
			return false;
		}
		
		// Do validation
		var dovali;
		dovali = validateForm(form);
		
		if(!dovali)
		{
			return false;
		}
		
		// Validate Second Mortgage
		if(getRadioValue(form.MTG_TWO) == "YES")
		{
			if (!validateSelectbox(form.BAL_TWO, "Please select the current balance of your second mortgage.")) {
				return false;
			}
			if (!validateSelectbox(form.MTG_TWO_INT, "Please select the interest type of your second mortgage.")) {
				return false;
			}
		}
		if (!validateSelectbox(form.ADD_CASH, "Please select how much additional cash (if any) you would like.")) {
			return false;
		}
		
		return true;
	}
	alert('No product chosen.');
	return false;
}

/* EQF Page Three Validation */
function validatePageThree(form)
{
	if (!validateSelectbox(form.INCOME, "Please choose your annual income.")) {
		return false;
	}
	if (!validateSelectbox(form.OCC_STAT, "Please choose your occupational status.")) {
		return false;
	}
	if (!validateSelectbox(form.MIN_PAY, "Please indicate your monthly payments (excluding housing payments).")) {
		return false;
	}
	// Do validation
	return validateForm(form);
}

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 MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function KW_getVal(o){ //v1.2
	var retVal="0";if (o.type=="select-one")
	{retVal=(o.selectedIndex==-1)?0:o.options[o.selectedIndex].value;}
	else if (o.length>1){for (var i=0;i<o.length;i++) if (o[i].checked) retVal=o[i].value;
	} else if (o.type=="checkbox") {retVal=(o.checked)?o.value:0;} else {
	retVal=Number(o.value)}return parseFloat(retVal);
}

function KW_calcForm() { //v1.2
	var str="",a=KW_calcForm.arguments; for (var i=3;i<a.length;i++)
	str+=(a[i].indexOf("#")==-1)?a[i]:KW_getVal(MM_findObj(a[i].substring(1)));
	t=Math.round(a[1]*eval(str))/a[1];tS=t.toString();if(a[2]>0){tSp=tS.indexOf(".");
	if(tSp==-1)	tS+=".";tSp=tS.indexOf(".");while(tSp!=(tS.length-1-a[2])){tS+="0";
	tSp=tS.indexOf(".");}} MM_findObj(a[0]).value=tS;
}


function calcPayment() {
	try{
    	KW_calcForm('sum1',1,-1,'#cc_debt','+','#unsec_debt');
    	KW_calcForm('amount_1',1,-1,'#sum1','*','0.01');
    	KW_calcForm('amount_2',1,-1,'#sum1','*','0.019');
    	KW_calcForm('amount_3',1,-1,'#sum1','*','0.025');
	}catch(e){
	}
}

function calcPaymentUC() {
	try{
    	KW_calcForm('SUM1',1,-1,'#CC_DEBT','+','#UNSEC_DEBT');
    	KW_calcForm('AMOUNT_1',1,-1,'#SUM1','*','0.01');
    	KW_calcForm('AMOUNT_2',1,-1,'#SUM1','*','0.019');
    	KW_calcForm('AMOUNT_3',1,-1,'#SUM1','*','0.025');
	}catch(e){
	}
}

function onAffordChange(affordPayCtrl, child1, child2, parent1, parent2) {
	// There is nothing to do.
	if ( affordPayCtrl.value == null )
		return;

	var isYes = affordPayCtrl.value.toUpperCase() == "YES"; 
	
	if ( !isYes ){
		markSelectOption(child1, "no");
		markSelectOption(child2, "no");
	}

	if ( isYes ){
		markSelectOption(parent1, "yes" );
		markSelectOption(parent2, "yes" );
	}

}

function markSelectOption(sel, value) {
	if ( sel == null )
		return;
		
		sel.value = value 
}