$(document).ready(function(){
    
    
});

function CleanForm() {
        $('#auto-loan-calc input[name="alpayments"]').val('');
        
        $('#auto-loan-calc input[name="alamount"]').val(clean_numeric( $('#auto-loan-calc input[name="alamount"]').val()));
        $('#auto-loan-calc input[name="alrate"]').val(clean_numeric( $('#auto-loan-calc input[name="alrate"]').val()));
        $('#auto-loan-calc input[name="alterm"]').val(clean_numeric( $('#auto-loan-calc input[name="alterm"]').val()));
}

function CalcLoan() {
    CleanForm();
    if ( ValidateMortgageForm() ) {
        var payments;
        var principal;
        var monthly;
        
        rate = $('#auto-loan-calc input[name="alrate"]').val() / 100 / 12;
        payments = $('#auto-loan-calc input[name="alterm"]').val();
        principal = $('#auto-loan-calc input[name="alamount"]').val();
        monthly = Math.floor((principal * rate) / (1 - Math.pow(1 + rate, (-1 * payments))) * 100) / 100;

        $('#auto-loan-calc input[name="alpayments"]').val(monthly);
    }
}

function ValidateMortgageForm() {
    var result = true;
    
    $('#auto-loan-calc input').removeClass('error');
    if ( $('#auto-loan-calc input[name="alamount"]').val() == '0' ) {
        result = false;
        $('#auto-loan-calc input[name="alamount"]').addClass('error');
    }
    if ( $('#auto-loan-calc input[name="alrate"]').val() == '0' ) {
        result = false;
        $('#auto-loan-calc input[name="alrate"]').addClass('error');
    }
    if ( $('#auto-loan-calc input[name="alterm"]').val() == '0' ) {
        result = false;
        $('#auto-loan-calc input[name="alterm"]').addClass('error');
    }
    
    return result;
}

function clean_numeric(value) {
     var clean = value.replace(/[^0-9.]/g,'');
     
     if ( clean.length == 0 ) clean = '0';

     return clean;
}

function is_numeric(value) {
    var reg = /^([0-9.$]{5})$/;
    
    return reg.test(value); 
}