// JavaScript Document

	var calculatedTotalCost;
	var amtNeedToPayPerMonth;
	var theFinanceMargin
	var thePropertyPrice;
	var totalPayment;

	var theLoanYear;
	var theInterest;
	var theInterestRate;
	var totalMonths;


function calculateTotalCost() {

	document.frmLoanCalculator.totalCost.value = 0;
	k = document.frmLoanCalculator.financeMargin.options.selectedIndex;

	//retrieve value in the form
	thePropertyPrice = Number(document.frmLoanCalculator.propertyPrice.value);
	theFinanceMargin = (document.frmLoanCalculator.financeMargin.options[k].text / 100 )

	//calculate total payment
	totalPayment = thePropertyPrice 
	calculatedTotalCost = Number(totalPayment * theFinanceMargin);
	document.frmLoanCalculator.totalCost.value = "" +calculatedTotalCost;
}


function validateForm() {
	
	if ((thePropertyPrice == null || thePropertyPrice == 0))  
		{
		alert("Please enter the property price before the Monthly Payment can be Calculated.");
		return false; 
		}
	else {
		if (calculatedTotalCost == null || calculatedTotalCost == 0) 
			{
			alert("Monthly Payment can not be Calculated.");
			return false; 
			}
		else {
			if (isNaN(calculatedTotalCost)) 
				{
				alert("Please enter the correct Amount to calculate the Monthly Payment");
				return false;	
				}
			else 
				{
				return true; 
				}
			}
		}
}

function calculateMonthlyPayment() {

	if (validateForm() == true) {
		var i;	var j; var k;


		// Add the text, Calculate monthly payment
		document.frmLoanCalculator.tEstimate.value="Estimated Monthly Payment =";

		//retrieve no. of years
		i = document.frmLoanCalculator.loanYear.options.selectedIndex;
		theLoanYear = document.frmLoanCalculator.loanYear.options[i].text;
		totalMonths = theLoanYear * 12;

		//retrieve interest rate
		j = document.frmLoanCalculator.interestRate.options.selectedIndex;
		theInterestRate = document.frmLoanCalculator.interestRate.options[j].text/100;
		k = theInterestRate / 12; //get the interest rate for each month
		
	        var pow = 1;

        	for (var m = 0; m < totalMonths; m++)
		        pow = pow * (1 + k);

		amtNeedToPayPerMonth = Math.round((calculatedTotalCost * pow * k) / (pow - 1))
		document.frmLoanCalculator.monthlyInstalment.value = "RM "+amtNeedToPayPerMonth;

		document.frmLoanCalculator.tQualify.value ="To be Qualify, your Gross/Total Monthly Income\n should be at least RM "+amtNeedToPayPerMonth*3; 
	}
}

//-->
