
// by Scott Johnson (scott@ishopper.com)

var i;

var pow;

var l;   



function computePopups(input) {

	computeForm(input.form);

}

function computeInterest() {

	if (document.calc.interest.value == null) {

		return false;

	}

	i = parseFloat(document.calc.interest.value);

	if (!checkNumber(document.calc.interest, .01, 99, "Interest")) {

	return false;

	}

	if (i > 1.0) {

		 i = i / 100.0;

	}

	i /= 12;

	pow = 1;

	for (var j = 0; j < parseInt(document.calc.payments.options[document.calc.payments.selectedIndex].value); j++) {

		pow = pow * (1 + i);

	}

return true;

}



function computePrincipal() {

	if (computeInterest()) {

		checkNumber(document.calc.payment, 25, 10000, "Payment")

		document.calc.principal.value = parseInt(document.calc.payment.value * ((1 - (1 / pow)) / i))

		l = "princ"

		computeTotInterest()

	}

}

function computeTotInterest() {

if (computeInterest()) {

	document.calc.totinterest.value = parseInt((document.calc.payment.value * parseInt(document.calc.payments.options[document.calc.payments.selectedIndex].value)) - document.calc.principal.value)

	}

}

function computePayment() {

	if (computeInterest()) {

		checkNumber(document.calc.principal, 500, 100000, "Principal")

		document.calc.payment.value = parseInt(document.calc.principal.value / ((1 - (1 /pow)) / i))

		l = "pay"

		computeTotInterest()

	}

}



function computeForm() {

	if ((document.calc.principal.value == null || document.calc.principal.value.length == 0) && (document.calc.payment.value == null || document.calc.payment.value.length == 0)) {

		return;



	}

if (l != null) {

	if (l == "princ") {

		computePrincipal()

		return;

	} else {

	computePayment()

	return;

	}

} else {

	if (document.calc.principal.value.length == 0) {

		computePrincipal()

	} else {

		computePayment()

	}

}	

computeTotInterest()

}

function clearForm() {

        document.calc.payments.value = "";

        document.calc.interest.selectedIndex = "0";

        document.calc.principal.value = "";

}

function checkNumber(input, min, max, msg) {

	msg = msg + " field has invalid data: " + input.value;

	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 != '.') {

			alert(msg);

			return false;

		}

	}

	var num = 0 + str

	if (num < min || max < num) {

		alert(msg + " not in range [" + min + ".." + max + "]");

		return false;

	}

	input.value = str;

	return true;

}

// -->