var
	pay,
	interestRate,
	period,
	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 changePay(){
	pay = parseInt(document.forms[1].pay.value);
	if ( isNaN(eval(pay)) ){
		document.forms[1].pay.focus();
		document.forms[1].pay.select();
		alert("Invalid input");
		return false;
	}else{
		document.forms[1].pay.value = pay;
		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 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{
		document.forms[1].period.value = period;
		return true;
	}
}
function changeReward(){
	document.forms[1].reward.value = reward;
}
function calc(){
	if ( !changePay() ){
		return;
	}
	if ( !changeInterestRate() ){
		return;
	}
	if ( !changePeriod() ){
		return;
	}

	interestRate /= 100;
	year = Math.round(period / 12 - 0.5);
	remainPayTimes = period % 12;
	amountPerYear = 12 * pay;

	result = cyear(year);
	if ( remainPayTimes != 0 ){
		remainPrincipal = remainPayTimes * pay;

		result += remainPrincipal;
		result += (pay * fac(remainPayTimes) * interestRate) / 12.0;
		result += cyear(1) * interestRate * remainPayTimes / 12.0;
	}

	document.forms[1].reward.value = formatMoney(Math.round(result * 100) / 100);
}
function cyear(inyear){
	amountPerYear = 12 * pay;

	result = amountPerYear;
	result *= (Math.pow(( 1 + interestRate ),inyear) - 1) / interestRate;
	return result *= (2 * 12 + (12 + 1) * interestRate) / (2 * 12);
}
function fac(input){
	if ( input == 1 ){
		return 1;
	}else{
		return input + fac(input-1);
	}
}

