function chkNumber(input, min, max, fieldName, mayBeBlank) {
	msg = 'The ' + fieldName + ' field';
	if (input.value == null || input.value.length == 0) {
		if (mayBeBlank == "yes") {
			return true;
		}
		alert(msg + ' must be filled in!');
		input.focus();
		input.select();
		return false;
	}
	var str = input.value;
	for (var i = 0; i < str.length; i++) {
		var ch = str.substring(i, i + 1);
		if ((ch < "0" || "9" < ch) && ch != '.') {
			if (ch != '%' || i != str.length-1) {
				alert(msg + ' has a non-numeric character');
				input.focus();
				input.select();
				return false;
			}
		}
	}
	var num = parseFloat(str);
	if (num < min || max < num) {
		alert(msg + ' must be between [' + min + ".." + max + "]");
		input.focus();
		input.select();
		return false;
	}
	return true;
}

function round(value, places) {
	var multi, chars;
	chars = (places == 0 ? 0 : places + 1);
	var str = "" + value;
	for (var i = 0; (str.substring(i, i + 1) != "." && i < str.length); ++i) {
	}
	if (str.length == 0) {
		return str;
	}
	str = str + (i < str.length ? "00000000" : ".00000000");
	if (i < 4) {
		return(str.substring(0, i + chars));
	}
	var retstr = "";
	for (j = 0; j < i; ++j) {
		if (j != 0 && (i-j) % 3 == 0) {
			retstr = retstr + ",";
		}
		retstr = retstr + str.substring(j, j + 1);
	}
	retstr = retstr + str.substring(i, i + chars);
	return retstr;
}

function calculateLoan(pmt, rate, months) {
	if (rate <= 0) {
		return "0.00";
	}
	rate /= 1200.0;
	var power = 1.0;
	for (var i=0; ++i <= months; power *= (1 + rate)) {
	}
	return pmt / (rate / (1 - (1 / power)));
}

function computeForm(form,name) {
	if (!chkNumber(form.income, 100, 999999999, "Before Tax Income", "no") ||
		!chkNumber(form.rate, 0.01, 19.99, "Mortgage Rate", "no") ||
		!chkNumber(form.years, 1, 50, "# of Years", "no") ||
		!chkNumber(form.downpymt, 0, 999999, "Down Payment", "yes")) {
		return;
	}
	if (form.rate.value < 1.0) {
		form.rate.value = form.rate.value * 100;
	}
	var months   = form.years.value * 12;
	var monthpay = form.income.value;
	var downpay  = form.downpymt.value == null || form.downpymt.value.length == 0 ? 0 : form.downpymt.value;
	if (monthpay >= 10000) {
		monthpay /= 12.0;
	}
	monthpay *= 0.28;
	var loanamt = calculateLoan(monthpay, form.rate.value, months);
	var docmessage;
	docmessage = "With your income, you can afford a monthly payment of <strong>$" + round(monthpay, 2) + "</strong>.<br /><br />";
	docmessage = docmessage + "This translates to a " +  form.years.value + "-year, " + form.rate.value + "% mortgage of <strong>$" + round(loanamt, 2) + "</strong>.<br /><br />";
	docmessage = docmessage + "You can therefore buy a house of up to <strong>$" + round(loanamt - -downpay, 2) + "</strong>.";
	result.innerHTML = docmessage;
}