//Contains repayment calculation using the standard p = ((A*R)/12) * (1/(1-(Math.pow(1/(1+R),T)))) ****
// ** 
// ** 
//Standard comparison interest rate
var repaymentRate = 5.5;  //  5.5 % 

//ensure input data is valid 
function checkNumber(input, min, max, msg) {
msg = msg + " is invalid: " + input.value;

//ensure input is a number
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;
	}
}
//ensure value between the min and max values allowed
var num = 0 + str
	if (num < min || max < num) {
		alert("The value in " + msg + " is not in the range [" + min + " to " + max + "]");
	return false;
	}
	input.value = str;
	return true;
}

function computeField(input) {
if (input.value != null && input.value.length != 0)
{
	input.value = "" + eval(input.value);
}
	computeForm(input.form);
}

function computeForm(form) {
var A=form.Loan.value;
var T=form.Term.value;
var R=form.Rate.value;

//ensure all fields have a value
	if ((A == null || A.length == 0) ||
	(R == null || R.length == 0)) 
	{
//alert('not all fields filled in');
	return;
}

// Ensure entries are within tollerence
	if (!checkNumber(form.Loan, 100, 250000, "Loan required") ||
	!checkNumber(form.Rate, 1.5, 25, "Interest rate") ||
	!checkNumber(form.Term, 1, 30, "Repayment period")) 
	{
	form.repayment.value = "Invalid";
	return;
	}

// calculate all fields
	R = R / (100*12);  // monthly interest as decimal
	var R2 = repaymentRate / (100*12);  // standare monthly interest as decimal
	T = T * 12; 	   // term in months
	var P = (A*R) / (1-(1/Math.pow((1+R),T)));
	form.repayment.value = poundsPence( P );
	P = (A*R2) / (1-(1/Math.pow((1+R2),T)));
	form.compRepayment.value = poundsPence( P );
	P = (A*R);
	form.interest.value = poundsPence( P );
	P = (A*R2);
	form.compInterest.value = poundsPence( P );
}

function poundsPence( N ) {
	// minimum browser = IE3
	if ((navigator.appName.indexOf('Microsoft')>-1)
	&& (navigator.appVersion.indexOf('3.0')>-1) )
	{
	return N;
	}
	S = new String( N );
	var i = S.indexOf('.');
	if (i != -1) {
		S = S.substr( 0, i+3 );
		if (S.length-i < 3)
			S = S + '0';
	}
	return S;
}

//clears form
function clearForm(form) {
	form.Loan.value = "";
	form.Term.value = "";
	form.Rate.value = "";
	form.repayment.value = "";
	form.compRepayment.value = "";
	form.interest.value = "";
	form.compInterest.value = "";
}

//==========================

