function getAmortization(a,n,p) { // a=amount n=term p=apr
	var i=0;
	/* Calculate amortization and write table to text area **/
	var payment = getPayment(a,n,p);
	jQuery('#monPayment').html("Monthly Payment = " + (Math.round(payment*100)/100));
	var balance=a;
	var interest = 0.0;
	var principal=0.0;
	var totalinterest=0.0;
	jQuery('#amortizationtable').css('visibility', 'visible');
	jQuery('#amortizationtable tbody').html('');
	for (i=1;i<=n;i++) { //for the total months given
		interest = balance*p/1200; 
		totalinterest += interest; 
		principal = payment-interest; 
		balance -= principal;
		jQuery('#amortizationtable tbody').append('<tr><td>'+i+'</td><td>'+Math.round(balance*100)/100 +' </td><td>'+Math.round(principal*100)/100 +'</td><td>'+Math.round(interest*100)/100 +' </td><td>'+Math.round(i*payment*100)/100 +' </td><td>'+Math.round(totalinterest*100)/100 +' </td></tr>');
	}
}

function getPayment(a,n,p) {
	/* Calculates the monthly payment from annual percentage
	   rate, term of loan in months and loan amount. **/
	var acc=0;
	var base = 1 + p/1200;
	for (i=1;i<=n;i++) 
		{ acc += Math.pow(base,-i); }
	return a/acc;
}

jQuery(document).ready(function(){
	jQuery('#amortizationtable').tablesorter();
	jQuery('#calculate').click(function(){
		getAmortization(jQuery('#amount').val(),jQuery('#term').val(),jQuery('#apr').val());
		jQuery('#amortizationtable').trigger("update");
	});
});