// No, you are not allowed to copy this. I wish you could but my employer would not really like that.


function amortize (principal, interest, duration) {
	displayArea = document.getElementById("amortization_table");
	
	var output = "\n<table class=\"datatable\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n\t<thead>\n\t\t<th>Month</th>\n\t\t<th>Payment</th>\n\t\t<th>Interest Paid</th>\n\t\t<th>Principal Paid</th>\n\t\t<th>Remaining Principal</th>\n\t</thead>\n\t<tbody>\n";
	
	principal = parseFloat(principal);
	rate = parseFloat(interest);
	duration = parseInt(duration);
	
	monthlyRate = parseFloat( rate/(12 * 100) );
	durationMonths = parseInt( duration * 12 );
	
	payment = ( principal * ( monthlyRate / (1 - Math.pow((1 + monthlyRate), -durationMonths)) )  );
	month = 1;

	while ( (month <= durationMonths) ) {
		output += "\t\t<tr class=\"rowtwo\">\n";				// Row start
		
		output += "\t\t\t<td class=\"textright\">"+ month +"</td>\n";
		
		output += "\t\t\t<td class=\"textright\">"+ currency(payment) +"</td>\n";
		
		currentMonthlyInt = (principal * monthlyRate);
		output += "\t\t\t<td class=\"textright\">"+ currency(currentMonthlyInt) +"</td>\n";
		
		principalMonth = (payment - currentMonthlyInt);
		output += "\t\t\t<td class=\"textright\">"+ currency(principalMonth) +"</td>\n";
		
		principalBalance = (principal - principalMonth);
		output += "\t\t\t<td class=\"textright\">"+ currency(principalBalance) +"</td>\n";
		
		principal = principalBalance;
		
		output += "\t\t</tr>\n";			// Row end
		
		month++;
	}
	
	output += '\t</tbody>\n</table>';
	
	displayArea.innerHTML = output;
}


function currency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
		num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

