$(document).ready(function(){
	$('#mc_start').click(function(e){
		e.preventDefault();
		computeForm();
	});
});

function checkNumber(input, min, max, msg) {

	msg = "The " + msg + " field is invalid. ";

	//this makes sure that the number is a number
	var str = input;
	var nstr = '';
	for (var i = 0; i < str.length; i++) {
		var ch = str.substring( i, i + 1)
		if ((ch < "0" || "9" < ch) && ch != '.') {
			//do nothing
		}else{
			nstr += ch;
		}
	}
	
	str = nstr;

	//this makes sure that the number lies between the min and max values allowed
	var num = 0 + str
	if (num < min || max < num) {
		alert(msg + "The figure should be between " + min + " and " + max + ".");
		return 0;
	}
	return str;
}

function computeForm() {
	var A=checkNumber($('#mc_amount').val(), 1, 99999999, "'Mortgage required'"); // Principal amount
	var T=checkNumber($('#mc_years').val(), 5, 40, "Repayment period"); // Term - number of years
	var R=checkNumber($('#mc_rate').val(), .001, 1000, "Interest rate"); // Rate of interest

	//making sure that an entry has been made in each field.
	if ((A == null || A.length == 0) ||
		(R == null || R.length == 0)) 
	{
		//alert('not all fields filled in');
		return;
	}
	
	$('#mc_sum_amount').html(A);
	$('#mc_sum_years').html(T);
	$('#mc_sum_rate').html(R);
	// maths et al to be computed
	R = R / 100;
	var P = ((A*R)/12) * (1/(1-(Math.pow(1/(1+R),T))));
	$('#mc_monthly').html(poundsPence( P ));
	
	P = (A*R)/12;
	$('#mc_monthly_interest').html(poundsPence( P ));
	
	$('#mc_form').hide();
	$('#mc_result').fadeIn();
}

function poundsPence( N ) {
	// won't work as intended in 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;
}
