// JavaScript Document
function clearOutput() {
    var output = document.getElementById("output");
    while (output.firstChild)
	output.removeChild(output.firstChild);
	var summary = document.getElementById("summary");
    while (summary.firstChild)
	summary.removeChild(summary.firstChild);
}

// Write a string to the output area.
function write(str) {
    var output = document.getElementById("output");
    var txt = document.createTextNode(str);
    output.appendChild(txt);
}

// Write a string with a newline to the output area.
function writeln(str) {
    var output = document.getElementById("output");
    var txt = document.createTextNode(str);
    var newline = document.createElement("br");
    output.appendChild(txt);
    output.appendChild(newline);
}

// Write a string with a newline to the output area.
function writeln_title(str) {
    var output = document.getElementById("summary");
    var txt = document.createTextNode(str);
    var newline = document.createElement("br");
    output.appendChild(txt);
    output.appendChild(newline);
}

// Write a string in red to signify an error.
function errorln(str) {
    var output = document.getElementById("output");
    var txt = document.createTextNode(str);
    var newline = document.createElement("br");
    var span = document.createElement("span");
    // setAttribute("class" ...) does not work in IE.
    span.className = "error";
    span.appendChild(txt);
    span.appendChild(newline);
    output.appendChild(span);
}

// Format floating point number in fixed-point notation.
function fixedfmt(num, decimals) {
    // Number.toFixed is a Javascript 1.5 feature, 
    // so we need to test for it here.
    return num.toFixed ? num.toFixed(decimals) : num;
}

function fmtmoney(num) {
    if (Math.abs(num) < 0.005)
	num = 0;
    return "$" + fixedfmt(num, 2);
}

function fmtpct(num) {
    return fixedfmt(num * 100, 2) + "%";
}

function flushright(s, width) {
    var str = s.toString();
    var pad = width - str.length;
    for (var i = 0; i < pad; ++i)
	str = " " + str;
    return str;
}

// Get numbers from the input fields.
function getInput() {
    var field;
    var obj = new Object();

    field = document.getElementById("principal");
    obj.principal = parseFloat(field.value);
    if (isNaN(obj.principal) || obj.principal <= 0) {
	errorln("Invalid principal amount. Enter a positive number.");
	return false;
    }

    field = document.getElementById("amortperiod");
    obj.amortperiod = parseFloat(field.value);
    if (isNaN(obj.amortperiod) || obj.amortperiod <= 0) {
	errorln("Invalid amortization period. Enter a positive number.");
	return false;
    }

    field = document.getElementById("paymentsperyear");
    obj.payperyear = parseInt(field.value);
    if (isNaN(obj.payperyear) || obj.payperyear <= 0) {
	errorln("Invalid number of payments per year. Enter a positive integer.");
	return false;
    }

    field = document.getElementById("interest");
    obj.interest = parseFloat(field.value) / 100;
    if (isNaN(obj.interest) || obj.interest <= 0) {
	errorln("Invalid interest rate. Enter a positive number.");
	return false;
    }

    return obj;
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function main() {
    clearOutput();

    var input = getInput();
    if (!input)
	return false;

    var intrate = input.interest / input.payperyear;
    var numpayments = input.amortperiod * input.payperyear;

    var x = Math.pow(1 + intrate, numpayments);
    var payments = intrate * input.principal * x / (x - 1);

    writeln_title("Payments       = " + addCommas(fmtmoney(payments)));
    writeln_title("Total payments = " + addCommas(fmtmoney(payments * numpayments)));
    writeln_title("Interest cost  = " + 
	    addCommas(fmtmoney(payments * numpayments - input.principal)));
    writeln_title("");

    var balance = input.principal;
    var sumint = 0;
    var sumprin = 0;
    var sumpay = 0;

    writeln("Period   Principal    Interest   " + 
	    "  Balance");
    for (var i = 1; i <= numpayments; ++i) {
	sumpay += payments;

	var thisint = balance * intrate;
	sumint += thisint;

	var thisprin = payments - thisint;
	sumprin += thisprin;

	balance -= thisprin;

	writeln(flushright(i, 6) + "  " + 
		//flushright(fmtmoney(payments), 10) + "  " + 		
		 addCommas(flushright(fmtmoney(thisprin), 10)) + "  " + 
		 addCommas(flushright(fmtmoney(thisint), 10)) + "  " + 
    //flushright(fmtmoney(sumpay), 10) + "  " + 
	  //flushright(fmtmoney(sumint), 10) + "  " + 
	  //flushright(fmtmoney(sumprin), 10) + "  " + 
	addCommas(flushright(fmtmoney(balance), 10)));
    }
}