// Mortgage Calculator
// Adapted from BBC Mortgage Calculator model

	function showResults() {
		var results=document.getElementById('resultsbody');
		var rtab=document.getElementById('results');
		var calcform=document.getElementById('calcbody');
		
		results.style.visibility = 'visible';
		rtab.style.zIndex = 4;
		calcform.style.visibility = 'hidden';
	}
	
	function showMortgage() {
		var results=document.getElementById('resultsbody');
		var rtab=document.getElementById('results');
		var calcform=document.getElementById('calcbody');
		
		results.style.visibility = 'hidden';
		rtab.style.zIndex = 0;
		calcform.style.visibility = 'visible';
	} 		
		
		
	//checks that data are valid 
	function checkNumber(input, min, max, msg) {

		msg = msg + " should be in the range ";

		//this makes sure that the number 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;
			}
		}

		//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 + "[" + min + ".." + max + "]");
			return false;
		}
		input.value = str;
		return true;
	}

	function computeField(input, min, max, label) {
		if (input.value != null && input.value.length != 0)
		{
			input.value = "" + eval(input.value);
		}
		var bool = checkNumber(input, min, max, label);
		//computeForm(input.form);
	}

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

		//making sure that an entry has been made in each field.
		if ((A == null || A.length == 0) ||
			(R == null || R.length == 0) ||
			(T == null || T.length == 0)) 
		{
			alert('Please fill in all fields');
			return false;
		}

		// making sure that entries are valid by using check number
		if (!checkNumber(form.A, 1, 99999999, "Mortgage Required") ||
			!checkNumber(form.R, .001, 1000, "Interest rate") ||
			!checkNumber(form.T, 5, 40, "Time to repay")) 
		{
			document.getElementById('resultsform').Cm.value = "Invalid";
			return false;
		}

		// maths et al to be computed
		R = R / 100;
		var P = ((A*R)/12) * (1/(1-(Math.pow(1/(1+R),T))));
		document.getElementById('resultsform').Cm.value = poundsPence( P );
		P = (A*R)/12;
		document.getElementById('resultsform').CI.value = poundsPence( P );
		return true;
	}

	function poundsPence( N ) {
		// cut off any digits beyond the 2nd decimal place 
		// don't try this with ie3 because it's rubbish
		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.A.value = "";
		form.T.value = "";
		form.R.value = "";
	}
	
	
