﻿<!--
var amount_decimal_places = 2;
var interest_decimal_places = 4;
var days_in_year = 365;
var max_loan_ratio = 0.70;

function ltrim(x) { return x.replace(/^\s*/,''); }
function rtrim(x) { return x.replace(/\s*$/,''); }
function trim(x)  { return ltrim(rtrim(x)); }
function isMatch(val,re) { return re.test(val); }

function calculate(){
	var propertyPrice = trim(document.getElementById("property_price").value);
	var loanAmount = trim(document.getElementById("loan_amount").value);
	var tenor = trim(document.getElementById("tenor").value);
	var interestRate = trim(document.getElementById("interest_rate").value);
	
	propertyPrice = propertyPrice.replace(/\,/g,"");
	loanAmount = loanAmount.replace(/\,/g,"");
	tenor = tenor.replace(/\,/g,"");
	interestRate = interestRate.replace(/\,/g,"");
	
	propertyPrice = parseFloat(propertyPrice);
	loanAmount = parseFloat(loanAmount);
	tenor = parseInt(tenor);
	interestRate = parseFloat(interestRate);
	
	loanAmount = roundNumber(loanAmount,amount_decimal_places);
	interestRate = roundNumber(interestRate,interest_decimal_places);
	
	var noOfInstalment = tenor*12;
	var interestRatePct = interestRate / 100;
	
	var monthlyPayment = calculatePayment(interestRatePct / 12, noOfInstalment, loanAmount);
	
	var mortgagePercentage = (loanAmount / propertyPrice) * 100;
	
	var biweeklyPayment = monthlyPayment / 2;
	biweeklyPayment = roundNumber(biweeklyPayment, 2);
	
	var totalInterestPaid = 0;
	var outstandingBalance = loanAmount;
	
	for (var i = 0; i < noOfInstalment; i++) {
		var daysInMonth = calculateNoOfDays(i);
		
		var interestPaid = calculateSimpleMonthlyInterest(interestRatePct, daysInMonth, days_in_year, outstandingBalance);
		var principalPaid = monthlyPayment - interestPaid;
		
		outstandingBalance -= principalPaid;
		totalInterestPaid += interestPaid;
	}
	
	var biweeklyTenor = calculateTenor(interestRatePct * 14 / 365, loanAmount, biweeklyPayment);
	
	var noOfBiweeklyInstalment = parseInt(Math.ceil(biweeklyTenor));
	biweeklyTenor = noOfBiweeklyInstalment / 26;
	
	var totalBiweeklyInterestPaid = 0;
	var biweeklyOutstandingBalance = loanAmount;
	
	for (var i = 0; i < noOfBiweeklyInstalment; i++) {
		var biweeklyInterestPaid = calculateSimpleBiweeklyInterest(interestRatePct, days_in_year, biweeklyOutstandingBalance);
		var biweeklyPrincipalPaid = biweeklyPayment - biweeklyInterestPaid;
		
		biweeklyOutstandingBalance -= biweeklyPrincipalPaid;
		
		totalBiweeklyInterestPaid += biweeklyInterestPaid;
	}
	
	var interestSaving = totalInterestPaid - totalBiweeklyInterestPaid;
	var repaymentShorten = tenor - biweeklyTenor;
	
	monthlyPayment = roundNumber(monthlyPayment,amount_decimal_places);
	biweeklyPayment = roundNumber(biweeklyPayment,amount_decimal_places);
	totalInterestPaid = roundNumber(totalInterestPaid,amount_decimal_places);
	totalBiweeklyInterestPaid = roundNumber(totalBiweeklyInterestPaid,amount_decimal_places);
	biweeklyTenor = roundNumber(biweeklyTenor,amount_decimal_places);
	mortgagePercentage = roundNumber(mortgagePercentage,amount_decimal_places);
	interestSaving = roundNumber(interestSaving,amount_decimal_places);
	repaymentShorten = roundNumber(repaymentShorten,amount_decimal_places);
	
	monthlyPayment = Math.round(monthlyPayment);
	mortgagePercentage = Math.round(mortgagePercentage);
	interestRate = interestRate.toFixed(2);
	
	propertyPrice = addCommas(propertyPrice);
	loanAmount = addCommas(loanAmount);
	mortgagePercentage = addCommas(mortgagePercentage);
	interestRate = addCommas(interestRate);
	monthlyPayment = addCommas(monthlyPayment);
	
	document.getElementById("property_price").value=propertyPrice;
	document.getElementById("loan_amount").value=loanAmount;
	document.getElementById("interest_rate").value=interestRate;
	
	var html="";
	html+='<table width="100%" border="0" cellspacing="0" cellpadding="0">';
	html+='  <tr>';
	html+='    <td><H2><img src="com/pixelsbox.gif" width="22" height="22" align="absmiddle">Result</H2></td>';
	html+='  </tr>';
	html+='</table>';
	html+='<table width="100%" border="0" cellspacing="0" cellpadding="0">';
	html+='  <tr>';
	html+='    <td><img src="com/line01.gif" width="660" height="1"></td>';
	html+='  </tr>';
	html+='</table>';
	html+='<img src="com/spacer.gif" width="1" height="5"><br>';
	html+='<table width="645" border="0" align="center" cellpadding="0" cellspacing="1">';
	html+='  <tr>';
	html+='    <td bgcolor="#FFFFFF"><table width="100%" border="0" cellspacing="0" cellpadding="0">';
	html+='      <tr>';
	html+='        <td width="100%" class="insidecontent"><table width="643" border="0" align="center" cellpadding="0" cellspacing="0">';
	html+='          <tr>';
	html+='            <td width="150"><table width="150" border="0" cellspacing="0" cellpadding="0">';
	html+='              <tr>';
	html+='                <td width="129" bgcolor="54aa00"><div align="center" class="insidecontent"><font color="#FFFFFF"><strong>Monthly Repayment</strong></font></div></td>';
	html+='                <td width="12"><div align="right"><img src="com/round_2.gif" width="12" height="23"></div></td>';
	html+='              </tr>';
	html+='            </table></td>';
	html+='            <td>&nbsp;</td>';
	html+='          </tr>';
	html+='        </table></td>';
	html+='      </tr>';
	html+='    </table>';
	html+='    <table width="643" border="0" cellspacing="0" cellpadding="0">';
	html+='      <tr>';
	html+='        <td bgcolor="54aa00"><table width="100%" border="0" align="center" cellpadding="3" cellspacing="1">';
	html+='          <tr bgcolor="ddfac2">';
	html+='            <td width="30%" class="insidecontent"><strong>Property price/ valuation:</strong></td>';
	html+='            <td width="70%" class="insidecontent">HKD ';
	html+=                                                   propertyPrice;
	html+='            </td>';
	html+='          </tr>';
	html+='          <tr bgcolor="ebfcdb">';
	html+='            <td class="insidecontent"><strong>Loan amount:</strong></td>';
	html+='            <td class="insidecontent">HKD ';
	html+=                                                   loanAmount;
	html+='            </td>';
	html+='          </tr>';
	html+='          <tr bgcolor="ddfac2">';
	html+='            <td class="insidecontent"><strong>Loan tenure:</strong></td>';
	html+='            <td class="insidecontent">';
	html+=                                                   tenor;
	html+='            yesr(s)</td>';
	html+='          </tr>';
	html+='          <tr bgcolor="ebfcdb">';
	html+='            <td class="insidecontent"><strong>Loan ratio:</strong></td>';
	html+='            <td class="insidecontent">';
	html+=                                                   mortgagePercentage;
	html+='            %</td>';
	html+='          </tr>';
	html+='          <tr bgcolor="ddfac2">';
	html+='            <td class="insidecontent"><strong>Interest rate:</strong></td>';
	html+='            <td class="insidecontent">';
	html+=                                                   interestRate;
	html+='            %</td>';
	html+='          </tr>';
	html+='          <tr bgcolor="ebfcdb">';
	html+='            <td class="insidecontent"><strong>Monthly repayment:</strong></td>';
	html+='            <td class="insidecontent">HKD ';
	html+=                                                   monthlyPayment;
	html+='            </td>';
	html+='          </tr>';
	html+='        </table></td>';
	html+='      </tr>';
	html+='    </table></td>';
	html+='  </tr>';
	html+='</table>';
	html+='<br>';
	html+='<table width="645" border="0" align="center" cellpadding="2" cellspacing="0">';
	html+='  <tr>';
	html+='    <td colspan="2" class="insidecontent">We offer a comprehensive range of mortgage plans tailored to your different needs. Please select:</td>';
	html+='  </tr>';
	html+='  <tr>';
	html+='    <td width="4%" class="insidecontent"><input type="radio" name="bus_mortgage" id="bus_mortgage" value="0" /></td>';
	html+='    <td width="96%" class="insidecontent">Prime-based Mortgage</td>';
	html+='  </tr>';
	html+='  <tr>';
	html+='    <td class="insidecontent"><input type="radio" name="bus_mortgage" id="bus_mortgage" value="1" /></td>';
	html+='    <td class="insidecontent">Business Mortgage-Link</td>';
	html+='  </tr>';
	html+='  <tr>';
	html+='    <td class="insidecontent"><input type="radio" name="bus_mortgage" id="bus_mortgage" value="2" /></td>';
	html+='    <td class="insidecontent">Property Refinancing</td>';
	html+='  </tr>';
	html+='</table>';
	html+='<table width="645" border="0" align="center" cellpadding="0" cellspacing="0">';
	html+='  <tr>';
	html+='    <td><div align="right"><a href="javascript:applyMortgage();"><img src="com/apply_busmort_cal.gif" width="76" height="19" vspace="5" border="0"></a></div></td>';
	html+='  </tr>';
	html+='</table>';
	html+='<br>';
	html+='<table width="645" border="0" align="center" cellpadding="2" cellspacing="0">';
	html+='  <tr>';
	html+='    <td class="insidecontent">The above information is for reference only.</td>';
	html+='  </tr>';
	html+='</table>';
	
	var resultDiv = document.getElementById("result");
	resultDiv.innerHTML = html;
}

function roundNumber(number,decimalPlaces){
	return(Math.round(number * Math.pow (10 , decimalPlaces)) / Math.pow(10 , decimalPlaces)) ; 
}

function calculatePayment(rate,tenor,principle){
	if (rate == 0) {
		return (principle / tenor);
	}
	var factor = Math.pow(1 + rate, tenor);	
	var pmt = (rate * factor * principle) / (factor - 1);
	return pmt;
}

function calculateSimpleMonthlyInterest(rate,daysInMonth,daysInYear,principle){
	var factor = daysInMonth / daysInYear;
	var interest = principle * rate * factor;
	return interest;
}

function calculateTenor(rate,principal,payment){
	var factor = payment / (payment - rate * principal);
	var tenor = Math.log(factor) / Math.log(1 + rate);
	return tenor;
}

function calculateSimpleBiweeklyInterest(rate,daysInYear,principle){
	var factor = 14.0 / daysInYear;
	var interest = principle * rate * factor;
	return interest;
}

function calculateNoOfDays(instalmentNo){
	var month = parseInt((instalmentNo + 1) % 12);
	switch (month) {
		case 2:
			return 28;
		case 4:
		case 6:
		case 9:
		case 11:
			return 30;
		default:
			return 31;
	}
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function clearValue(){
	document.getElementById("property_price").value="";
	document.getElementById("loan_amount").value="";
	document.getElementById("tenor").value="";
	document.getElementById("interest_rate").value="";
	var resultDiv = document.getElementById("result");
	resultDiv.innerHTML = "";
}

function applyMortgage(){
	var form = document.forms[0];
	var mortgValue;
	for (var i = 0; i < form.bus_mortgage.length; i++) {
		if (form.bus_mortgage[i].checked) {
			mortgValue=form.bus_mortgage[i].value;
			break;
		}
	}
	
	switch(mortgValue){
		case "0":
			window.location.href="https://eba.hangseng.com/form/Form?appl=mortgage&locale=en&loantype=PBM";
			break;
		case "1":
			window.location.href="https://eba.hangseng.com/form/Form?appl=mortgage&locale=en&loantype=BML";
			break;
		case "2":
			window.location.href="https://eba.hangseng.com/form/Form?appl=mortgage&locale=en&loantype=PR";
			break;
	}
}

function preCalculate(){
	var errCount = 0;
	
	var propertyPrice = trim(document.getElementById("property_price").value);
	var loanAmount = trim(document.getElementById("loan_amount").value);
	var tenor = trim(document.getElementById("tenor").value);
	var interestRate = trim(document.getElementById("interest_rate").value);
	
	if(propertyPrice==""){
		alert("Please input property price.");
		errCount++;
		return;
	}
	if(loanAmount==""){
		alert("Please input loan amount.");
		errCount++;
		return;
	}
	if(tenor==""){
		alert("Please input tenor.");
		errCount++;
		return;
	}
	if(interestRate==""){
		alert("Please input mortgage interest rate.");
		errCount++;
		return;
	}
	
	var amount_patten;
	var tenor_patten;
	var interest_rate_patten;
	amount_patten=/^([+-]?[0-9,]*)$/;
	tenor_patten=/^([0-9,]*)$/;
	interest_rate_patten=/^([+-]?[0-9,]*(.[0-9]{0,2})?)$/;
	
	propertyPrice = propertyPrice.replace(/\,/g,"");
	loanAmount = loanAmount.replace(/\,/g,"");
	tenor = tenor.replace(/\,/g,"");
	interestRate = interestRate.replace(/\,/g,"");
	
	if (!isMatch(propertyPrice,amount_patten)) {
		alert("Invalid property price.");
		errCount++;
		return;
	}
	if (!isMatch(loanAmount,amount_patten)) {
		alert("Invalid loan amount.");
		errCount++;
		return;
	}
	if (!isMatch(tenor,tenor_patten)) {
		alert("Invalid tenor.");
		errCount++;
		return;
	}
	if (!isMatch(interestRate,interest_rate_patten)) {
		alert("Invalid loan interest rate.");
		errCount++;
		return;
	}
	
	if(parseFloat(propertyPrice)<0.01){
		alert("Purchase price / valuation should be greater than 0.");
		errCount++;
		return;
	}	
	if(parseFloat(loanAmount)<0.01){
		alert("Loan amount should be greater than 0.");
		errCount++;
		return;
	}
	
	var maxLoanAmount = Math.floor(parseFloat(propertyPrice) * max_loan_ratio);
	var maxLoanPercentage = max_loan_ratio * 100;
	if(parseFloat(loanAmount) > maxLoanAmount && parseFloat(propertyPrice)>0){
		alert("The loan amount exceeds the maximum loan amount of HKD "+maxLoanAmount+" (equivalent to "+maxLoanPercentage+"% of property purchase price).");
		errCount++;
		return;
	}
	
	if(parseInt(tenor)<1 || parseInt(tenor)>30){ 
		alert("Tenor should be 1 and 30.");
		errCount++;
		return;
	}
	
	if(parseFloat(interestRate)<0.001 || parseFloat(interestRate)>20){ 
		alert("Interest rate should between 0.001% and  20%."); 
		errCount++;
		return;
	}
	
	if(errCount>0){
		var html="";
		var resultDiv = document.getElementById("result");
		resultDiv.innerHTML = html;
	}else{
		calculate();
	}
}
//-->