function repaymentAmount(totalAmount, interestRate, total_payments, freq_per_year) {

    var rate = interestRate / 100 / freq_per_year;
        
    if (total_payments == 0) {
        return 0;
    } 
    total_payments = Math.floor(total_payments);
    if (interestRate == 0) {
        return totalAmount / total_payments;        
    } else {
        return (rate + rate/(Math.pow(rate + 1, total_payments)-1)) * totalAmount;
    } 
} 
function showRepaymentAmount(amount, freq_per_year) {
  var period = '';
  switch (freq_per_year) {
    case "12": period = 'monthly'; break;
    case "26": period = 'fortnightly'; break;
    case "52": period = 'weekly'; break;
  }
  $('#periodical_1').html(period);
  $('#periodical_2').html(period);
  
  $('#repayment').html(amount);
  $('#extra_repayment').html(amount + $('#extra_contribution').asNumber());
  $('#interest_saved').html('');
  
  $('#repayment').formatCurrency();
  $('#extra_repayment').formatCurrency();
  $('#interest_saved').formatCurrency();
}


/* -------------------------------------------------------------------------- */
/*  Total interest payable                                                    */
/* -------------------------------------------------------------------------- */
function totalInterest(totalAmount, interestRate, term, payments_per_year) {
  return repaymentAmount(totalAmount, interestRate, term, payments_per_year)*term - totalAmount;
}
function showTotalInterest(amount) {
  $('#total_interest').html(amount);
  $('#total_interest').formatCurrency();
}


/* -------------------------------------------------------------------------- */
/*  Principal calculation                                                     */
/* -------------------------------------------------------------------------- */
function newPrincipal(principal, interestRate, repaymentAmount, term) 
{
    var value = principal + principal * interestRate / 100 / term - repaymentAmount;
    if (value < 0) value = 0;
    return value;
}


/* -------------------------------------------------------------------------- */
/*  Interest only calculation                                                 */
/* -------------------------------------------------------------------------- */
function newInterestOnly(totalAmount, interest_only, term) {
    var value = totalAmount + interest_only * term;
    if (value < totalAmount) value = totalAmount;
    return value;
}

function interestOnly(totalAmount, interestRate, total_payments, term, freq_per_year) {
  var rate = interestRate / 100 / freq_per_year * term;
  return totalAmount * rate / term;
}
function showInterestOnly(amount) {
  $('#monthly_repayment').html(amount);
  $('#monthly_repayment').formatCurrency(); 
}


  function BaseCalculator_presentValue(interestRate, term, payments, paymentsPerYear) {
    var __reg1 = term;
    var __reg3 = payments;
    var __reg2 = undefined;
    __reg1 = Math.floor(__reg1); 
    __reg2 = interestRate / paymentsPerYear; 
    if (__reg3 == 0 || __reg1 == 0) 
    {
        return 0;
    }
    if (__reg2 == 0)    
    {
        return (0 - __reg3) * __reg1;
    }
    else 
    {
        x = Math.pow(1 + __reg2, 0 - __reg1);
        y = Math.pow(1 + __reg2, __reg1);
        return (0 - x * (y * __reg3 - __reg3)) / __reg2;
    }
}


function BaseCalculator_repaymentAmount(totalAmount, interestRate, term)
{
    var __reg1 = term;
    var __reg2 = interestRate;
    if (__reg1 == 0) 
    {
        return 0;
    }
    __reg1 = Math.floor(__reg1);
    if (__reg2 == 0) 
    {
        return totalAmount / __reg1;
    }
    else 
    {
        return totalAmount * __reg2 / (1 - Math.pow(__reg2 + 1, 0 - __reg1));
    }
}


function BorrowingPower_recalculate() {
    var totalExpenses = 
        $('#car_loan_m_repayment').asNumber() 
        + $('#total_cc_limit').asNumber() * 5 / 100 
        + $('#other_payments').asNumber() * $('#other_net_income_freq').val() / 12
        ;
        
    var totalIncome =         
        $('#salary').asNumber()*$('#salary_freq').val() + 
        $('#other_net_income').asNumber()*$('#other_net_income_freq').val();
    
    if ($('#joint_income_chb').is(':checked')) {
        var array_ = Array(14400, 17280, 20160, 23040, 25920); // joint        
        totalIncome += $('#salary2').asNumber()*$('#salary2_freq').val();
    } else {
        var array_ = Array(11400, 14280, 17160, 20040, 22920); // single
        salary2PY = 0;
    } 

    var totalIncome = totalIncome / 12;    


    var dependents = $('#dependents').val();
    if (dependents > array_.length - 1) {
        totalExpenses = totalExpenses + array_[array_.length - 1] / 12;
    } else {    
        totalExpenses = totalExpenses + array_[dependents] / 12;
    }
    return totalIncome * 85 / 100 - totalExpenses;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
/*  Output                                                                    */
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
function output() {
            var graph_total = [], graph_principal = [];
            var loan_term = $('#loan_term').val(); // x
            var step = loan_term / 12;
         
    var repayment = BorrowingPower_recalculate();
    var borrow_amount = 
        -BaseCalculator_presentValue(
            ($('#interest_rate').asNumber()+1.5)/100, 
            $('#loan_term').asNumber()*12, 
            repayment,
            12
        );
           borrow_amount = Math.floor(borrow_amount/1000)*1000; 
            
    $('#can_borrow').html(borrow_amount);
    if (borrow_amount > 0) {
      $('#div_can_borrow').css('display', 'block');
      $('#can_borrow').formatCurrency({roundToDecimalPlace:-2});
      $('#div_can_not_borrow').css('display', 'none');
    } else {
      $('#div_can_borrow').css('display', 'none');
      $('#div_can_not_borrow').css('display', 'block');
    }
            var repayment_amount = repaymentAmount(
                borrow_amount,
                $('#interest_rate').asNumber(),
                $('#loan_term').asNumber() * 12,
                12
            );
            
           repayment_amount = BaseCalculator_repaymentAmount(
           borrow_amount,
           $('#interest_rate').asNumber() / 1200,
           Math.floor($('#loan_term').asNumber() * 12)
           );
            
$('#repayment').html(repayment_amount);
if (repayment_amount > 0)
  $('#repayment').formatCurrency(); else
  $('#repayment').html('0.00');
    
            
            // *******
            // Graph
            // *******
            
                var cur_month = 0;
                var principal = borrow_amount;
                var months_remains = $('#loan_term').asNumber() * 12;
                while( months_remains >= 0) {
//alert(cur_month+repayment_amount+months_remains);
                    graph_total.push([cur_month, repayment_amount*months_remains]);
                    graph_principal.push([cur_month, principal]);
//if (cur_month==23) alert(principal);                    
                    principal = newPrincipal(
                        principal, 
                        $('#interest_rate').asNumber(), 
                        repayment_amount, 
                        12);
                    ++cur_month;
                    --months_remains;
                }


                plot1.setData([ 
                { 
                    data: graph_total,
                    lines: { show: true, steps: true }, 
                    label: "Total", 
                    color: "#6285C9" 
                }
                , { 
                    data: graph_principal,
                    lines: { show: true, steps: true }, 
                    label: "Principal"
                }
                 ]);
             
             
             
            plot1.setupGrid();
            plot1.draw();
            
            //$('#transport_registration_a').asNumber() +
            
            showTotalInterest(
                totalInterest(
                    $('#loan_amount').asNumber(),
                    $('#interest_rate').asNumber(),
                    $('#loan_term').asNumber() * $('#payment_freq').val(),
                    $('#payment_freq').val()
                )
            );

}

