﻿
// Interest Calculator
var calculator = {
    principal   : Number,
    downPayment : Number,
    APR         : Number,
    payments    : Number,
    base        : Number,
    init        : function(){

        // Allows only numeric input
        $('#price, #downPayment, #apr').numeric({allow:"."});
        
        // Clears and resets default values
        $('#price, #downPayment, #apr').focus(function(){
            if($(this).val() == $(this).attr('defaultValue')){
                $(this).val('');
            }
        });
        $('#price, #downPayment, #apr').blur(function(){
            if($(this).val() == ''){
                $(this).val($(this).attr('defaultValue'));
            }
        });
    
        // Runs the calculation
        $('#btnCalculate').click(function(e){
        
            $('#output').stop(true, true).slideUp('fast', function(){    
                        
                if(calculator.isValid()){
                    calculator.principal = parseFloat($('#price').val());
                    calculator.downPayment = parseFloat($('#downPayment').val());
                    calculator.APR = parseFloat($('#apr').val()) / 100;
                    calculator.payments = parseFloat($('#payments option:selected').val());
                    $('#output').html('<h4>Your Monthly Payment:</h4> <p>$' + calculator.calculate());
                }else{
                    $('#output').html('<p><strong>Please complete all the fields</strong></p>');
                }
                
            }).slideDown('fast');
            
            e.preventDefault();
        });
    },
    // Does the calculation
    calculate   : function(){
        var a = 0;
        var b = 0;
        var c = 0;
        var d = 0;
        var r = (this.APR / 12) + 1
        this.base = this.principal - this.downPayment;
            
        a = r - 1
        b = Math.pow(r, this.payments - (this.payments * 2)) - 1
        c = a/b;
        d = this.base * c
        d = Math.round((d - (d*2)) * 100) / 100;
        
        return d      
    },
    // Checks to see if the input is valid
    isValid      : function(){
        if($('#price').val() == '' || $('#downPayment').val() == '' || $('#apr').val() == ''){
            return false
        }else{
            return true
        }
    }
}


// Start
$(document).ready(function(){
    calculator.init();
});
