var
	target,
	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 changeTarget(){
	target = parseInt(document.forms[1].target.value);
	if ( isNaN(eval(target)) ){
		document.forms[1].target.focus();
		document.forms[1].target.select();
		alert("Invalid input");
		return false;
	}else{
		document.forms[1].target.value = target;
		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 ( !changeTarget() ){
		return;
	}
	if ( !changeInterestRate() ){
		return;
	}
	if ( !changePeriod() ){
		return;
	}

	interestRate /= 100;
	year = Math.round(period / 12 - 0.5);
	remainPayTimes = period % 12;

	result = target;
	if ( remainPayTimes == 0 ){
		result *= 24 / (24 + 13 * interestRate);
		result *= interestRate / (Math.pow((1 + interestRate),year) - 1);
		result /= 12;
	}else{
		dom = 12.0 * (Math.pow(( 1.0 + interestRate ),year) - 1.0) / interestRate * (2.0 * 12 + (12 + 1.0) * interestRate) / (2.0 * 12);
		dom += remainPayTimes;
		dom += fac(remainPayTimes) * interestRate / 12;
		dom += 12 * (24 + 13 * interestRate) / 24 * interestRate * remainPayTimes / 12;
		result /= dom;
	}

	document.forms[1].reward.value = formatMoney(Math.round(result * 100) / 100);
}
function fac(input){
	if ( input == 1 ){
		return 1;
	}else{
		return input + fac(input-1);
	}
}


