window.onload = preparePage;

function preparePage() {
	browserType();
	var bal = document.getElementById('balance');
	var pay = document.getElementById('payment');
	var app = document.getElementById('apprec');
	var int = document.getElementById('interest');
	if (bal != null && pay != null && app != null) { // We got all the form fields
		if (browser == 1) { // This is not IE
			bal.addEventListener("change", checkBal, false);
			pay.addEventListener("change", checkPay, false);
			app.addEventListener("change", checkApp, false);
			int.addEventListener("change", checkInt, false);
		} else if (browser == 2) { // This is IE
			bal.attachEvent("onchange", checkBal);
			pay.attachEvent("onchange", checkPay);
			app.attachEvent("onchange", checkApp);
			int.attachEvent("onchange", checkInt);
		} else { // This is some very old browser
			bal.onchange = checkBal;
			pay.onchange = checkPay;
			app.onchange = checkApp;
			int.onchange = checkInt;
		}
	}
}

/* NOT NEEDED 
function hideErrors() {
	var errs = getElementsByClassName('span', 'errmes');
	for (i = 0; i < errs.length; i++)
		errs[i].style.display = "none"; // Hide any error messages that may be open right now
	document.getElementById('calcerr').style.display = "none";
}*/

function checkBal() {
	document.getElementById('balinc').style.display = "none";
	document.getElementById('balinv').style.display = "none";
	var bal = document.getElementById('balance');
	var actval = document.getElementById('actval');
	var years = document.getElementById('years');
	var cost = document.getElementById('cost');
	var contain = document.getElementById('contain');
	if (bal.value.length < 1 || /^\$?((\d+)|([1-9]+[0-9]{0,2}(,[0-9]{3})*))(\.[0-9]{2})?$/.test(bal.value) == false) { // The balance field is incomplete or invalid
		clbal = null;
		actval.style.display = "none"; // Hide the asset value output until this is fixed
		years.style.display = "none"; // Hide the asset equalization display
		cost.style.display = "none"; // Hide the total cost display
		if (bal.value.length < 1) // The balance was not entered
			document.getElementById('balinc').style.display = "inline"; // Show error
		else // The balance is invalid
			document.getElementById('balinv').style.display = "inline"; // Show error
	} else { // The balance field is good
		clbal = parseFloat((bal.value.substr(0,1) == '$' ? bal.value.substr(1) : bal.value).replace(',', '')); // Get rid of a possible dollar sign and store the remaining balance gloablly
		bal.value = clbal;
		actval.innerHTML = ((est-clbal) >= 0 ? 'Current Asset Value = ' : 'Current Liability = ')+'<span>$'+((commaFormatted(Math.abs(Math.floor(est-clbal)))))+'</span>'; // Set the Actual value of the house for the homeowner, estimated value - amount owed (could be negative)
		actval.style.display = "block";
		if (est-clbal >= 0) { // This person is not underwater, no need to display the years and cost
			if (est-clbal == 0) {
				years.innerHTML = 'Not bad! You\'re breaking even.';
				contain.className = "";
			} else {
				years.innerHTML = 'Congratulations! Your property is already an asset for you.';
				contain.className = "posvalue";
			}
			years.style.display = "block";
			cost.style.display = "none"; // Hide the total cost display
		} else {
			contain.className = "negvalue";
			years.style.display = "none";
			cost.style.display = "none";
		}
		if (clint && clpay && clapp) // We know the monthly payment and annual appreciation	
			calcTotals(); // Calculate the year of asset equalization and cost
	}
}

function checkPay() {
	document.getElementById('payinc').style.display = "none";
	document.getElementById('payinv').style.display = "none";
	var pay = document.getElementById('payment');
	if (pay.value.length < 1 || /^\$?((\d+)|([1-9]+[0-9]{0,2}(,[0-9]{3})*))(\.[0-9]{2})?$/.test(pay.value) == false) { // The payment field is incomplete or invalid
		clpay = null;
		if (pay.value.length < 1) // The balance was not entered
			document.getElementById('payinc').style.display = "inline"; // Show error
		else // The balance is invalid
			document.getElementById('payinv').style.display = "inline"; // Show error
		document.getElementById('actval').style.display = "none"; // Hide the asset value output until this is fixed
		document.getElementById('years').style.display = "none"; // Hide the asset equalization display
		document.getElementById('cost').style.display = "none"; // Hide the total cost display
	} else { // The monthly payment field is good
		clpay = parseFloat(pay.value.substr(0,1) == '$' ? pay.value.substr(1) : pay.value); // Get rid of a possible dollar sign and store the monthly payment gloablly
		pay.value = clpay;
		if (clbal && clint && clapp && est && (est-clbal) < 0) // We know the balance and annual appreciation and the user is underwater
			calcTotals(); // Calculate the year of asset equalization and cost
	}
}

function checkApp() {
	var app = null;
	var selbox = document.getElementById('apprec'); // Get the appreciation select box from the form
	if (selbox != null) { // We got it
		for (var i = 0; i < selbox.options.length; i++) { // Go through all the options in the select box
			if (selbox.options[i].selected == true) // We found the one that is selected
				app = parseInt(selbox.options[i].value);
		}
	}
	if (app < 5 || app > 12) { // The appreciation rate field is incomplete or invalid
		clbal = null;
		clpay = null;
		return;
	} else { // The appreciation rate field is good is good
		clapp = parseFloat(app/100);
		if (clbal && clint && clpay && est && (est-clbal) < 0) // We know the balance and annual appreciation
			calcTotals(); // Calculate the year of asset equalization and cost
	}
}

function checkInt() {
	var int = null;
	var selbox = document.getElementById('interest'); // Get the interest select box from the form
	if (selbox != null) { // We got it
		for (var i = 0; i < selbox.options.length; i++) { // Go through all the options in the select box
			if (selbox.options[i].selected == true) // We found the one that is selected
				int = parseFloat(selbox.options[i].text.substr(0,selbox.options[i].text.length-1));
		}
	}
	if (int < 3.0 || int > 12) { // The appreciation rate field is incomplete or invalid
		clbal = null;
		clpay = null;
		return;
	} else { // The interest rate field is good
		clint = parseFloat(int/100);
		if (clbal && clpay && clapp && est && (est-clbal) < 0) // We know the balance and annual appreciation
			calcTotals(); // Calculate the year of asset equalization and cost
	}
}

function calcTotals() {
	if (clbal && clint && clpay && clapp && est) { // We have all the vars we need to do some math
		var sform = document.getElementById('sform');
		sform.style.display = "block";
		var years = document.getElementById('years');
		var cost = document.getElementById('cost');
		if (years != null && cost != null) {
			var amor = 360; // Assume a standard 30 year mortgage 
			var perint = Math.pow(1+(Math.pow(1+clint/12,12)-1), 1/12)-1; // Get the periodic interest rate assuming 12 periods a year
			var perapp = Math.pow(1+(Math.pow(1+clapp/1,1)-1), 1/12)-1; // Get the periodic rate of appreciation assuming 12 periods a year (how much house gains value every month)
			var origprin = (clpay*(1-(1/Math.pow(1+perint,amor))))/perint; // Get the original principal amount
			var remterm = Math.log((clbal/origprin)*(Math.pow(1+perint, amor)-1)+1)/Math.log(1+perint); // Return the exlipsed term given the original principal, remaining principal, periodic rate, and amortization term
			zeroyear = payoff(clbal, clpay, perint, est, perapp, remterm);
			// zeroyear = (clbal - est)/((est*clapp)+(clpay*12));
			if (zeroyear >= 0) {
				years.innerHTML = (est-clbal) > 0 ? 'Years Until Breakeven = 0' : 'Years Until Breakeven = <span>'+Math.floor(zeroyear/12)+' year(s), '+Math.ceil(zeroyear%12)+' month(s)</span>';
				cost.innerHTML = (est-clbal) > 0 ? 'Cost to Breakeven = 0' : 'Cost to Breakeven = <span>$'+commaFormatted((zeroyear*clpay).toFixed(0))+'</span>';
				years.style.display = "block";
				cost.style.display = "block"
			}
		}
	}
}

function payoff(remprin, monthlypay, perint, housevalue, perapp, remterm) {
	var breakeven = 0; // Months until principal = housevalue
	for (var i = 1; i < remterm && housevalue < remprin; i++) {
		remprin -= monthlypay-(remprin*perint); // You have to pay the periodic interest on the principle every month
		housevalue += housevalue*perapp;
		breakeven++;
	}
	return breakeven;
}

function commaFormatted(amount) { // From http://www.web-source.net/web_development/currency_formatting.htm
	amount = ""+amount;
	var delimiter = ","; // replace comma if desired
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i))
		return '';
	var minus = '';
	if(i < 0)
		minus = '-';
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3) {
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0)
		a.unshift(n);
	n = a.join(delimiter);
	if(!d || d.length < 1)
		amount = n;
	else
		amount = n + '.' + d;
	amount = minus + amount;
	return amount;
}
