/** Mouse position handlers for mouseover boxes **/document.onmousemove = mouseMove;var mousePos;var is_ie/*@cc_on = {  // quirksmode : (document.compatMode=="BackCompat"),  version : parseFloat(navigator.appVersion.match(/MSIE (.+?);/)[1])}@*/;function mouseMove(ev){	ev = ev || window.event;	mousePos = mouseCoords(ev);	}function mouseCoords(ev){	if(ev.pageX || ev.pageY){		return {x:ev.pageX, y:ev.pageY};	}	return {		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,		y:ev.clientY + document.body.scrollTop  - document.body.clientTop	};}/** End mouse position handlers **//**  * Method to show a given glossary term. * * @param HTMLElement	the span which the glossary is contained */function showGlossary(span) {			span.childNodes[1].className = 'show-glossary-term select-free';	if (!is_ie) {		span.childNodes[1].style.left = mousePos.x + "px !important";		span.childNodes[1].style.top = mousePos.y + "px !important";	}		return false;}/** * Method to hide a glossary term. * * @param HTMLElement	the span which the glossary is contained */function hideGlossary(span) {	span.childNodes[1].className = 'hide-glossary-term select-free';	return false;}/** * Method for AJAX platform independence * * @return XMLHTTPRequest	object to use for AJAX request. */function getAjaxObject() {	var xmlHttp=null;	try {		// Firefox, Opera 8.0+, Safari		xmlHttp = new XMLHttpRequest();	} catch (e) {		// Internet Explorer    	try {			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");		} catch (e) {			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");		}	}	return xmlHttp;}/** * Method to urlencode a given string  * * @param clearString 	string to be url encoded * * @param String	url encoded string  */function urlencode (clearString) {	var output = '';	var x = 0;	clearString = clearString.toString();	var regex = /(^[a-zA-Z0-9_.]*)/;	while (x < clearString.length) {		var match = regex.exec(clearString.substr(x));		if (match != null && match.length > 1 && match[1] != '') {			output += match[1];			x += match[1].length;		} else {			if (clearString[x] == ' ')				output += '+';			else {				var charCode = clearString.charCodeAt(x);				var hexVal = charCode.toString(16);				output += '%' + hexVal.toUpperCase();			}			x++;		}	}	return output;}/** * Method to authenticate the user in session and verify the user is still logged in  * * @return Boolean 	true if logged in, false otherwise */function auth() {	var req = getAjaxObject();	req.open("GET", "/applicationRPC.php?method=auth", false);	req.send(null);		if (req.readyState == 4) {		return !!parseInt(req.responseText);	} else {		return false;	}}/** * Method to validate an email  * * @return Boolean 	true if logged in, false otherwise */function validateEmailAjax(email) {	var req = getAjaxObject();	req.open("GET", "/applicationRPC.php?method=validateEmail&email="+urlencode(email), false);	req.send(null);			if (req.readyState == 4) {		return !!parseInt(req.responseText);	} else {		return false;	}}function validateEmail(node) {	if (!validateEmailAjax(node.value)) {		alert("Error: Please make sure your e-mail is valid.");				focusElement(node);						return false;		}		return true;}/** * Method to login a user via AJAX and return if it's valid or not * * @param email		e-mail to validate/authenticate * @param password	password to validate/authenticate */function login(email, password) {	var req = getAjaxObject();	req.open("GET", "/applicationRPC.php?method=login&email="+urlencode(email)+"&password="+urlencode(password), false);	req.send(null);		if (req.readyState == 4) {		setSessionVar('email', email);		return !!parseInt(req.responseText);	} else {		return false;	}}/** * Method to verify if the user is still logged in  * * @return boolean 	true if logged in, false otherwise */function isLoggedIn() {	var req = getAjaxObject();	req.open("GET", "/applicationRPC.php?method=isLoggedIn", false);	req.send(null);		if (req.readyState == 4) {		return !!parseInt(req.responseText);	} else {		return false;	}}/** * Method to save a input field in the application to the database * * @param input		object of the input element  */function saveField (input) {	if ($("loading").className == "") hideLoad = false;	else hideLoad = true;		$("loading").className = "";	if (input.selectedIndex) {		field = input.name;		value = input.options[input.selectedIndex].value;		} else {			field = input.name;		value = input.value;	}	saveFieldReq(field, value);	if (hideLoad) $("loading").className = "hide";		return true;}/** * Method to save a date of birth in the application to the database * * @param prefix 	prefix of the fieldname * @param input		object of the input element  */function saveDOB(prefix, input) {	if ($("loading").className == "") hideLoad = false;	else hideLoad = true;			$("loading").className = "";		if (prefix == '') {		dob = input.form.year_DOB.options[input.form.year_DOB.selectedIndex].value				+ "-" + input.form.month_DOB.options[input.form.month_DOB.selectedIndex].value 				+ "-" + input.form.day_DOB.options[input.form.day_DOB.selectedIndex].value;		fieldname = 'DOB';			} else {		dob = input.form.co_year_DOB.options[input.form.co_year_DOB.selectedIndex].value				+ "-" + input.form.co_month_DOB.options[input.form.co_month_DOB.selectedIndex].value 				+ "-" + input.form.co_day_DOB.options[input.form.co_day_DOB.selectedIndex].value;		fieldname = 'coDOB';	}		saveFieldReq(fieldname, dob);		if (hideLoad) $("loading").className = "hide";}function saveDate(prefix, input) {	if ($("loading").className == "") hideLoad = false;	else hideLoad = true;		$("loading").className = "";	if (prefix == '2ndMortgageMaturity') {			dob = input.form.secondMortgageMaturity_year.options[input.form.secondMortgageMaturity_year.selectedIndex].value				+ "-" + input.form.secondMortgageMaturity_month.options[input.form.secondMortgageMaturity_month.selectedIndex].value 				+ "-" + input.form.secondMortgageMaturity_day.options[input.form.secondMortgageMaturity_day.selectedIndex].value;		fieldname = prefix;			} else if (prefix == 'currentMortgageMaturity') {		dob = input.form.currentMortgageMaturity_year.options[input.form.currentMortgageMaturity_year.selectedIndex].value				+ "-" + input.form.currentMortgageMaturity_month.options[input.form.currentMortgageMaturity_month.selectedIndex].value 				+ "-" + input.form.currentMortgageMaturity_day.options[input.form.currentMortgageMaturity_day.selectedIndex].value;		fieldname = prefix;			} else if (prefix == 'currentHomePurchaseDate') {		dob = input.form.currentHomePurchaseDate_year.options[input.form.currentHomePurchaseDate_year.selectedIndex].value				+ "-" + input.form.currentHomePurchaseDate_month.options[input.form.currentHomePurchaseDate_month.selectedIndex].value 				+ "-" + input.form.currentHomePurchaseDate_day.options[input.form.currentHomePurchaseDate_day.selectedIndex].value;		fieldname = prefix;			}		saveFieldReq(fieldname, dob);	if (hideLoad) $("loading").className = "hide";}/** * Method to handle the application save field requests to the database * * @param field		field name of the field being saved * @param value		value of the field being saved */function saveFieldReq(field, value) {	var req = getAjaxObject();	req.open("GET", "/applicationRPC.php?method=saveField&name="+urlencode(field)+"&value="+urlencode(value), false);	req.send(null);}/** * Method to generate an account save request to the server to save a user after registering * * @param email		email of the user registering * @param password	password of the user registering * * @return boolean 	true if there were no errors, false otherwise */function saveAccountRequest (email, password) {	var req = getAjaxObject();	req.open("GET", "/applicationRPC.php?method=saveAccount&email="+urlencode(email)+"&password="+urlencode(password), false);	req.send(null);		if (req.readyState == 4) {		return !!parseInt(req.responseText);	} else {		return false;	}	}/** * Method to handle logins on the right menu of the website * * @return boolean 	returns false to prevent form from submitting */function tryRightLogin(){		email = $('right-login-email').value;	password = $('right-login-password').value;	if (login(email, password)) {				location.href = "/redirect.php";		} else {		$('right-login-error').style.display = 'block';		new Effect.Shake($('right-login-error'));		}	return false;	}/** * Method to load the application from the database into the application form */function loadApplication () {	$("loading").className = "";	appRequest = getAjaxObject();		appRequest.onreadystatechange = function () {		if (appRequest.readyState == 4) {							doc = appRequest.responseXML.documentElement;			fields = new Array();			var list = doc.getElementsByTagName('field');			// Generate a hash table for ease of use 			for (i=0; i<list.length; i++) {				fields[list[i].getElementsByTagName("name")[0].firstChild.data] = list[i].getElementsByTagName("value")[0].firstChild.data;						}						inputs = document.getElementsByTagName("input");						// Update input fields in the application with database information			for (i=0; i<inputs.length; i++) 				if (inputs[i].type == 'text' && fields[inputs[i].name]) 					inputs[i].value = fields[inputs[i].name];									select = document.getElementsByTagName("select");						// Update select fields in the application with database information			for (i=0; i<select.length; i++) {				if (fields[select[i].name]) {										for (j=0; j<select[i].options.length; j++) {												if (select[i].options[j].value == fields[select[i].name]) {							select[i].selectedIndex = j; 								break;											} 										}				}						}					textarea = document.getElementsByTagName("textarea");						// Update textarea fields in application with database information			for (i=0; i<textarea.length; i++) {				if (fields[textarea[i].name]) {					textarea[i].value = fields[textarea[i].name];				}			}					// Load any data from the session			if (isFromCalc() && hasApplication()) {							message = "You are entering your mortgage application again with calculated numbers from the calculator such as purchase price and maximum mortgage. Do you wish to import these values into your application at this time?";							if (confirm(message)) {					loadFromSession();								}								fromCalcFlag(false);							} else if (isFromCalc()) {				loadFromSession();								fromCalcFlag(false);						}						$("loading").className = "hide";				}			};		appRequest.open("GET", "/applicationRPC.php?method=loadApplication", true);	appRequest.send(null);}function fromCalcFlag(flag) {	var req = getAjaxObject();			if (flag) {		req.open("GET", "/applicationRPC.php?method=fromCalcOn", false);		} else {		req.open("GET", "/applicationRPC.php?method=fromCalcOff", false);		}	req.send(null);	}function isFromCalc() {	var req = getAjaxObject();	req.open("GET", "/applicationRPC.php?method=isFromCalc", false);	req.send(null);			if (req.readyState == 4) {		return !!parseInt(req.responseText);	} else {		return false;	}}function hasApplication() {	var req = getAjaxObject();	req.open("GET", "/applicationRPC.php?method=hasApplication", false);	req.send(null);			if (req.readyState == 4) {		return !!parseInt(req.responseText);	} else {		return false;	}}/** * Method to load persistent input fields from the session */function loadFromSession() {	applicantIncome = getSessionVar('applicant-income');	if (applicantIncome && (applicantIncome - 0) > 0) {		 $('yearlyIncome').value = (applicantIncome - 0) * 12;		 formatNumber($('yearlyIncome'));		 saveField($('yearlyIncome'));	}	coApplicantIncome = getSessionVar('co-applicant-income');	if (coApplicantIncome && (coApplicantIncome - 0) > 0) {		$('coYearlyIncome').value = (coApplicantIncome - 0) * 12;		formatNumber($('coYearlyIncome'));		saveField($('coYearlyIncome'));	}	/*	monthlyCreditCard = getSessionVar('monthly-credit-card');	if (monthlyCreditCard && (monthlyCreditCard - 0) > 0) {		$('creditCard').value = monthlyCreditCard - 0;		formatNumber($('creditCard'));		saveField($('creditCard'));	}	monthlyCar = getSessionVar('monthly-car');	if (monthlyCar && (monthlyCar - 0) > 0) {		$('carPayments').value = monthlyCar - 0;		formatNumber($('carPayments'));		saveField($('carPayments'));	}		monthlyLoan = getSessionVar('monthly-loan');	if (monthlyLoan && (monthlyLoan - 0) > 0) {		$('loans').value = monthlyLoan - 0;		formatNumber($('loans'));		saveField($('loans'));	}	monthlyOther = getSessionVar('monthly-other');	if (monthlyOther && (monthlyOther - 0) > 0) {		$('otherPayments').value = monthlyOther - 0;		formatNumber($('otherPayments'));		saveField($('otherPayments'));	}*/		principal = getSessionVar('principal');	if (principal && (principal - 0) > 0) {		$('neededPrincipal').value = principal - 0;		formatNumber($('neededPrincipal'));		saveField($('neededPrincipal'));				$('require-current-home-purchase-price').value = principal-0;		formatNumber($('require-current-home-purchase-price'));		saveField($('require-current-home-purchase-price'));	}		propertyTaxes = getSessionVar('property-taxes');	if (propertyTaxes && (propertyTaxes - 0) > 0) {		$('yearlyTaxes').value = propertyTaxes - 0;		formatNumber($('yearlyTaxes'));		saveField($('yearlyTaxes'));	}		rateID = getSessionVar('rate-id') - 0;	if (rateID > 0) {		rateTerm = $('desiredTerms');				for (i=0; i<rateTerm.options.length; i++) {			if (rateTerm.options[i].value == rateID) {				rateTerm.selectedIndex = i;				break;						}		}				saveField($('desiredTerms'));	}		amort = getSessionVar('amortization') - 0;	if (amort > 0) {		string = amort;		rateTerm = $('amortizationYears');				for (i=0; i<rateTerm.options.length; i++) {			if (rateTerm.options[i].value == string) {				rateTerm.selectedIndex = i;				break;						}		}				saveField($('amortizationYears'));	}		}/** * Method to handle saves of session variables from input fields *  * @param name		name of the session * @param value 	value of the session field */function setSessionVar(name, value) {		req = getAjaxObject();	req.open("GET", "/session.php?set&name="+urlencode(name)+"&value="+urlencode(value), false);	req.send(null);	return true;}/** * Method to obtain session variables from the session * * @param name 	name of the session variable * * @return string 	the value of the variable */function getSessionVar(name) {		req = getAjaxObject();	req.open("GET", "/session.php?get&name="+urlencode(name), false);	req.send(null);		if (req.readyState == 4) {				if (req.responseText) {			if (req.responseText == ' ') {				return "";			} else {				return req.responseText.strip().strip();			}		} else {			return null;		}			} else {		return null;	}}/** * Method to number format a object with a string  *  * @param obj 	input object to format */function format(obj){	var test;	obj.value = formatString(obj.value);}/** * Method to number format the given string without a warning *  * @param obj 	string to be formatted * * @return string 	formatted number string */function formatWithoutWarn(obj) {	return formatStringWithoutWarn(obj);}/** * Method to number format a given strng without a warning *  * @param temp	string to be formatted * * @return string 	formatted string */ function formatStringWithoutWarn(temp) {	 temp += '';	 temp = commaSplitWithoutWarn(findCommas(temp));		if (temp.match(/\./)) {		test = temp.substr(temp.indexOf("."));		if (test.length < 3)			temp = temp + "0";					} else {		temp = temp;	}		return temp;}/** * Method to format a number string  * * @param temp 	string to be formatted * * @return string 	formatted string  */function formatString(temp){	 temp += '';	 temp = commaSplit(findCommas(temp));		if (temp.match(/\./)) {		test = temp.substr(temp.indexOf("."));		if (test.length < 3)			temp = temp + "0";					} else {		temp = temp;	}		return temp;}/** * Method to load the persistent session fields from page to page */function loadFields() {		nodes = $$('input').toArray();	name = null;	email = null;	mortgagePrincipal = null;	mortgageAmortization = null;	downPayment = null;			// update all input fields	for(i=0; i<nodes.length; i++) {			if (nodes[i].name == 'email' && nodes[i].type == 'text') {			if (email == null) {				//email = getSessionVar('email');						}			nodes[i].value = email;		}				if (nodes[i].name == 'name' && nodes[i].type == 'text') {			if (name == null) {				//name = getSessionVar('name');						}			if (name != null && name != "null")			{				//nodes[i].value = name;				}		}				if ((nodes[i].name == 'principal' || nodes[i].name == 'form-principal')  && nodes[i].type == 'text' && !isNaN(mortgagePrincipal)) {			if (mortgagePrincipal == null) {				mortgagePrincipal = getSessionVar('principal');				}						nodes[i].value = formatString(mortgagePrincipal);							}				if (nodes[i].name == 'amortization' && nodes[i].type == 'text' && mortgageAmortization != ''&& !isNaN(mortgageAmortization)) {			if (mortgageAmortization == null) {				mortgageAmortization = getSessionVar('amortization');			}						nodes[i].value = mortgageAmortization;		}				if (nodes[i].name == 'down-payment' && nodes[i].type == 'text' && downPayment != '' && !isNaN(downPayment)) {			if (downPayment == null) {								downPayment = getSessionVar('down-payment');						}			nodes[i].value = downPayment;		}	}		nodes = document.getElementsByTagName("select");	// update select input boxes	for (i=0; i<nodes.length; i++) {		if (nodes[i].name == "amortization" || nodes[i].name == "amortization-select") {			if (mortgageAmortization == null) {				mortgageAmortization = getSessionVar('amortization');			}			string = mortgageAmortization + "";			for (j=0; j<nodes[i].options.length; j++) {				if (nodes[i].options[j].value == string) {					nodes[i].selectedIndex = j;					break;								}			}		}	}}function validateNumber(num) {	check = num.value;	check = check.replace(/,/g,"");		//remove any spaces	check = check.replace(/\s/g,"");		if (isNaN(check) || check == "") {			alert("Error: That does not appear to be a valid number.  Please try again.");		focusElement(num);			return false;	} else {			return true;	}}function validatePositiveNumber(num) {	if (!validateNumber(num)) return false;	check = num.value;	check = check.replace(/,/g,"");		//remove any spaces	check = check.replace(/\s/g,"");	if (check-0 <= 0) {		alert('Error: Please ensure that the number is greater than zero.');		focusElement(num);		return false;			}		return true;}function validatePositiveZeroNumber(num) {	if (!validateNumber(num)) return false;	check = num.value;	check = check.replace(/,/g,"");		//remove any spaces	check = check.replace(/\s/g,"");	if (check-0 < 0) {		alert('Error: Please ensure that the number is greater than or equal to zero.');		focusElement(num);		return false;			}		return true;}function validatePositiveZeroFillNumber(num) {	if (num.value == '') {		num.value = '0';		return false;	}	if (!validateNumber(num)) return false;	check = num.value;	check = check.replace(/,/g,"");		//remove any spaces	check = check.replace(/\s/g,"");	if (check-0 < 0) {		alert('Error: Please ensure that the number is greater than or equal to zero.');		focusElement(num);		return false;			}		return true;}function validateNameString(node) {		 	a = node.value;	check = Trim(a);	//replace(/^\s{0,}/,''))	node.value = check;		if(check == ""){						alert("Error: Please ensure that this field is not empty.");			focusElement(node);			return false;			}		}function validateReferred(node) {check = node.value;		if (check == "") {		alert("Error: Please ensure that this field is not empty.");		focusElement(node);		return false;	}}	function validateStreet(node) {check = node.value;		if (check == "") {		alert("Error: Please ensure that this field is not empty.");		focusElement(node);		return false;	}}	function validateNotEmpty(node) {	check = node.value;		if (check == "") {		alert("Error: Please ensure that this field is not empty.");		focusElement(node);		return false;	}		return true;}function validateNoNumbers(node) {	check = node.value;		if (check.match(/\d/)) {		alert("Error: Please make sure you do not have numbers in your name.");		focusElement(node);				return false;	}		return true;}function validatePhoneNumber(node) {	check = node.value;		if (check.match(/\D/)) {		alert("Error: Please make sure the phone number only contains numbers.")		focusElement(node);				return false;	}		if (check.length < 10) {		alert("Error: Please make sure the phone number is at least 10 digits long.");		focusElement(node);			return false;	}		return true;}function validatePhoneVarNumber(node, num) {	check = node.value;		if (check.match(/\D/)) {		alert("Error: Please make sure the phone number only contains numbers.")		focusElement(node);				return false;	}		if (check.length < num) {		alert("Error: Please make sure the phone number is at least " + num + " digits long.");		focusElement(node);			return false;	}		return true;}function validateSIN(node) {	check = node.value;		if (check.match(/\D/)) {		alert("Error: Please make sure your SIN only has numbers.");		focusElement(node);				return false;	}	if (check.length != 9) {		alert("Error: Please make sure your SIN is exactly 9 digits long.");		focusElement(node);			return false;	}		return true;}function validatePostalCode(node, type) {	check = node.value.replace(/\b/, "");	if (type == 2) {		if (!check.match(/^[0-9a-zA-Z]+$/)) {			alert("Error: The postal code is not in the right format.");			focusElement(node);						return false;				} 					} else if (type == 1) {		if (!check.match(/^[0-9a-zA-Z]+$/)) {			alert("Error: The postal code is not in the right format.");			focusElement(node);						return false;				} 		} else {				if (!check.match(/^[A-Za-z][0-9][A-Za-z][0-9][A-Za-z][0-9]$/)) {			alert("Error: The postal code is not in the right format.");			focusElement(node);						return false;				} 			}		return true;}function formatNumberNoDec(num) {	string = num.value;		string=string.replace(/,/g,"");	string=string.replace(/\s/g,"");	srcNumber = Math.round(string - 0);		var txtNumber = '' + srcNumber;	var rxSplit = new RegExp('([0-9])([0-9][0-9][0-9][,.])');	var arrNumber = txtNumber.split('.');	arrNumber[0] += '.';	do {					arrNumber[0] = arrNumber[0].replace(rxSplit, '$1,$2');			} while (rxSplit.test(arrNumber[0]));					if (arrNumber.length > 1) {		num.value =  arrNumber.join('');	} else {		num.value = arrNumber[0].split('.')[0];	}			return true;}function formatNumber(num) {	string = num.value;		string=string.replace(/,/g,"");	string=string.replace(/\s/g,"");	srcNumber = roundToTwoDecimalPlaces(string);			var txtNumber = '' + srcNumber;	var rxSplit = new RegExp('([0-9])([0-9][0-9][0-9][,.])');	var arrNumber = txtNumber.split('.');	arrNumber[0] += '.';	do {					arrNumber[0] = arrNumber[0].replace(rxSplit, '$1,$2');			} while (rxSplit.test(arrNumber[0]));					if (arrNumber.length > 1) {		num.value =  arrNumber.join('');	} else {		num.value = arrNumber[0].split('.')[0];	}		if (num.value.split('.').length == 1) {		num.value = num.value + ".00";		}	if (num.value.split('.').length == 2 && num.value.split('.')[1].length == 1) {		num.value = num.value.split('.')[0] + "." + num.value.split('.')[1] + "0";	}	return true;}/* function formatNumberValue(num) {	string = num;	returnval = '';		string=string.replace(/,/g,"");	string=string.replace(/\s/g,"");	srcNumber = roundToTwoDecimalPlaces(string);			var txtNumber = '' + srcNumber;	var rxSplit = new RegExp('([0-9])([0-9][0-9][0-9][,.])');	var arrNumber = txtNumber.split('.');	arrNumber[0] += '.';	do {					arrNumber[0] = arrNumber[0].replace(rxSplit, '$1,$2');			} while (rxSplit.test(arrNumber[0]));					if (arrNumber.length > 1) {		returnval =  arrNumber.join('');	} else {		returnval = arrNumber[0].split('.')[0];	}		if (returnval.split('.').length == 1) {		returnval = returnval + ".00";		}	if (returnval.split('.').length == 2 && returnval.split('.')[1].length == 1) {		returnval = returnval.split('.')[0] + "." + returnval.split('.')[1] + "0";	}	return returnval;} */function formatNumberValue(num, round) {	string = num + "";	returnval = '';		string=string.replace(/,/g,"");	string=string.replace(/\s/g,"");	if (round == 0) {		srcNumber = Math.round(string-0);	} else {		srcNumber = roundToTwoDecimalPlaces(string);	}		var txtNumber = '' + srcNumber;	var rxSplit = new RegExp('([0-9])([0-9][0-9][0-9][,.])');	var arrNumber = txtNumber.split('.');	arrNumber[0] += '.';	do {					arrNumber[0] = arrNumber[0].replace(rxSplit, '$1,$2');			} while (rxSplit.test(arrNumber[0]));					if (arrNumber.length > 1) {		returnval =  arrNumber.join('');	} else {		returnval = arrNumber[0].split('.')[0];	}		if (round != 0) {		if (returnval.split('.').length == 1) {			returnval = returnval + ".00";				}			if (returnval.split('.').length == 2 && returnval.split('.')[1].length == 1) {				returnval = returnval.split('.')[0] + "." + returnval.split('.')[1] + "0";		}	}		return returnval;}/** * Method to add commas and decimal point to a given number string  * * @param srcNumber 	string of the number  * * @return string 		formatted number */function commaSplit(srcNumber)  {	srcNumber = roundToTwoDecimalPlaces(srcNumber);	var txtNumber = '' + srcNumber;	if (isNaN(txtNumber) || txtNumber == "") {		alert("Error: That does not appear to be a valid number.  Please try again.");		} else {		var rxSplit = new RegExp('([0-9])([0-9][0-9][0-9][,.])');		var arrNumber = txtNumber.split('.');		arrNumber[0] += '.';		do {						arrNumber[0] = arrNumber[0].replace(rxSplit, '$1,$2');				} while (rxSplit.test(arrNumber[0]));						if (arrNumber.length > 1) {			return arrNumber.join('');		} else {			return arrNumber[0].split('.')[0];		}	   	}}/** * Method to add commas and decimal point to a given number string without a warning * * @param srcNumber 	string of the number  * * @return string 		formatted number */function commaSplitWithoutWarn(srcNumber)  {		srcNumber = roundToTwoDecimalPlaces(srcNumber);	var txtNumber = '' + srcNumber;		if (isNaN(txtNumber) || txtNumber == "") {		return "0";	} else {		var rxSplit = new RegExp('([0-9])([0-9][0-9][0-9][,.])');		var arrNumber = txtNumber.split('.');		arrNumber[0] += '.';		do {						arrNumber[0] = arrNumber[0].replace(rxSplit, '$1,$2');				} while (rxSplit.test(arrNumber[0]));						if (arrNumber.length > 1) {			return arrNumber.join('');		} else {			return arrNumber[0].split('.')[0];		}	   	}}/** * Method to remove commas and spaces froma string  * * @param string 	string to be processed *  * @return string 	string with commas and spaces removed */function findCommas(string){	//remove any commas	string=string.replace(/,/g,"");		//remove any spaces	string=string.replace(/\s/g,"");		return string;}/** * Method to round a given number to two decimal places * * @param string 	number to be round to two decimal places * * @return string 	number rounded to two decimal places */function roundToTwoDecimalPlaces(string) {		return Math.round((string - 0)*100)/100;}/** onload handler for persistent session variables **/Event.observe(window, 'load',	 function () {			//loadFields();			});/** * Method to show the proper video on click of the video link * * @param 	video	node of the video selected */function showVideo(video) {	videolist = document.getElementById('video-list');		for(i=0; i<videolist.childNodes.length; i++) {		videolist.childNodes[i].className = '';	}		document.getElementById('video-'+video).className = "selected";	return false;}/** * Method to save rates to persistent session variables * * @param row 	select row to save */function saveRates(row) {	if (selectedBank == '') {		alert('Error: Please select a lender.');		return false;	}		prin = findCommas($('principal').value);	down = findCommas($('down-payment').value);		a = $('amortization');	if (a == null) a = $('form-amortization');	amort = findCommas(a.value);			setSessionVar('principal', prin);	setSessionVar('down-payment', down);	setSessionVar('amortization', amort);	setSessionVar('bank-preference', selectedBank);	therates = new Array();	inputs = document.getElementsByTagName("input");	count = 0;	for(i=0; i<inputs.length; i++) {		if (inputs[i].name == "rateid") {			therates[count] = inputs[i].value;			count++;		}	}	rateID = therates[row-1];	setSessionVar('rate-id', rateID);		fromCalcFlag(true);		location.href = "/preapproval.php";}/** * Method to add a contact to the groups page */function addContact() {	node = document.getElementById('contact').cloneNode(true);		node.childNodes[1].value = '';	node.childNodes[3].value = '';		document.getElementById('list').appendChild(node);}$cur_text =0;function addincluded() {         	if($cur_text==5)			{	alert('cannot enter more than five textboxes');	    }		else		{		for(i=1;i<=$cur_text+1;i++)	{	document.getElementById('show'+($cur_text+1)).style.display="block";	}	$cur_text += 1;		}}/** * Method to focus the form element given * * @param node 	form element node to be focused */function focusElement(node) {	errorfocus = node;	setTimeout('errorfocus.focus()', 150);	setTimeout('errorfocus.select()', 152);}function validateAdvertise(node) {	if (!validateEmailForm(node)) return false;	if (node.send_industry.value == '') {		alert("Error: You must enter an Industry.");				focusElement(node.send_industry);				return false;	}		if (node.send_business_name.value == '') {				alert("Error: You must enter a Business Name.");		focusElement(node.send_business_name);				return false;		}	if (node.phone_area.value == '') {				alert("Error: You must enter your phone number area code.");		focusElement(node.phone_area);				return false;		}	if (node.phone_first_three.value == '') {				alert("Error: You must enter the first three digits of your phone number.");		focusElement(node.phone_first_three);				return false;		}	if (node.phone_last_four.value == '') {				alert("Error: You must enter your the last four digits of your phone number.");		focusElement(node.phone_last_four);				return false;	}		if (node.send_business_email.value == '') {				alert("Error: You must enter your business email.");		focusElement(node.send_business_email);				return false;		} else if (!validateEmail(node.send_business_email)) {		return false;	}	if (node.send_business_address.value == '') {				alert("Error: You must enter your business address.");		focusElement(node.send_business_address);				return false;		}		return true;	}function validateEmailForm(node) {	if (node.name.value == '') {		alert("Error: You must enter your name.");		focusElement(node.name);				return false;	}		if (node.email.value == '') {			alert("Error: You must enter an e-mail address.");		focusElement(node.email);				return false;	} else if (!validateEmail(node.email)) {		return false;	}		return true;}function validateAddVideo(node) {	if (!validateEmailForm(node)) return false;	if (node.send_url.value == '') {				alert("Error: You must enter the address of the YouTube Video.");		focusElement(node.send_url);				return false;		}		return true;	}function validateMover(node) {	if (!validateEmailForm(node)) return false;	if (node.inspectionaddress.value == '' || node.inspection.value == '' || node.inspectiondate.value == '' || node.name.value == '' || node.email.value == '' || node.phone.value == '' ) {				alert("Error: You must enter all the requied fields.");		focusElement(node.inspectionaddress);				return false;		}		return true;	}function validateInspection(node) {	if (!validateEmailForm(node)) return false;	if (node.inspectionaddress.value == '' || node.inspection.value == '' || node.inspectiondate.value == '' || node.name.value == '' || node.email.value == '' || node.phone.value == '' ) {				alert("Error: You must enter all the requied fields.");		focusElement(node.inspectionaddress);				return false;		}		return true;	}function validateFeedback(node) {		if (!validateEmailForm(node)) return false;	if (node.send_feedback.value == '') {				alert("Error: You must enter your feedback.");		focusElement(node.send_feedback);				return false;		}		return true;	}function validateSpecialist(node) {	if (!validateEmailForm(node)) return false;	if (node.send_comment.value == '') {				alert("Error: You must enter your question/comment for our specialist.");		focusElement(node.send_comment);				return false;		}		return true;	}function validateGetReferral(node) {	if (!validateEmailForm(node)) return false;		return true;	}function validateGiveReferral(node) {	if (!validateEmailForm(node)) return false;	if (node.send_referral_name.value == '') {		alert("Error: You must enter the first and last name of the referral.");				focusElement(node.send_referral_name);				return false;	}		if (node.send_referral_business_name.value == '') {				alert("Error: You must enter the referral's business name.");		focusElement(node.send_referral_business_name);				return false;		}		if (node.send_referral_business_email.value == '') {				alert("Error: You must enter the referral's business e-mail.");		focusElement(node.send_referral_business_email);				return false;		} else if (!validateEmail(node.send_referral_business_email)) {		return false;	}					if (node.phone_area.value == '') {				alert("Error: You must enter your phone number area code.");		focusElement(node.phone_area);				return false;		}	if (node.phone_first_three.value == '') {				alert("Error: You must enter the first three digits of your phone number.");		focusElement(node.phone_first_three);				return false;		}	if (node.phone_last_four.value == '') {				alert("Error: You must enter your the last four digits of your phone number.");		focusElement(node.phone_last_four);				return false;	}		if (node.send_referral_business_address.value == '') {				alert("Error: You must enter your business address.");		focusElement(node.send_referral_business_address);				return false;		}		return true;}function validateGroups(node) {	if (node.groupName.value == '') {		alert("Error: You must enter the name of your group.");				focusElement(node.groupName);				return false;	}	if (!validateEmailForm(node)) return false;		count = 0;	firstCount = 0;	first = null;		a = $$('input');		for (i=0; i<a.length; i++) {		if (a[i].name == 'E[]') {			if (firstCount == 0) first = a[i];								if (a[i].value != '') {				count++;				t = a[i-1];				if (t.value == '') {										alert("Error: Please make sure you enter the name for the reciepient with the email of " + a[i].value + ".");					focusElement(t);											return false;								}			}						firstCount++;		}		}			if (count == 0) {		alert("Error: Please make sure you enter at least one e-mail address for your group members.");				if (first) {			focusElement(first);		}				return false;	}		return true;}function validateRenewal(node) {		if (!validateEmailForm(node)) return false;		theDate = new Date();	today = new Date();	theDate.setFullYear(node.year.options[node.year.selectedIndex].value, node.month.options[node.month.selectedIndex].value-1, node.day.options[node.day.selectedIndex].value);	if (theDate <= today) {		alert('Error: Please make sure you enter a date that is in the future.');		node.month.focus();		return false;		}		return true;	}function validateRateAlert(node) {		if (!validateEmailForm(node)) return false;		if (!checkNumber(node.send_rate_low.value)) {		alert("Error: Please enter a valid number for the low rate.");		focusElement(node.send_rate_low);				return false;	}			if (!checkNumber(node.send_rate_high.value)) {		alert("Error: Please enter a valid number for the high rate.");		focusElement(node.send_rate_high);				return false;	}				if (node.send_rate_low.value - 0 > node.send_rate_high.value) {		alert('Error: Please make sure the low rate is less than the high rate');		focusElement(node.send_rate_low);				return false;	}		return true;	}function validateNewsletter(node) {		if (!validateEmailForm(node)) return false;	return true;}/* APPLICATION.js *//** * Method to switch between application form pages *  * @param page	the page number that the the function will switch to * @param obj	deprecaited  */function switchPage(page, obj) {	document.getElementById('application-page-one').style.display = 'none';	document.getElementById('application-page-two').style.display = 'none';	document.getElementById('application-page-three').style.display = 'none';		li = document.getElementsByTagName('li');		// Loop through the pages hide the other pages	count = 1;	for (i=0; i<li.length; i++) {		if (li[i].parentNode.id == 'application-page-nav') {			li[i].className = '';			if (count == page) li[i].className = 'active';					count++;		}				}	// Pick the page to show	show = '';	if (page == 2) {		show = 'application-page-two';			} else if (page == 3) {		show = 'application-page-three';	} else if (page == 1) {		show = 'application-page-one';			} 	if (show != '') {		document.getElementById(show).style.display = 'block';	}}/** * Handlers to load the application form on page load. * */var joinPage = false;function focusElementApp(node) {	errorfocus = node;		setTimeout('errorfocus.focus()', 400);	setTimeout('errorfocus.select()', 405);}/** * Method to check application form for any inconsistencies * * @return boolean true if all valid, false is not valid */function checkPreApp() {	// Validate agreement for the terms & conditions	if (!document.getElementById("agree").checked) {		alert("You must agree to the terms and conditions to continue.");		focusElement($("agree"));		return false;	}		if (document.getElementById("mortgage_status").value == '') {		alert("Error: Please make sure the status field is filled out." );		focusElement($("mortgage_status"));		return false;	}		if (document.getElementById("mortgage_type").value == '') {		alert("Error: Please make sure the Heard of Buyingblock from field is filled out." );		focusElement($("mortgage_type"));		return false;	}		if (document.getElementById("currentProvince").value == '') {		alert("Error: Please make sure the Prov. field is filled out." );		focusElement($("currentProvince"));		return false;	}			if (document.getElementById("employerYears").value == '') {		alert("Error: Please make sure the Length of Emplyment field is filled out." );		focusElement($("employerYears"));		return false;	}		inputs = document.getElementsByTagName("input");		// Check every field in the application	for(i=0; i<inputs.length; i++) {	if(inputs[i].id == 'require-sin')	{	continue;	}			if (inputs[i].id.substr(0, 8) == 'require-') {			if (inputs[i].value == '') {												// Validate text fields on Page One				w = document.getElementById("application").getElementsByTagName("input");								for(j=0; j<w.length; j++) {					if (w[j].name == inputs[i].name) {						alert("Error: Please make sure the " + inputs[i].id.substr(8).replace(/-/g, ' ') + " field is filled out.");						focusElementApp(inputs[i]);																		return false;					}				}								return false;								}				}	}	if (document.getElementById("require-month-DOB").value == '') {		alert("Error: Please make sure the month of birth date field is filled out." );		focusElement($("require-month-DOB"));		return false;	}	if (document.getElementById("require-day-DOB").value == '') {		alert("Error: Please make sure the day of birth date field is filled out." );		focusElement($("require-day-DOB"));		return false;	}	if (document.getElementById("require-year-DOB").value == '') {		alert("Error: Please make sure the year of birth date field is filled out." );		focusElement($("require-year-DOB"));		return false;	}	// Validate SIN	if(document.getElementById("require-sin").value != '')	{	if (!checkSIN(document.getElementById("require-sin").value)) {		alert("Error: Please make sure you have entered your SIN number correctly.");		focusElementApp($("require-sin"));		//switchPage(1);		return false;	}	}	// Validate home phone number	if (!checkPhone(document.getElementById("require-home-phone").value)) {		alert("Error: Please make sure you have entered your home phone number correctly.");		focusElementApp($("require-home-phone"));		//switchPage(1);		return false;	}			// Validate yearly income	if (document.getElementById("yearlyIncome").value == '') {		alert("Error: Please make sure the yearly income field is filled out.");		focusElementApp($("yearlyIncome"));		//switchPage(1);		return false;	}	    if (document.getElementById("yearlyIncome").value <= 0) {		alert("Error: Income should be greater than 0");		focusElementApp($("yearlyIncome"));		//switchPage(1);		return false;	}	 	 			return true;}/** * Method to check application form for any inconsistencies * * @return boolean true if all valid, false is not valid */function checkApp() {	// Validate agreement for the terms & conditions	if (!document.getElementById("agree").checked) {		alert("You must agree to the terms and conditions to continue.");		focusElement($("agree"));		return false;	}			inputs = document.getElementsByTagName("input");		// Check every field in the application	for(i=0; i<inputs.length; i++) {		if( inputs[i].id == 'require-first-name' || inputs[i].id == 'require-last-name' || inputs[i].id == 'require-current-street' || inputs[i].id == 'require-current-city' || inputs[i].id == 'require-current-postal' || inputs[i].id == 'require-current-postal-second' || inputs[i].id == 'require-current-occupation'  )		{					if (inputs[i].id.substr(0, 8) == 'require-') {				if (inputs[i].value == '') {														// Validate text fields on Page One					w = document.getElementById("application").getElementsByTagName("input");										for(j=0; j<w.length; j++) {						if (w[j].name == inputs[i].name) {							alert("Error: Please make sure the " + inputs[i].id.substr(8).replace(/-/g, ' ') + " field is filled out.");							focusElementApp(inputs[i]);																				return false;						}					}										/*					// Validate text fields on Page Two					w = document.getElementById("application-page-two").getElementsByTagName("input");															for(j=0; j<w.length; j++) {						if (w[j].name == inputs[i].name) {							alert("Error: Please make sure the " + inputs[i].id.substr(8).replace(/-/g, ' ') + " field is filled out.");							focusElementApp(inputs[i]);								//switchPage(2);							return false;						}					}															// Validate text fields on Page Three					w = document.getElementById("application-page-three").getElementsByTagName("input");										for(j=0; j<w.length; j++) {						if (w[j].name == inputs[i].name) {							alert("Error: Please make sure the " + inputs[i].id.substr(8).replace(/-/g, ' ') + " field is filled out.");							focusElementApp(inputs[i]);								//switchPage(3);							return false;						}					}					*/										return false;										}						}		}		}		// Validate SIN	/*if(document.getElementById("require-sin").value != '')	{		if (!checkSIN(document.getElementById("require-sin").value)) {			alert("Error: Please make sure you have entered your SIN number correctly.");			focusElementApp($("require-sin"));			//switchPage(1);			return false;		}	} */	// Validate home phone number	if (document.getElementById("require-month-DOB").value == '') {		alert("Error: Please make sure the month of birth date field is filled out." );		focusElement($("require-month-DOB"));		return false;	}	if (document.getElementById("require-day-DOB").value == '') {		alert("Error: Please make sure the day of birth date field is filled out." );		focusElement($("require-day-DOB"));		return false;	}	if (document.getElementById("require-year-DOB").value == '') {		alert("Error: Please make sure the year of birth date field is filled out." );		focusElement($("require-year-DOB"));		return false;	}	if(document.getElementById("require-home-phone").value != '')	{		if (!checkPhone(document.getElementById("require-home-phone").value)) {			alert("Error: Please make sure you have entered your home phone number correctly.");			focusElementApp($("require-home-phone"));			//switchPage(1);			return false;		}	}		// Validate work phone number	if(document.getElementById("require-work-phone").value != '')	{		if (!checkPhone(document.getElementById("require-work-phone").value)) {			alert("Error: Please make sure you have entered your work phone number correctly.");			focusElementApp($("require-work-phone"));			//switchPage(1);			return false;		}	}		// Validate co-applicant's phone number	if (!checkPhone(document.getElementById("coPhone").value) & document.getElementById("coPhone").value != null & document.getElementById("coPhone").value != '') {		alert("Error: Please make sure you have entered your co-applicant's home phone number correctly.");		focusElementApp($("coPhone"));		//switchPage(1);		return false;	}		// Validate yearly income	if (document.getElementById("yearlyIncome").value == '' || document.getElementById("yearlyIncome").value == '0') {		alert("Error: Please make sure the yearly income field is filled out.");		focusElementApp($("yearlyIncome"));		//switchPage(1);		return false;	}			// Validate Principal needed	if (document.getElementById("neededPrincipal").value == '') {		alert("Error: Please make sure the purchase price needed field is filled out.");				focusElementApp($("neededPrincipal"));		//switchPage(3);		return false;	}			// Validate yearly taxes	if (document.getElementById("yearlyTaxes").value == '') {		alert("Error: Please make sure the yearly taxes field is filled out.");		focusElementApp($("yearlyTaxes"));		//switchPage(3);		return false;	}		return true;}/** * Method to save account using AJAX * * @return boolean returns false to prevent action from happening. */function checkrenewalApp() {	// Validate agreement for the terms & conditions	if (!document.getElementById("agree").checked) {		alert("You must agree to the terms and conditions to continue.");		focusElement($("agree"));		return false;	}			inputs = document.getElementsByTagName("input");		// Check every field in the application	for(i=0; i<inputs.length; i++) {		if( inputs[i].id == 'require-first-name' || inputs[i].id == 'require-last-name' || inputs[i].id == 'require-current-street' || inputs[i].id == 'require-current-city' || inputs[i].id == 'require-current-postal' || inputs[i].id == 'require-current-postal-second' || inputs[i].id == 'require-current-occupation'  )		{					if (inputs[i].id.substr(0, 8) == 'require-') {				if (inputs[i].value == '') {														// Validate text fields on Page One					w = document.getElementById("application").getElementsByTagName("input");										for(j=0; j<w.length; j++) {						if (w[j].name == inputs[i].name) {							alert("Error: Please make sure the " + inputs[i].id.substr(8).replace(/-/g, ' ') + " field is filled out.");							focusElementApp(inputs[i]);																				return false;						}					}										/*					// Validate text fields on Page Two					w = document.getElementById("application-page-two").getElementsByTagName("input");															for(j=0; j<w.length; j++) {						if (w[j].name == inputs[i].name) {							alert("Error: Please make sure the " + inputs[i].id.substr(8).replace(/-/g, ' ') + " field is filled out.");							focusElementApp(inputs[i]);								//switchPage(2);							return false;						}					}															// Validate text fields on Page Three					w = document.getElementById("application-page-three").getElementsByTagName("input");										for(j=0; j<w.length; j++) {						if (w[j].name == inputs[i].name) {							alert("Error: Please make sure the " + inputs[i].id.substr(8).replace(/-/g, ' ') + " field is filled out.");							focusElementApp(inputs[i]);								//switchPage(3);							return false;						}					}					*/										return false;										}						}		}		}		// Validate SIN	/*if(document.getElementById("require-sin").value != '')	{		if (!checkSIN(document.getElementById("require-sin").value)) {			alert("Error: Please make sure you have entered your SIN number correctly.");			focusElementApp($("require-sin"));			//switchPage(1);			return false;		}	} */	// Validate home phone number	if (document.getElementById("require-month-DOB").value == '') {		alert("Error: Please make sure the month of birth date field is filled out." );		focusElement($("require-month-DOB"));		return false;	}	if (document.getElementById("require-day-DOB").value == '') {		alert("Error: Please make sure the day of birth date field is filled out." );		focusElement($("require-day-DOB"));		return false;	}	if (document.getElementById("require-year-DOB").value == '') {		alert("Error: Please make sure the year of birth date field is filled out." );		focusElement($("require-year-DOB"));		return false;	}	if(document.getElementById("require-home-phone").value != '')	{		if (!checkPhone(document.getElementById("require-home-phone").value)) {			alert("Error: Please make sure you have entered your home phone number correctly.");			focusElementApp($("require-home-phone"));			//switchPage(1);			return false;		}	}		// Validate work phone number	if(document.getElementById("require-work-phone").value != '')	{		if (!checkPhone(document.getElementById("require-work-phone").value)) {			alert("Error: Please make sure you have entered your work phone number correctly.");			focusElementApp($("require-work-phone"));			//switchPage(1);			return false;		}	}		// Validate co-applicant's phone number	if (!checkPhone(document.getElementById("coPhone").value) & document.getElementById("coPhone").value != null & document.getElementById("coPhone").value != '') {		alert("Error: Please make sure you have entered your co-applicant's home phone number correctly.");		focusElementApp($("coPhone"));		//switchPage(1);		return false;	}		// Validate yearly income	if (document.getElementById("yearlyIncome").value == '' || document.getElementById("yearlyIncome").value == '0') {		alert("Error: Please make sure the yearly income field is filled out.");		focusElementApp($("yearlyIncome"));		//switchPage(1);		return false;	}			// Validate Principal needed	if (document.getElementById("neededPrincipal").value == '') {		alert("Error: Please make sure the purchase price needed field is filled out.");				focusElementApp($("neededPrincipal"));		//switchPage(3);		return false;	}			// Validate yearly taxes	if (document.getElementById("yearlyTaxes").value == '') {		alert("Error: Please make sure the yearly taxes field is filled out.");		focusElementApp($("yearlyTaxes"));		//switchPage(3);		return false;	}		return true;}function saveAccount() {	email = document.getElementById('register-email').value;	password = document.getElementById('register-password').value;	passwordAgain = document.getElementById('register-password-again').value;	if (password.length < 5) {		alert("Error: your password must be at least 5 characters long.");		} else {			if (password != passwordAgain) {			alert("Error: The passwords don't match. Please try again");					} else {			// save the account and try to login			if (saveAccountRequest(email, password) && login(email, password)){								if (!joinPage) fadeOutSave();				else fadeOut();							} else {				document.getElementById('registration-error').style.display = 'block';				}		}	}	return false;}/** * Method to try a login  * * @return boolean false to prevent form from reloading page */function tryLogin(){	email = document.getElementById('login-email').value;	password = document.getElementById('login-password').value;	if (login(email, password)) {			//loadApplication();			//$('toLink').value			fadeOut();		} else {		document.getElementById('login-error').style.display = 'block';			}	return false;}function expandPrevious(node) {	if (node.options[node.selectedIndex].value == "3 yrs." ||		node.options[node.selectedIndex].value == "2 yrs." ||		node.options[node.selectedIndex].value == "1 year" ||		node.options[node.selectedIndex].value == "< 1") {				new Effect.SlideDown($('app-previous'), {duration: .5});		} else {		new Effect.SlideUp($('app-previous'), {duration: .5});	}}function expandPreviousCo(node) {	if (node.options[node.selectedIndex].value == "3 yrs." ||		node.options[node.selectedIndex].value == "2 yrs." ||		node.options[node.selectedIndex].value == "1 year" ||		node.options[node.selectedIndex].value == "< 1") {				new Effect.SlideDown($('coapp-previous'));		} else {		new Effect.SlideUp($('coapp-previous'));	}}function expandPreviousCo1(node) {	if (node.options[node.selectedIndex].value == "3 yrs." ||		node.options[node.selectedIndex].value == "2 yrs." ||		node.options[node.selectedIndex].value == "1 year" ||		node.options[node.selectedIndex].value == "< 1") {				new Effect.SlideDown($('coapp-previous1'));		} else {		new Effect.SlideUp($('coapp-previous1'));	}}/** * Method to check phone Number * * @param val 	Phone Number * * @return Boolean	true if valid, false otherwise */function checkPhone(val) {	if (checkNumber(val)) {		return true;	} else return false;}/** * Method to check SIN * * @param val 	SIN * * @return Boolean true if valid, false otherwise */function checkSIN(val) {	if (checkNumber(val)) {		return true;	} else return false;}/** * Method to validate that the given value is a Number * * @param value  	string to check * * @return boolean 	true if valid, false otherwise */function checkNumber(value){	var anum=/(^\d+$)|(^\d+\.\d+$)/		if (anum.test(value))		testresult=true	else{		// alert("Please input a valid number!")		testresult=false	}	return (testresult);}/** * Method handle clicked links on the application page and prompt for registration * * @param link	link that has been clicked */function clickLink(link) {	// decided which link to use 	if (link) {				if (link.href)			$('toLink').value = link.href;		else			$('toLink').value = $('homeLink').href;	} else {		$('toLink').value = 'refresh';	}	// Bypass if logged in	if (isLoggedIn()) {			//alert("Your application has been saved.");				setTimeout('openToLink()', 400);		// Show registration page		} else {			window.location = String(window.location).replace(/\#.*$/, "") + "#top";		$('registerOverlay').className = 'select-free';		$('registerWindow').className = '';		sizeArray = getPageSize();		$('registerOverlay').style.height = sizeArray[0] + 'px';				new Effect.Opacity('registerWindow', { duration: 0.5, transition: Effect.Transitions.linear, from: 0.0, to: 1.0 });		new Effect.Opacity('registerOverlay', { duration: 0.5, transition: Effect.Transitions.linear, from: 0.0, to: 0.7 });	}	}function fadeOutSave() {		alert("You application has been saved.");		fadeOut();}/** * Method to fade out registration window */function fadeOut () {	new Effect.Opacity('registerWindow', { duration: 0.3, transition: Effect.Transitions.linear, from: 1.0, to: 0.0 });	new Effect.Opacity('registerOverlay', { duration: 0.3, transition: Effect.Transitions.linear, from: 0.7, to: 0.0 });	setTimeout('openToLink()', 400);}/** * Method to open a link in the 'toLink' element  */function openToLink() {	if ($('toLink').value == 'refresh') {		location.href = '/';	} else {			location.href = $('toLink').value;	}}/** getPageSize() * Returns array with page width, height and window width, height * Core code from - quirksmode.org * Edit for Firefox by pHaez */function getPageSize(){		var xScroll, yScroll;		if (window.innerHeight && window.scrollMaxY) {			xScroll = document.body.scrollWidth;		yScroll = window.innerHeight + window.scrollMaxY;	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac		xScroll = document.body.scrollWidth;		yScroll = document.body.scrollHeight;	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari		xScroll = document.body.offsetWidth;		yScroll = document.body.offsetHeight;	}		var windowWidth, windowHeight;	if (self.innerHeight) {	// all except Explorer		windowWidth = self.innerWidth;		windowHeight = self.innerHeight;	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode		windowWidth = document.documentElement.clientWidth;		windowHeight = document.documentElement.clientHeight;	} else if (document.body) { // other Explorers		windowWidth = document.body.clientWidth;		windowHeight = document.body.clientHeight;	}			// for small pages with total height less then height of the viewport	if(yScroll < windowHeight){		pageHeight = windowHeight;	} else { 		pageHeight = yScroll;	}	// for small pages with total width less then width of the viewport	if(xScroll < windowWidth){			pageWidth = windowWidth;	} else {		pageWidth = xScroll;	}	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 	return arrayPageSize;}/** * Method to add a debt field in the application form *** deprecaited */function addDebt() {	if ($('debtstable').getElementsBySelector('tr').length >= 11) return;			node = document.getElementById('debt').cloneNode(true);		//clear values	$(node).getElementsBySelector("input").each(function(e) { e.value = ''; });			node.id = '';	document.getElementById('debtstable').appendChild(node);}/* CALCULATE.js *//** * Method to handle rate calculation on the rates page. * It uses the data from the tables to calculate the costs *  * @param bank		the name of the bank that was selected * @param column	the column that was selected * */function calculateRates(bank, column) {	var result = '';	var address = column+1;	selectedBank = bank;		if ($('down-payment').value == '') $('down-payment').value = 0;		if (!validatePositiveNumber($('principal')) || !validatePositiveZeroNumber($('down-payment')) ) return false;		if (findCommas($('down-payment').value)-0 >= findCommas($('principal').value)-0) {		alert("Error: Please make sure your purchase price is greater than your down payment.");		focusElement($('principal'));				return false;		}		var principal = $('principal').value 	var downpayment = $('down-payment').value;	var amort = $('form-amortization-select');	var term = amort.options[amort.selectedIndex].value;	var ratesTable = $('table-rates');		principal = (findCommas(principal)-0) - (findCommas(downpayment)-0);		resetRatesTableFormatting();	terms = new Array();	inputs = document.getElementsByTagName("input");	count = 0;	// obtain the terms	for(i=0; i<inputs.length; i++) {		if (inputs[i].name == "term") {			terms[count] = inputs[i].value;			count++;		}	}		// go through each rate and calculate the monthly payment and savings	for (i=1; i<ratesTable.rows.length-1; i++) {		bankRate = ratesTable.rows[i].childNodes[address].innerHTML -0;		bbRate = ratesTable.rows[i].childNodes[9].innerHTML -0;		rateTerm = terms[i-1]-0;		ratesTable.rows[i].childNodes[address].className = 'rates-bank-selected';				// bank monthly		var bankMonthly = calcMonthlyMortgagePayment(principal, bankRate, term);		if (bankMonthly <= 0 || isNaN(bankMonthly)) bankMonthly = 'N/A';		else bankMonthly = formatNumberValue(bankMonthly, 2);				// bb monthly		ratesTable.rows[i].childNodes[10].innerHTML = bankMonthly;				var bbMonthly = calcMonthlyMortgagePayment(principal, bbRate, term);		if (bbMonthly <= 0 || isNaN(bbMonthly)) bbMonthly = 'N/A';		else bbMonthly = formatNumberValue(bbMonthly, 2);		ratesTable.rows[i].childNodes[11].innerHTML = bbMonthly;		var savings = roundToTwoDecimalPlaces((findCommas(bankMonthly) - findCommas(bbMonthly))*rateTerm);		if (savings <= 0 || isNaN(savings)) savings = 'N/A';		else savings = formatNumberValue(savings, 2);				ratesTable.rows[i].childNodes[12].innerHTML = savings;	}	scrollToAnchor("calcRates");}function calculateRates_gkl(bank, column) {		var result = '';	var address = column+1;	selectedBank = bank;		if ($('down-payment').value == '') $('down-payment').value = 0;		if (!validatePositiveNumber($('principal')) || !validatePositiveZeroNumber($('down-payment')) ) return false;		if (findCommas($('down-payment').value)-0 >= findCommas($('principal').value)-0) {		alert("Error: Please make sure your purchase price is greater than your down payment.");		focusElement($('principal'));				return false;		}			var principal = $('principal').value 	var downpayment = $('down-payment').value;	var amort = $('form-amortization-select');	var term = amort.options[amort.selectedIndex].value;	var ratesTable = $('table-rates');		principal = (findCommas(principal)-0) - (findCommas(downpayment)-0);		resetRatesTableFormatting_gkl();	terms = new Array();	inputs = document.getElementsByTagName("input");	count = 0;	// obtain the terms	for(i=0; i<inputs.length; i++) {		if (inputs[i].name == "term") {			terms[count] = inputs[i].value;			count++;		}	}	var rowsxTable = ratesTable.rows.length-1;		for (j=2; j<10; j++) {		var bestRate = 999;		var highestRate = 0;		for (i=1; i<rowsxTable-4; i++) {			bankRate = ratesTable.rows[i].childNodes[j].innerHTML -0;			bbRate = ratesTable.rows[1].childNodes[j].innerHTML -0;						if (bankRate == "---") {				continue;			}						     	if (bankRate < bestRate) {				bestRate = bankRate;	     	}							if (bankRate > highestRate) {				highestRate = bankRate;			}					}		// Hightlight best rates		/*		for (i=1; i<rowsxTable-4; i++) {			currCell = ratesTable.rows[i].childNodes[j].innerHTML -0;	     	if (currCell == bestRate) {					ratesTable.rows[i].childNodes[j].className = 'rates-bank-selected';	     	}		}		*/					rateTerm = terms[j-1]-0;		var bestMonthly = calcMonthlyMortgagePayment(principal, bestRate, term);		if (bestMonthly <= 0 || isNaN(bestMonthly)) bestMonthly = '---';		else bestMonthly = formatNumberValue(bestMonthly, 2);		var bbMonthly = calcMonthlyMortgagePayment(principal, bbRate, term);		if (bbMonthly <= 0 || isNaN(bbMonthly)) bbMonthly = '---';		else bbMonthly = formatNumberValue(bbMonthly, 2);				var highestMonthly = calcMonthlyMortgagePayment(principal, highestRate, term);		if (highestMonthly <= 0 || isNaN(highestMonthly)) highestMonthly = '---';		else highestMonthly = formatNumberValue(highestMonthly, 2);				ratesTable.rows[10].childNodes[j].innerHTML = bbMonthly;		ratesTable.rows[11].childNodes[j].innerHTML = highestMonthly;		if (bbRate == bestRate) {			var savings = roundToTwoDecimalPlaces((findCommas(highestMonthly) - findCommas(bbMonthly))*rateTerm);			if (savings <= 0 || isNaN(savings)) savings = '';			else savings = formatNumberValue(savings, 2);			ratesTable.rows[12].childNodes[j].innerHTML = savings;					}	}			scrollToAnchor("calcRates");			}/** * Method used to calculate rates on the last minute deals page *  * @param column	column selected for calculation * @param field		field selected */function calcLastMin(column, field){  	var result = '';	var address = 3 + column * 2;	if ($('form-down-payment').value == '') $('form-down-payment').value = 0;		if (!validatePositiveNumber($('form-principal')) || !validatePositiveZeroNumber($('form-down-payment')) ) return false;		if ((findCommas($('form-principal').value)-0) < (findCommas($('form-down-payment').value)-0)) {				alert("Error: Please make sure the purchase price is greater then the down payment.");				focusElement($('principal'));				return false;	}	var principal = (findCommas($('form-principal').value) - 0) - (findCommas($('form-down-payment').value) - 0);	var amort = $('form-amortization');	var term = amort.value;	var ratesTable = $('table-rates');	resetRatesTableFormatting();			// Calculate savings for each special rate	for (i=1; i<ratesTable.rows.length; i++) {		bankRate = ratesTable.rows[i].cells[2].innerHTML -0;		if (bankRate <= 0 || isNaN(bankRate)) {			bankRate = '-';		}								var bankMonthly = calcMonthlyMortgagePayment(principal, bankRate, term);		if (bankMonthly <= 0 || isNaN(bankMonthly) || (bankMonthly > 100000000)) {			bankMonthly = '-';			} else {			bankMonthly = formatNumberValue(bankMonthly);				}				ratesTable.rows[i].cells[4].innerHTML = bankMonthly;				}	scrollToAnchor("calcDeals");	return true;}/** * Method to reset the table formatting on the rates page when selecting another bank */function resetRatesTableFormatting() {	var ratesTable = $('table-rates');	for (i = 1; i < ratesTable.rows.length; i++) {		for (j=0; j < ratesTable.rows[i].childNodes.length; j++) {			if (ratesTable.rows[i].childNodes[j].className == 'rates-bank-selected') 				ratesTable.rows[i].childNodes[j].className = '';			}	}	}function resetRatesTableFormatting_gkl() {	var ratesTable = $('table-rates');	for (i = 1; i < ratesTable.rows.length; i++) {		for (j=0; j < ratesTable.rows[i].childNodes.length; j++) {			if (ratesTable.rows[i].childNodes[j].className == 'rates-bank-selected') 				ratesTable.rows[i].childNodes[j].className = '';			}	}	for (i = 10; i < ratesTable.rows.length; i++) {		for (j=2; j < ratesTable.rows[i].childNodes.length; j++) {			ratesTable.rows[i].childNodes[j].innerHTML = "";		}	}		}/** * Method to calculate monthly mortgage payments * * @param P 	principal of mortgage * @param i 	interest rate * @param n 	term in months * * @return double	monthly mortgage payments in dollars */function calcMonthlyMortgagePayment(P, i, n) {	var M = P*((Math.pow((eval(1+(i/200))),(1/6))-1)/(1-(Math.pow((Math.pow((1+(i/200)),(1/6))),(-12*n)))));	M = roundToTwoDecimalPlaces(M);	return M;}/** * Method to format the number in the current cell * * @param value 	node of cell */function formatCurrentCell(value){    var num = value.value;    num = num+'';    value.value = formatP(num);}/** * Method to format the currency * * @param amount	number to be formatted * @return String	formatted amount */function currencyFormatted(amount) {	var i = parseFloat(amount);	if (isNaN(i)) i = 0.00;		var minus = '';	if(i < 0) { minus = '-'; }	i = Math.abs(i);	i = parseInt((i + .005) * 100);	i = i / 100;	s = new String(i);	if(s.indexOf('.') < 0) { s += '.00'; }	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }	s = minus + s;	return s;}/** * Method to format the number string with commas, dollars signs and decimals * * @param string 	input number string  */function formatP(string) {	var lengthString = string.length;	if (lengthString == 10)		return ("$"+string.charAt(0)+","+string.substring(1,4)+","+string.substring(4,10));		if (lengthString==9)		return ("$"+string.substring(0,3)+","+string.substring(3,9));	if (lengthString==8)		return ("$"+string.substring(0,2)+","+string.substring(2,8));			if (lengthString==7)		return ("$"+string.charAt(0)+","+string.substring(1,7));	if (lengthString<=6)		return("$"+string);}/** * Method to calculate the maximum mortgage and payments based on income * for the payments page *  * @param form	the form in which the calculations is based on  */function calculate(form) {	var income = (findCommas(form.monthlyIncome.value))*12;		var monthlyPayments = form.monthlyPayments.value;	var interest = form.rate.value;		var rdefine = Math.pow(eval(1+(interest/200)),(1/6))-1;		var purchase = Math.pow((1.0+rdefine),480);		var gdsTotal = (0.32*income);		var tdsTotal = (0.35*income);		if (gdsTotal < tdsTotal) {		var payment=gdsTotal/12;		payment = (payment + 0.00) + '';		form.monthlyPayments.value = roundToTwoDecimalPlaces(payment);			} else {		var payment=tdsTotal/12;		payment = (payment + 0.00) + '';				form.monthlyPayments.value = roundToTwoDecimalPlaces(payment);				}				formatNumber(form.monthlyPayments);	var maxMortgage = ((payment*(purchase-1.0))/rdefine)/purchase;	maxMortgage = maxMortgage + '';		form.maxMortgage.value = roundToTwoDecimalPlaces(maxMortgage);	formatNumberNoDec(form.maxMortgage);		return true;}/** * Method to format a percentage * * @param string 	percentage to format * * @return string 	result of formatting */function formati(string) {	return(string + "%");}/** * Method to calculate values for different amortization periods for a given form * * @param form	form to be processed */function amortize(form) {	var Q = form.P.value;	for (j=1; j<=120; j++) {		var H = roundToTwoDecimalPlaces(Q*(Math.pow((1+eval(form.i.value/200)),(1/6))-1));		var C = form.M.value-H;		var R = Q-C;		Q=R;		if (j==12)			form.oneyear.value = formatP(roundToTwoDecimalPlaces(R));					if (j==24)			form.twoyear.value = formatP(roundToTwoDecimalPlaces(R));					if (j==36)			form.threeyear.value = formatP(roundToTwoDecimalPlaces(R));					if (j==60)			form.fiveyear.value = formatP(roundToTwoDecimalPlaces(R));					if (j==120)			form.tenyear.value = formatP(roundToTwoDecimalPlaces(R));				}}/** * Method to check a number to see if it is valid * * @param value  number to check * * @return boolean 	true if valid, false otherwise */function checkNumber(value){	var anum=/(^\d+$)|(^\d+\.\d+$)/		if (anum.test(value))		return true;	else		return false;}/** * Method to set the amortization and check while in the process * * @param temp 	string to check and set */function setAmmortization(temp, check) {	if (!checkNumber(temp) && temp != '' && check) {		alert("Error: Please enter a valid number for your amortization period.");			} else {		document.getElementById('form-amortization').value = temp;	}}/** * Method to verify the rate is a valid number  * * @param temp 		string to check if valid number  *  * @return boolean 	true if valid, false otherwise */function checkRate (temp) {	if (!checkNumber(temp.value)){		alert('Error: Please enter a valid number for a rate');		focusElement(temp);				return false;	}	return true;}/** * Method to preform the calculation of the payments page * * @param form	form to be used in calculation */function sendtoCalc(form){	if (!validatePositiveNumber(form.principal)) return false;			if (form.rateSelected[1].checked) {		if (!validatePositiveNumber(form.inputRate)) return false;				rate = (findCommas(form.inputRate.value) - 0);		} else {		rate = (findCommas(form.rate.options[form.rate.selectedIndex].value) - 0);		}		var P = (findCommas(form.principal.value) - 0);	var i = rate;	var n = (findCommas(form.amortization.options[form.amortization.selectedIndex].value) - 0);		$('monthlyMortgagePayments').innerHTML = currencyFormatted(calcMonthlyMortgagePayment(P,i,n));	return false;}/** * Method to save payment field to persistent session variables for the payments page */function savePaymentFields() {		setSessionVar('principal', $('principal').value);		if ($('principal').form.rateSelected[1].checked) {		setSessionVar('rate', $('principal').form.inputRate);		} else {		setSessionVar('rate', $('principal').form.rate.options[$('principal').form.rate.selectedIndex].value);	}		setSessionVar('amortization', $('amortization').options[$('amortization').selectedIndex].value);		fromCalcFlag(true);	var mortg = document.payment_form.principal.value;		var amortz ;		for(i=0; i < document.payment_form.amortization.length; i++)			{				if(document.payment_form.amortization[i].selected)				 {				 amortz = document.payment_form.amortization[i].value;				 break;				 }			}			location.href = '/rates.php?mort='+mortg+'&amort='+amortz;}function saveLastMinDeals(rate, id) {	setSessionVar('principal', $('form-principal').value);	setSessionVar('down-payment', $('form-down-payment').value);	setSessionVar('amortization', $('form-amortization').value);	setSessionVar('lastmindealid', id);	setSessionVar('rate', rate);	fromCalcFlag(true);		location.href='/application.php';}function sumDebts() {	var debtSum = 0;	$('debtslist').getElementsBySelector('input').each(		function (e) {				if (e.readAttribute('name') == 'debts[]' && e.value != null && checkNumber(findCommas(e.value))) {							debtSum = debtSum + (findCommas(e.value) -0);						}			});			$('monthly-other-debt').value = debtSum;		return true;}function addDebt() {	if ($$('#debtslist > div').length >= 7) return;	debts++;	div = document.createElement("div");		for (i=0; i<document.getElementById('debt').childNodes.length; i++) {		node = document.getElementById('debt').childNodes[i].cloneNode(false);		div.appendChild(node);						}	document.getElementById('debtslist').appendChild(div);		//clear values	$(div).getElementsBySelector("input").each(function(e) { e.value = ''; });				}function monthlyPropTax(form) {	if (validateNumber(form.pTaxAnnual)) {		form.pTax.value = Math.round((findCommas(form.pTaxAnnual.value)*100)/12, 2)/100;				formatNumber(form.pTax);				return true;	}		return false;}function yearlyPropTax(node) {	form = node.form;		if (validateNumber(form.pTax)) {		form.pTaxAnnual.value = Math.round((findCommas(form.pTax.value)*100)*12, 2)/100;				formatNumber(form.pTaxAnnual);				return true;	}		return false;}function sumUp(form) {		var income;		var appIncome = (findCommas(form.appIncome.value)-0);	var coAppIncome = (findCommas(form.coAppIncome.value)-0);		var go = true;    	if (!validatePositiveZeroNumber(form.appIncome) || !validatePositiveZeroNumber(form.coAppIncome) || !validatePositiveZeroNumber(form.loanPayment) ||   		!validatePositiveZeroNumber(form.monthlyCreditCardPayment) || !validatePositiveZeroNumber($('monthly-other-debt')) ||  		!validatePositiveZeroNumber(form.monthlyPayment) || !validatePositiveZeroNumber(form.otherDebt) || !validatePositiveZeroNumber(form.pTax) ||  		!validatePositiveZeroNumber(form.heatCost) || !validatePositiveZeroNumber(form.condoFees) ) return false;  	  	if(!checkNumber(appIncome)) {		form.appIncome.value = 0;		go = false;	}		if(!checkNumber(coAppIncome)) {		form.coAppIncome.value = 0;		go = false;	}		if(go){		income = appIncome + coAppIncome;		income = income+'';	} else {		income = 0;	}	document.getElementById('totalIncome').innerHTML =  formatNumberValue(income, 2);	income = income * 12;	document.getElementById('totalAnnualIncome').innerHTML =   formatNumberValue(income, 2);		var debt;	var loanPayment = (findCommas(form.loanPayment.value)-0);	var monthlyPayment = (findCommas(form.monthlyPayment.value)-0);	var monthlyCreditCardPayment = (findCommas(form.monthlyCreditCardPayment.value)-0);	var otherDebt = (findCommas($('monthly-other-debt').value)-0);	go = true;	if(!checkNumber(loanPayment)) {		form.loanPayment.value = 0;		go = false;	}			if(!checkNumber(monthlyPayment)) {		form.monthlyPayment.value = 0;		go = false;	}		if(!checkNumber(monthlyCreditCardPayment)) {		form.monthlyCreditCardPayment.value = 0;		go = false;	}		if(!checkNumber(otherDebt)) {		form.otherDebt.value = 0;		go = false;	}				if(go){		debt = loanPayment + monthlyPayment + monthlyCreditCardPayment + otherDebt;		document.getElementById('totalPayments').innerHTML =   formatNumberValue(debt, 2);		document.getElementById('totalMonthlyDebt').innerHTML =   formatNumberValue(debt, 2);			} else {		document.getElementById('totalMonthlyDebt').innerHTML =   0;	}					var utils;	var pTax = (findCommas(form.pTax.value) - 0);	var heatCost = (findCommas(form.heatCost.value) - 0);	var condoFees = (findCommas(form.condoFees.value) - 0);	go = true;			if(!checkNumber(pTax)) {		form.pTax.value = 0;		go = false;	}			if(!checkNumber(heatCost)) {		form.heatCost.value = 0;		go = false;	}		if(!checkNumber(condoFees)) {		form.condoFees.value = 0;		go = false;	}		if(go){		utils = pTax + heatCost + condoFees;		document.getElementById('totalExpenses').innerHTML =  formatNumberValue(utils, 2);	} else {		document.getElementById('totalExpenses').innerHTML =   0.00;	}	return true;    //form.totalExpenses.value = utils;  }function calcMaxMgt(form) {	var income = (findCommas($('totalIncome').innerHTML))*12;	if (!income || income <= 0) {		alert('Error: Please make sure your total income is greater than zero.');				focusElement($('applicant-income'));						return false;	}	var expenses = (findCommas($('totalExpenses').innerHTML))*12; 	var loanOne = (findCommas($('totalPayments').innerHTML))*12;        var interest = 5.15;	var gds = 0.32;	var tds = 0.40;	var rdefine = Math.pow(1.0+((interest)/200),(2/12))-1.0;	var purchase = Math.pow((1.0+rdefine),300);	var gdsTotal = (gds*income)-expenses;	var tdsTotal = (tds*income)-expenses-loanOne;	if (gdsTotal < tdsTotal) {		var payment=gdsTotal/12;	} else {		if (tdsTotal < 0) {			alert("Sorry, your income is too low to qualify for a mortgage.");			focusElement($('applicant-income'));			return false;		}		var payment=tdsTotal/12;	}			var maxMortgage = (0 + ((payment*(purchase-1.0))/rdefine))/purchase;	if (maxMortgage < 0) {		alert('Error: Please check to make sure that your debts and payments are not greater then your income.');		$('maxprincipal').innerHTML = 0;				focusElement(form.loanPayment);				return false;	} else {		$('maxprincipal').innerHTML = formatNumberValue(maxMortgage, 0);	}		var downpayment = findCommas(form.downPayment.value);	var p = maxMortgage - downpayment;		if (downpayment >= maxMortgage) {		alert('Error: Please check to make sure that your down payment is less than the maximum mortgage.');		focusElement(form.downPayment);			return false;		}		var ans = calcMonthlyMortgagePayment(p,interest,25);		if (ans < 0) {		alert('Error: Please check to make sure that your debts and payments are not greater then your income.');		$('monthlyMortgagePayments').innerHTML =  0;		$('weeklyMortgagePayments').innerHTML = 0;		$('biWeeklyMortgagePayments').innerHTML = 0;				focusElement(form.loanPayment);				return false;	} else {			$('monthlyMortgagePayments').innerHTML =  formatNumberValue(ans, 2);		$('weeklyMortgagePayments').innerHTML = formatNumberValue(ans/4, 2);		$('biWeeklyMortgagePayments').innerHTML = formatNumberValue(ans/2, 2);		}		scrollToAnchor("calcMortgage");		return true;	}function saveCalculatorFields() {	setSessionVar('credit-card-name', $('credit-card-name').value);	setSessionVar('car-name', $('car-name').value);	setSessionVar('loan-name', $('loanName').value);		setSessionVar('monthly-credit-card', findCommas($('monthly-credit-card').value));	setSessionVar('monthly-car', findCommas($('monthly-car').value));	setSessionVar('monthly-loan', findCommas($('monthly-loan').value));		setSessionVar('monthly-credit-card-balance', findCommas($('monthly-credit-card-balance').value));	setSessionVar('monthly-car-balance', findCommas($('monthly-car-balance').value));	setSessionVar('monthly-loan-balance', findCommas($('monthly-loan-balance').value));		setSessionVar('monthly-other-debt', findCommas($('monthly-other-debt').value));	setSessionVar('principal', findCommas($('maxprincipal').innerHTML));	setSessionVar('property-taxes', findCommas($('property-taxes').value));	setSessionVar('applicant-income', findCommas($('applicant-income').value));	setSessionVar('co-applicant-income', findCommas($('co-applicant-income').value));		$('calculator-form').request({asynchronous: 'false'});		fromCalcFlag(true);		location.href = '/application.php';}var scrollInt;var scrTime, scrSt, scrDist, scrDur, scrInt;	function scrollPage() {	scrTime += scrInt;	if (scrTime < scrDur) {		window.scrollTo( 0, easeInOut(scrTime,scrSt,scrDist,scrDur) );	}else{		window.scrollTo( 0, scrSt+scrDist );		clearInterval(scrollInt);	}}	function scrollToAnchor(aname) {	var anchors, i, ele;	if (!document.getElementById)		return;		// get anchor	anchors = document.getElementsByTagName("a");	for (i=0;i<anchors.length;i++) {		if (anchors[i].name == aname) {			ele = anchors[i];			i = anchors.length;		}	}		// set scroll target	if (window.scrollY)		scrSt = window.scrollY;	else if (document.documentElement.scrollTop)		scrSt = document.documentElement.scrollTop;	else		scrSt = document.body.scrollTop;			scrDist = ele.offsetTop - scrSt;	scrDur = 500;	scrTime = 0;	scrInt = 10;		// set interval	clearInterval(scrollInt);	scrollInt = setInterval( scrollPage, scrInt );}		function easeInOut(t,b,c,d) {	return c/2 * (1 - Math.cos(Math.PI*t/d)) + b;}function loadValueIntoApp() {	applicantIncome = getSessionVar('applicant-income');	if (applicantIncome && (applicantIncome - 0) > 0) {		 $('yearlyIncome').value = (applicantIncome - 0) * 12;		 formatNumber($('yearlyIncome'));		// saveField($('yearlyIncome'));	}	coApplicantIncome = getSessionVar('co-applicant-income');	if (coApplicantIncome && (coApplicantIncome - 0) > 0) {		$('coYearlyIncome').value = (coApplicantIncome - 0) * 12;		formatNumber($('coYearlyIncome'));		//saveField($('coYearlyIncome'));	}				monthlyCreditCard = getSessionVar('credit-card-name');	if (monthlyCreditCard )  {		$('debt1_name').value = monthlyCreditCard ;					}	monthlyCar = getSessionVar('car-name');	if (monthlyCar) {		$('debt2_name').value = monthlyCar ;				//saveField($('debt1_amount'));	}		monthlyLoan = getSessionVar('loan-name');	if (monthlyLoan ) {		$('debt3_name').value = monthlyLoan ;				//saveField($('loans'));	}	monthlyOther = getSessionVar('monthly-other');	if (monthlyOther ) {		$('debt4_name').value = monthlyOther ;				//saveField($('otherPayments'));	}		monthlyCreditCard = getSessionVar('monthly-credit-card');	if (monthlyCreditCard && (monthlyCreditCard - 0) > 0) {		$('debt1_amount').value = monthlyCreditCard - 0;		formatNumber($('debt1_amount'));			}	monthlyCar = getSessionVar('monthly-car');	if (monthlyCar && (monthlyCar - 0) > 0) {		$('debt2_amount').value = monthlyCar - 0;		formatNumber($('debt2_amount'));		//saveField($('debt1_amount'));	}		monthlyLoan = getSessionVar('monthly-loan');	if (monthlyLoan && (monthlyLoan - 0) > 0) {		$('debt3_amount').value = monthlyLoan - 0;		formatNumber($('debt3_amount'));		//saveField($('loans'));	}	monthlyOther = getSessionVar('monthly-other');	if (monthlyOther && (monthlyOther - 0) > 0) {		$('debt4_amount').value = monthlyOther - 0;		formatNumber($('debt4_amount'));		//saveField($('otherPayments'));	}		monthlyCreditCard = getSessionVar('monthly-credit-card-balance');	if (monthlyCreditCard && (monthlyCreditCard - 0) > 0) {		$('debt1_monthly').value = monthlyCreditCard - 0;		formatNumber($('debt1_monthly'));			}	monthlyCar = getSessionVar('monthly-car-balance');	if (monthlyCar && (monthlyCar - 0) > 0) {		$('debt2_monthly').value = monthlyCar - 0;		formatNumber($('debt2_monthly'));		//saveField($('debt1_amount'));	}		monthlyLoan = getSessionVar('monthly-loan-balance');	if (monthlyLoan && (monthlyLoan - 0) > 0) {		$('debt3_monthly').value = monthlyLoan - 0;		formatNumber($('debt3_monthly'));		//saveField($('loans'));	}			loadotherfield();		principal = getSessionVar('principal');	if (principal && (principal - 0) > 0) {		$('neededPrincipal').value = principal - 0;		formatNumber($('neededPrincipal'));		//saveField($('neededPrincipal'));				$('require-current-home-purchase-price').value = principal-0;		formatNumber($('require-current-home-purchase-price'));		//saveField($('require-current-home-purchase-price'));	}		propertyTaxes = getSessionVar('property-taxes');	if (propertyTaxes && (propertyTaxes - 0) > 0) {		$('yearlyTaxes').value = propertyTaxes - 0;		formatNumber($('yearlyTaxes'));		//saveField($('yearlyTaxes'));	}		rateID = getSessionVar('rate-id') - 0;	if (rateID > 0) {		rateTerm = $('desiredTerms');				for (i=0; i<rateTerm.options.length; i++) {			if (rateTerm.options[i].value == rateID) {				rateTerm.selectedIndex = i;				break;						}		}				//saveField($('desiredTerms'));	}		amort = getSessionVar('amortization') - 0;	if (amort > 0) {		string = amort;		rateTerm = $('amortizationYears');				for (i=0; i<rateTerm.options.length; i++) {			if (rateTerm.options[i].value == string) {				rateTerm.selectedIndex = i;				break;						}		}				//saveField($('amortizationYears'));	}		}function getSessionValue(name) {		req = getAjaxObject();	req.open("GET", "/getsession.php?method=get&name="+urlencode(name), false);	req.send(null);		if (req.readyState == 4) {				if (req.responseText) {			if (req.responseText == ' ') {				return "";			} else {				return req.responseText.strip().strip();			}		} else {			return null;		}			} else {		return null;	}}//Agency preappfunction checkAgencyPreApp() {	// Validate agreement for the terms & conditions	if (!document.getElementById("agree").checked) {		alert("You must agree to the terms and conditions to continuewww.");		focusElement($("agree"));		return false;	}		/*if(document.getElementById("beacon_score").value == '')   {		   alert("Error: Please make sure the Beacon score field is filled out");		   focusElement($("beacon_score"));		   return false;	 }	if(document.getElementById("gds_tds").value == '')   {		   alert("Error: Please make sure the GDS/TDS field is filled out");		   focusElement($("gds_tds"));		   return false;	}	*/		inputs = document.getElementsByTagName("input");		// Check every field in the application	for(i=0; i<inputs.length; i++) {	if(inputs[i].id == 'require-sin')	{		continue;	}			if (inputs[i].id.substr(0, 8) == 'require-') {			a = inputs[i].value;						check = Trim(a);						if (check == '') {												// Validate text fields on Page One				w = document.getElementById("application").getElementsByTagName("input");								for(j=0; j<w.length; j++) {					if (w[j].name == inputs[i].name) {						alert("Error: Please make sure the " + inputs[i].id.substr(8).replace(/-/g, ' ') + " field is filled out.");						focusElementApp(inputs[i]);																		return false;					}				}								return false;								}				}	}		//selct type require fields		if (document.getElementById("require-first-name")!='') {		check = document.getElementById("require-first-name").value;		if (!check.match(/^[a-zA-Z]{1,}[\sa-zA-Z]{0,}$/)) {			alert("Error: Please make sure you do not have numbers or special charaters in your first name.");			//focusElement(node);			focusElementApp($("require-first-name"));			return false;		}	}		if (document.getElementById("require-last-name")!='') {		check = document.getElementById("require-last-name").value;		if (!check.match(/^[a-zA-Z]{1,}[\sa-zA-Z]{0,}$/)) {			alert("Error: Please make sure you do not have numbers or special charaters in your last name.");			//focusElement(node);			focusElementApp($("require-last-name"));			return false;		}	}			if (document.getElementById("require-current-employer")!='') {		check = document.getElementById("require-current-employer").value;		if (!check.match(/^[a-zA-Z]{1,}[\sa-zA-Z]{0,}$/)) {			alert("Error: Please make sure you do not have numbers or special charaters in your current employer name.");			//focusElement(node);			focusElementApp($("require-current-employer"));			return false;		}	}		if(document.getElementById("require-mortgage-status").value == ''){		alert("Error: Please make sure you have selected Mortgage type.");		focusElementApp($("require-mortgage-status"));		return false;	}		if(document.getElementById("require-mortgage-type").value == ''){		alert("Error: Please make sure you have selected Referred from.");		focusElementApp($("require-mortgage-type"));		return false;	}		if(document.getElementById("require-currentProvince").value == ''){		alert("Error: Please make sure you have selected Province.");		focusElementApp($("require-currentProvince"));		return false;	}	if(document.getElementById("require-employerYears").value == ''){		alert("Error: Please make sure you have selected Length of employment.");		focusElementApp($("require-employerYears"));		return false;	}		// Validate SIN	if(document.getElementById("require-sin").value != '')	{	if (!checkSIN(document.getElementById("require-sin").value)) {		alert("Error: Please make sure you have entered your SIN number correctly.");		focusElementApp($("require-sin"));		//switchPage(1);		return false;	}	}	// Validate home phone number	if (!checkPhone(document.getElementById("require-home-phone").value)) {		alert("Error: Please make sure you have entered your home phone number correctly.");		focusElementApp($("require-home-phone"));		//switchPage(1);		return false;	}			// Validate yearly income	if (document.getElementById("yearlyIncome").value == '') {		alert("Error: Please make sure the yearly income field is filled out.");		focusElementApp($("yearlyIncome"));		//switchPage(1);		return false;	}				return true;}function Trim(str){  return RTrim(LTrim(str));}function RTrim(str){  // We don't want to trip JUST spaces, but also tabs,  // line feeds, etc.  Add anything else you want to  // "trim" here in Whitespace  var whitespace = new String(" \t\n\r");  var s = new String(str);  if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {    // We have a string with trailing blank(s)...    var i = s.length - 1;       // Get length of string    // Iterate from the far right of string until we    // don't have any more whitespace...    while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)      i--;    // Get the substring from the front of the string to    // where the last non-whitespace character is...    s = s.substring(0, i+1);  }  return s;}function LTrim(str){  var whitespace = new String(" \t\n\r");  var s = new String(str);  if (whitespace.indexOf(s.charAt(0)) != -1) {    // We have a string with leading blank(s)...    var j=0, i = s.length;    // Iterate from the far left of string until we    // don't have any more whitespace...    while (j < i && whitespace.indexOf(s.charAt(j)) != -1)    j++;    // Get the substring from the first non-whitespace    // character to the end of the string...    s = s.substring(j, i);  }  return s;}
