

function calculate() {
    // Get user input from the form.
	// Assume it is all valid for now.
	
 
    var principal = parseFloat(document.loandata.principal.value);
    var period = document.loandata.period.value;
    var payments = parseInt(document.loandata.years.value);
	var intrate = parseFloat(document.loandata.intrate.value);
	var interest
	var time
	var number
	
 
	if(period == "week"){
	interest = ((intrate/365.25)*7)/100;
	time = period + "s";
	number = 52 * payments;
		   // Add an extra week if 6 years or more
		   if(payments > 5 ){
		   number = (52 * payments) + 1;
		   }
		   // Add 2 extra weeks if 9 years or more
		   if(payments > 8 ){
		   number = (52 * payments) + 2;
		   }
	}
	else if(period == "fortnight"){
	interest = ((intrate/365.25)*14)/100;
	time = "weeks";
	number = 52 * (payments / 2);
		   // Add an extra week if 6 years or more 
		   // of fortnightly repayments.
		   if(payments > 5 ){
		   number = 52 * (payments / 2) + 1;
		   }
	}
	else if(period == "month"){
	interest = (intrate/12)/100;
	time = period + "s";
	number = 12 * payments;
	}
	
 
	IR = interest + 1;
	IR = Math.pow(IR,number);
 
    // Work out the repayment figure now.
	//
	Fig1 = principal*IR;
	Fig2 = IR-1;
	Fig3 = Fig2/interest;
	monthly = Fig1/Fig3;
 
    // Since Math.pow can sometimes return an infinite number,
	// make sure that we have a finite number for monthly figure
    if (!isNaN(monthly) && 
        (monthly != Number.POSITIVE_INFINITY) &&
        (monthly != Number.NEGATIVE_INFINITY)) {
 
       
		//Display the calculated data
		//
		document.loandata.payment.value = round(monthly) + " " + "every " + period;
        document.loandata.total.value = round(monthly * number)
        document.loandata.totalinterest.value = round((monthly * number) - principal);
    }
    // If the user input invalid data
    // clear the display again for re-entry.
    else {
       
	    document.loandata.principal.value = "";
		document.loandata.payment.value = "";
        document.loandata.total.value = "";
        document.loandata.totalinterest.value = "";
    }
}
 
function round(x) {
// Round the number to two decimal places.
valRounded = Math.round(x*100)/100;
valRounded = "" + valRounded + "";
decLoc = valRounded.indexOf(".");
 
if (decLoc != -1) {
	array1 = valRounded.split(".");
 
	if (array1[1].length != 2) {
		valRounded = valRounded + "0";
	}
}
 
else {
 	valRounded = valRounded + ".00";
}
 
return valRounded;
}

