
/*
 * mortgage.js -- JavaScript mortgage calculator
 *
 * Copyright 2009 Michael S. D'Errico -- All rights reserved
 *
 *
 *
 */

var createMortgageCalculator = function (doc)
{
    var home_price      = doc.getElementById ('home_price');
    var down_payment    = doc.getElementById ('down_payment');
    var interest_rate   = doc.getElementById ('interest_rate');
    var duration        = doc.getElementById ('duration');

    var loan_amount     = doc.getElementById ('loan_amount');
    var monthly_payment = doc.getElementById ('monthly_payment');
    var total_payments  = doc.getElementById ('total_payments');
    var total_interest  = doc.getElementById ('total_interest');

    var calculate = function ()
    {
        var price    = home_price.value;
        var down     = down_payment.value;
        var apr      = interest_rate.value / 100;
        var years    = duration.value;

        var loan     = price - down;
        var rate     = apr   / 12;
        var months   = years * 12;

        var payment  = loan * rate / (1 - Math.pow (1 + rate, -months));
        var total    = payment * months;
        var interest = total - loan;

        loan_amount.value     = loan.toFixed (2);
        monthly_payment.value = payment.toFixed (2);
        total_payments.value  = total.toFixed (2);
        total_interest.value  = interest.toFixed (2);

        return false;
    }

    return calculate;
}


