var
	loan,
	interestRate,
	period,
	handlingFeeRate,
	reward=0;
	
function formatMoney(inVal){
	strIn = new String(inVal);
	if ( strIn.indexOf(".") == -1 ){
		dollar = strIn;
		cent = "";
	}else{
		dollar = strIn.substring(0,strIn.indexOf("."));
		cent = strIn.substring(strIn.indexOf("."),strIn.length);
	}
	count = dollar.length%3;
	if ( count == 0 ){
		count = 3;
	}
	result = dollar.substring(0,count);
	count += 3;
	while ( count <= dollar.length ){
		result += ",";
		result += dollar.substring(count-3,count);
		count += 3;
	}
	result += cent;
	return result;
}

function changeLoan(){
	loan = parseInt(document.forms[1].loan.value);
	if ( isNaN(eval(loan)) ){
		document.forms[1].loan.focus();
		document.forms[1].loan.select();
		alert("Invalid input");
		return false;
	}else{
		document.forms[1].loan.value = loan;
		return true;
	}
}
function changeInterestRate(){
	interestRate = parseFloat(document.forms[1].interestRate.value);
	if ( isNaN(eval(interestRate)) ){
		document.forms[1].interestRate.focus();
		document.forms[1].interestRate.select();
		alert("Invalid input");
		return false;
	}else{
		document.forms[1].interestRate.value = interestRate;
		return true;
	}
}
function changeHandlingFeeRate(){
	handlingFeeRate = parseFloat(document.forms[1].handlingFeeRate.value);
	if ( isNaN(eval(handlingFeeRate)) ){
		document.forms[1].handlingFeeRate.focus();
		document.forms[1].handlingFeeRate.select();
		alert("Invalid input");
		return false;
	}else{
		document.forms[1].handlingFeeRate.value = handlingFeeRate;
		return true;
	}
}
function changePeriod(){
	period = parseInt(document.forms[1].period.value);
	if ( isNaN(eval(period)) ){
		document.forms[1].period.focus();
		document.forms[1].period.select();
		alert("Invalid input");
		return false;
	}else{
		if(eval(period)>12){
		  alert('Maximum Repayment Period is 12 months');
		  return false;
		}else{
		   document.forms[1].period.value = period;
		  return true;
		}
	}
}
function changeReward(){
	document.forms[1].reward.value = reward;
}
function calc(){
	if ( !changeLoan() ){
		return;
	}
	if ( !changeInterestRate() ){
		return;
	}
	if ( !changePeriod() ){
		return;
	}
	if ( !changeHandlingFeeRate() ){
		return;
	}
	//result = ( loan * ( 1.0 + ( handlingFeeRate / 100 ) * period / 12.0 ) ) * ( 1.0 + interestRate / 100 * period ) / period
result =( loan+loan*handlingFeeRate/100)/period+( loan +loan*handlingFeeRate/100)*interestRate/100;
	document.forms[1].reward.value = formatMoney(Math.round(result * 100) / 100);
}


