// JavaScript Document
// Written by and Copyright to David Kirkland of DKA Associates
// http://www.dkauk.com
// sales@dkauk.com

var principal;
var rate;
var term;

function calc() {
	principal = calcForm.amount.value;
	rate = calcForm.rate.value;
	term = calcForm.length.value;
        deposit = calcForm.deposit.value;
	if (checkValues()){
		calculateMonthly();
		calculateInterest();
	}
}

function calculateMonthly() {
	principal = principal - deposit;
	var monthrate = (rate*0.01)/12;
	var cumm_monthrate = monthrate + 1;
	var num_of_payments = term*12;
	var raised = Math.pow(cumm_monthrate,num_of_payments);
	var monthly = (principal*raised*monthrate)/(raised-1);

	calcForm.monthly.value = decimalRound(monthly);
}

function calculateInterest() {
	var inter = principal*((rate/100)/12);

	calcForm.interest.value = decimalRound(inter);
}

function decimalRound(N) {
	var s = new String(N);
	var deci = s.indexOf('.');
	if (deci !='-1')
	{
		var fin = s.charAt(deci+4);
		var up;
		if (fin !=null)
		{
			if (fin>=5)
			{	
				var ch = (s.charAt(deci+3)*1)+1;
				var rest = s.substring(0,deci+2);
				s = rest+ch;
			}		
		}
		q = s.substring(0,deci+3);
	}
	else {
		q= s+".00";
	}
	return q;
}

function checkValues(){
	if (checker(principal, "Mortgage Amount") && checker(deposit, "Deposit"))
	{	
		if (term=="term"){
			alert ("Please choose a mortgage length")
			return false;
		}
		if (rate=="rate") {
			alert ("Please choose an interest rate")
			return false;
		}
		else {		
			return true;
		}
	}
	else
	{	
		return false;
	}
	

}
function checker(vari,name){
	if (vari.length=="0") {
		alert ("Please enter a value in " + name + " to continue");
		return false;
	}
	for (var i = 0; i<vari.length; i++)
	{
		charact = vari.charAt(i);
		if ((charact < "0" || charact > "9") && charact!='.')
		{
			alert ("please check the " + name + " entry, it should only contain numbers from 0 to 9 and a decimal point ('.') if required");
			return false;
		}
	}
	return true;
}