function MortgageCalculator()
{
};

MortgageCalculator.prototype =
{
    form: null,
    prefix: '',
    P: null,
    i: null,
    n: null,

    calculate: function(form, prefix)
    {
        this.form = form;
        this.prefix = prefix;

        this.getValues();

        if (this.checkValues() === false)
        {
            return false;
        }

        this.calculateInterestPayment();
        this.calculateMonthlyPayment();

        return false;
    },

    calculateInterestPayment: function()
    {
        this.setPayment(
            (this.P * this.i) / 12,
            'interestPayment'
        );
    },

    calculateMonthlyPayment: function()
    {
        this.setPayment(
            (this.P * (this.i / 12)) /
            (1 - Math.pow(1 + (this.i / 12), (this.n * -1))),
            'payment'
        );
    },

    setPayment: function(payment, field)
    {
        this.form[field].value = this.prefix + payment.toFixed(2);
    },

    getValues: function()
    {
        this.P = parseFloat(this.form.principal.value.replace(/[^0-9\.]/g, ""));
        this.i = parseFloat(this.form.apr.value.replace(/[^0-9\.]/g, "")) / 100;
        this.n = parseInt(this.form.years.value) * 12;
    },

    checkValues: function()
    {
        if (isNaN(this.P) || isNaN(this.i) || isNaN(this.n))
        {
            return false;
        }

        return true;
    }

};

var MC = new MortgageCalculator();
