function floor(number) {
  return Math.floor(number*Math.pow(10,2))/Math.pow(10,2);
}

function dosum(field) {
	if (typeof(customInsuranceRate) == "number") {
		var insuranceRate = customInsuranceRate / 100;
	} else {
		var insuranceRate = 0.003;
	}
	// home price (list price)
	var hp = parseInt(replaceChars(',','',$('mortgage_calculator').getElement('#LP').value));
	// down payment
	var dp = parseInt(replaceChars(',','',$('mortgage_calculator').getElement('#DP').value));
	if (field == 'LP' || field == 'DP') {
		// loan amount (display)
		$('mortgage_calculator').getElement('#LA').value = hp-dp;
		var la = la = parseInt(replaceChars('$','',replaceChars(',','',$('mortgage_calculator').getElement('#LA').value)));
		var la = replaceChars(',','',$('mortgage_calculator').getElement('#LA').value);
		la = parseInt(replaceChars('$','',la));
	} else if (field == 'LA') {
		// loan amount
		var la = la = parseInt(replaceChars('$','',replaceChars(',','',$('mortgage_calculator').getElement('#LA').value)));
		$('mortgage_calculator').getElement('#DP').value = hp-la;
	} else {
		var la = la = parseInt(replaceChars('$','',replaceChars(',','',$('mortgage_calculator').getElement('#LA').value)));
	}
	if (dp > hp) {
		dp = hp;
		la = 0;
		$('mortgage_calculator').getElement('#DP').value = dp;
		$('mortgage_calculator').getElement('#LA').value = la;
	}
	if (la > hp) {
		la = hp;
		dp = 0;
		$('mortgage_calculator').getElement('#DP').value = dp;
		$('mortgage_calculator').getElement('#LA').value = la;
	}
	// interest rate
	var mi = replaceChars('%','',$('mortgage_calculator').getElement('#IR').value) / 1200;
	// property taxes
	var at = replaceChars(',','',$('mortgage_calculator').getElement('#AT').value);
	at = replaceChars('$','',at);
	// Insurance
	if (field == '') {
		var ai = replaceChars(',','',$('mortgage_calculator').getElement('#AI').value);
		ai = replaceChars('$','',ai);
	} else {
		var ai = hp * insuranceRate;
		$('mortgage_calculator').getElement('#AI').value = ai;
	}
	var base = 1;
	var mbase = 1 + mi;
	for (i=0; i<$('mortgage_calculator').getElement('#YR').value * 12; i++) {
		base = base * mbase
	}
	var pi = floor(la * mi / ( 1 - (1/base)));
	if (pi == NaN) {
		pi = 0;
	}
	$('mortgage_calculator').getElement('#PI').value = pi;
	$('mortgage_calculator').getElement('#MT').value = floor(at / 12);
	$('mortgage_calculator').getElement('#MI').value = floor(ai / 12);
	var dasum = pi + at / 12 +  ai / 12;
	$('mortgage_calculator').getElement('#MP').value = floor(dasum);
}

function replaceChars(char_find,char_replace_with,entry) {
	temp = "" + entry; // temporary holder
	while (temp.indexOf(char_find)>-1) {
		pos= temp.indexOf(char_find);
		temp = "" + (temp.substring(0, pos) + char_replace_with + 
		temp.substring((pos + char_find.length), temp.length));
	}
	return temp;
}
