/* Simple Calculator Javascript */

// simple mortage calculator
function simplecalc(objForm) {

	// get form values
	var nPurchaseprice = objForm.simpcalc_price.value;
	var nDownpayment = objForm.simpcalc_downpay.value;
	var nInterest = objForm.simpcalc_interest.value;
	var nPayments = objForm.simpcalc_loanterm.value;
	
	// check for valid data entries
	if (!checkNumber(nPurchaseprice, 1, 9999999999, "Purchase Price") ) return false;
	if (!checkNumber(nDownpayment, 1, 9999999999, "Down Payment") ) return false;
	if (!checkNumber(nInterest, 1, 9999999999, "Interest Rate") ) return false;
	if (!checkNumber(nPayments, 1, 50, "Loan Term") ) return false;
	if (parseInt(nDownpayment) > parseInt(nPurchaseprice)) {
		alert ("Downpayment ($ "+nDownpayment+") cannot be larger the Purchase Price ($ "+nPurchaseprice+")");
		return false;
	}
	
	// calculate mortage
	nInterest = nInterest / 100 / 12;
	nPayments = nPayments * 12;
	var nPrincipal = nPurchaseprice - nDownpayment;
	var x = Math.pow(1 + nInterest, nPayments);
	var nMonthly = (nPrincipal * x * nInterest) / (x - 1);
	
	// set form value
	if (
		!isNaN(nMonthly) &&
		(nMonthly != Number.POSITIVE_INFINITY) &&
		(nMonthly != Number.NEGATIVE_INFINITY)
	) objForm.simpcalc_payment.value = round(nMonthly);
	else objForm.simpcalc_payment.value = "Error!";	
}

// round to two decimals places
function round (x) {
	return Math.round(x*100)/100;
}

// check data for valid number string between limits
function checkNumber(str, min, max, msg) {
	msg = msg + " field has invalid input: " + str;
	for (var z = 0; z < str.length; z++) {
		var ch = str.substring(z, z + 1)
		if ((ch < "0" || "9" < ch) && ch != '.') {
			alert(msg);
			return false;
		}
	}
	var num = 0 + str;
	if (num < min || max < num) {
		alert(msg + " not in range [" + min + ".." + max + "]");
		return false;
	}
	return true;
}

