
/*
 * Display loan summary.
 */
function DisplaySummary() {
    return DisplaySummaryInDocument(document);
}


/*
 * Display loan summary in the specified document.
 */
function DisplaySummaryInDocument(targetDocument) {
    var summary = GetInterestSummary(
            document.getElementById('amount_input').value,
            document.getElementById('termlength_input').value,
            document.getElementById('term_units').value,
            document.getElementById('rate_input').value / 100,
            document.getElementById('period_input').value);

    targetDocument.getElementById('LoanAmount').innerHTML = DisplayCurrency(summary.Principal);
    targetDocument.getElementById('TotalPayments').innerHTML = summary.TotalPayments;
    targetDocument.getElementById('Period').innerHTML = summary.PeriodName;
    targetDocument.getElementById('PaymentSize').innerHTML = DisplayCurrency(summary.PeriodPayment);
    targetDocument.getElementById('TotalPaid').innerHTML = DisplayCurrency(summary.TotalPayment);
    targetDocument.getElementById('TotalInterest').innerHTML = DisplayCurrency(summary.TotalInterest);
    targetDocument.getElementById('AverageMonthly').innerHTML = DisplayCurrency(summary.MonthlyPayment);

    return summary;
}


/*
 * Global pointer to popup window for report.
 */
var reportWindow;


/*
 * Display amortization report in a popup window.
 */
function PopupAmortizationReport(report) {
    reportWindow = window.open(report, "reportWindow");
}


/*
 * Callback for when the external window has finished loading.
 */
function ReportPopupCallback() {
    DisplaySummaryInDocument(document);
    DisplayAmortizationTableInDocument(reportWindow.document);
}


/*
 * Display the amortization table in the specified document.
 */
function DisplayAmortizationTableInDocument(targetDocument) {
    
    var summary = DisplaySummaryInDocument(targetDocument);

    var totalPaid = 0;
    var totalInterestPaid = 0;
    var outstandingAmount = summary.TotalPayment;
    var outstandingInterest = summary.TotalInterest;

    var interestRatePerPeriod = document.getElementById('rate_input').value / document.getElementById('period_input').value / 100;

    for (x = 1; x <= summary.TotalPayments; x++) {
        
        totalPaid += summary.PeriodPayment;

        var interestThisPayment = (outstandingAmount - outstandingInterest) * interestRatePerPeriod;
        var principalThisPayment = summary.PeriodPayment - interestThisPayment

        totalInterestPaid += interestThisPayment;

        AppendRowToAmortizationTable(
                targetDocument,
                x,
                summary.PeriodPayment, principalThisPayment, interestThisPayment);
        
    }
}


/*
 * Add a row to the amortization table.
 */
function AppendRowToAmortizationTable(
        targetDocument,
        rowNumber,
        currentAmount,
        currentPrincipal,
        currentInterest)
{

    var table = targetDocument.getElementById('AmortizationTableBody');
    var row = targetDocument.createElement('tr');
    
    AppendEntryToTableRow(targetDocument, row, rowNumber);
    
    AppendEntryToTableRow(targetDocument, row, DisplayCurrency(currentAmount));
    AppendEntryToTableRow(targetDocument, row, DisplayCurrency(currentPrincipal));
    AppendEntryToTableRow(targetDocument, row, DisplayCurrency(currentInterest));

    table.appendChild(row);
}


/*
 * Append an entry to the amortization table row.
 */
function AppendEntryToTableRow(targetDocument, row, value) {
    var td = targetDocument.createElement('td');
    var textNode = targetDocument.createTextNode(value);
    td.appendChild(textNode);
    row.appendChild(td);
}


/*
 * Format currency for the specified numeric value.
 */
function DisplayCurrency(value) {
    return FormatCurrency(value);
}



/*
 * Financial Calculator -- Common Functions.
 */


/*
 * Format a number as currency.
 */
function FormatCurrency(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);
}


/*
 * Calculate summary for interest payments.
 */
function GetInterestSummary(
        principal, 
        term, 
        termsPerYear, 
        rate, 
        periodsPerYear) 
{
    var totalPayments = term / termsPerYear * periodsPerYear;
    var periodName = GetPeriodName(periodsPerYear);
    var ratePerPeriod = rate / periodsPerYear;
    var totalPeriods = term / termsPerYear * periodsPerYear;
    
    var paymentPerPeriod = 0;
    if (rate != 0) {
        paymentPerPeriod =
            principal *
            ratePerPeriod *
            Math.pow(1 + ratePerPeriod, totalPeriods) /
            (Math.pow(1 + ratePerPeriod, totalPeriods) - 1);
    }
    else {
        paymentPerPeriod = principal / totalPeriods;
    }

    var averageMonthlyPayment = paymentPerPeriod * periodsPerYear / 12;

    var totalPayment = paymentPerPeriod * totalPeriods;

    var totalInterest = totalPayment - principal;
    
    
    
    return {
        Principal : principal,
        TotalPayments: totalPayments,
        PeriodPayment: paymentPerPeriod,
        PeriodName: periodName,
        MonthlyPayment: averageMonthlyPayment,
        TotalPayment: totalPayment,
        TotalInterest: totalInterest
    }
}


function GetPeriodName(periodsPerYear) {
    if (periodsPerYear == 12) {
        return "month";
    }

    if (periodsPerYear == 24) {
        return "half month";
    }

    if (periodsPerYear == 26) {
        return "two weeks";
    }

    if (periodsPerYear == 52) {
        return "week";
    }

    return "..";
}


