//
function hideShowYearRromo(hide) {

    if (hide == true) {

        $('#with_interest').attr("disabled", true);
        $('#no_interest').attr('checked', true);
    }

    else {

        $('#with_interest').attr("disabled", false);
        $('#no_interest').attr('checked', false);
    }
}




function calc(amount, interest, term) {

    var rm = interest / 12;
    var T_Price = (amount * rm) / (1 - Math.pow((1 + rm), (-12 * term)));
    T_Price = (parseInt(T_Price * 100)) / 100;
    return T_Price;
}

function clear_years() {
    var mySelect = document.getElementById('years'); // your form
    var counter = 0;

    for (var loop = 0; loop < mySelect.options.length; loop++) {
        if (loop > 19) {
            mySelect.options[loop] = null; // remove the option
            loop--;
        }
    }
}

function add_years(count) {
    clear_years();

    var select = document.getElementById('years');
    var text = select.options[1].text.substring(1);
    var start = select.options.length;
    var end = select.options.length + count;
    //    alert(text);
    //    return;

    for (var x = start + 1; x <= end; x++) {
        var option = document.createElement('option');
        option.appendChild(document.createTextNode(x + ' ' + text));
        option.setAttribute('value', x * 12);

        select.appendChild(option);
    }
}

function calculateBG() {

    //$(document).ready(function() {

    // $('#credit_type1').click(function() {
    //$('#Year1')
    //$('#calcType1')
    // });

    //$('#credit_type2').click(function() {
    //$('#Year1')
    // $('#calcType1')
    // });

    // $('#credit_type3').click(function() {
    // $('#Year1')
    // $('#Year2')
    // });


    // $('#calc_mortageBGN').click(function() {

    // $('#result_mortageBGN').show();




    //get language
    var urlArr = window.location.href.split("/");
    var bg = false;
    for (var i = 0; i < urlArr.length; i++) {
        if (urlArr[i].toLowerCase() == 'bg-BG'.toLowerCase()) {
            bg = true;
            break;
        }
    }

    //localizing
    var msg1;
    var msg2;
    var msg3;
    var msg4;
    var msg5;
    var msg6;
    if (bg) {

        msg1 = "Моля, най-напред изберете тип на кредита.";
        msg2 = "Моля, най-напред изберете кредит с промоционален период 1г.\nили кредит без промоционален период.";
        msg3 = "Моля, най-напред изберете промоционален период 1г.\nили кредит без промоционален период.";
        msg4 = "Максималният размер на кредита е 500 000 лева!";
        msg5 = "Минималният размер на кредита е 15 000 лева!";
        msg6 = "Моля, въведете сума.";
        msg7 = "Максималният размер на кредита е 200 000 лева!";

    }
    else { // no english page for this calc - if such a page ready - localize english version
        msg1 = "ee";
        msg2 = "oo";
        msg3 = "aa";
        msg4 = "vv";
        msg5 = "zz";
        msg6 = "ff";
    }


    //initialize values from DB (available in hidden fields in the page)
    var interestFirstFlatDB = $('#txtPurchasePercentFirstFlatBGN').attr("value") / 100;

    var interest1DB = $('#txtPurchasePercentBGN').attr("value") / 100;
    var interest2DB = $('#txtRepairPercentBGN').attr("value") / 100;
    var interest3DB = $('#txtRepairFittingPercentBGN').attr("value") / 100;

    var tax1 = $('#txtApplicationFeeBGN').attr("value");

    var creditTax1 = $('#txtPurchaseFeeBGN').attr("value") / 100;
    var creditTax2 = $('#txtRepairFeeBGN').attr("value") / 100;
    var creditTax3 = $('#txtRepairFeeBGN').attr("value") / 100;

    var min1 = $('#txtCreditBGNMin').attr("value");
    var max1 = $('#txtCreditBGNMax').attr("value");
    var max2 = $('#txtCreditFittingBGNMax').attr("value");


    ///////////////////////////////////UBB's logic refactored///////////////////////////////////////////

    var called = true;
    var term;
    var interest1;
    var interest2;
    var promoTerm;
    var amount;
    var creditTax; //Taksa 2 za upravlenie
    var requestTax = tax1; //ednokratna taksa za molba (Taksa 1)


    //checks the selected credit type
    var isTypeFirstFlat = $('#credit_type_firstFlatBG').is(':checked');
    var isType1 = $('#credit_type1').is(':checked');
    var isType2 = $('#credit_type2').is(':checked');
    var isType3 = $('#credit_type5').is(':checked');

    //var isType4 = $('#credit_type4').is(':checked');


    //checks the selected with/no interest
    var withInterest = $('#with_interest').is(':checked');
    var noInterest = $('#no_interest').is(':checked');


    // Set max value for credit & alert!

    if (isType1) { interest2 = interest1DB; } //- purchase whole period
    else if (isTypeFirstFlat) { interest2 = interestFirstFlatDB }
    else if (isType2) { interest2 = interest2DB; }  //-repair whole period
    else if (isType3) { interest3 = interest3DB; }
    else { $('#result_mortageBGN').hide(); $('#result_mortageBGN_label').hide(); alert(msg1); return false; }


    if (isTypeFirstFlat) {
        if (withInterest) { interest1 = 0.07; interest2 = 0.084; promoTerm = 1; creditTax = 0.015; $('#result_mortage_firstyear').show(); } //-1 year
        else if (noInterest) { interest1 = 0; interest2 = interestFirstFlatDB; promoTerm = 0; creditTax = creditTax1 } //- whole period
        else { $('#result_mortageBGN').hide(); $('#result_mortageBGN_label').hide(); alert(msg2); return false; }
    }
    else if (isType1) { //-purchase
        if (withInterest) { interest1 = 0.07; interest2 = 0.084; promoTerm = 1; creditTax = 0.015 } //-1 year
        else if (noInterest) { interest1 = 0; interest2 = interest1DB; promoTerm = 0; creditTax = creditTax1 } //- whole period
        else { $('#result_mortageBGN').hide(); $('#result_mortageBGN_label').hide(); alert(msg2); return false; }
    }
    else if (isType2) { //-repair
        if (withInterest) { interest1 = 0; interest2 = 0.0950; promoTerm = 0; creditTax = 0.015 } //-1 year , not available for now, works as whole period
        else if (noInterest) { interest1 = 0; interest2 = interest2DB; promoTerm = 0; creditTax = creditTax2 } //- whole period
        else { $('#result_mortageBGN').hide(); $('#result_mortageBGN_label').hide(); alert(msg3); return false; }
    }
    else if (isType3) { //-repair&fitting
        if (withInterest) { interest1 = 0; interest2 = 0.0950; promoTerm = 0; creditTax = 0.015 } //-1 year , not available for now, works as whole period
        else if (noInterest) { interest1 = 0; interest2 = interest3DB; promoTerm = 0; creditTax = creditTax3 } //- whole period
        else { $('#result_mortageBGN').hide(); $('#result_mortageBGN_label').hide(); alert(msg3); return false; }
    }


    // Expenses - wrong action
    //interest1 += 0.015;
    //interest2 += 0.015;

    //gets the entered amount
    amount = parseInt($('#mortage_amount').attr('value'));

    if (isNaN(amount) || amount == 0) {
        $('#result_mortageBGN').hide(); $('#result_mortageBGN_label').hide(); alert(msg6);
        return;
    }

    //gets the selected year and sets the term
    var months = $('#years').val();
    term = months / 12;

    // check  if it is the third radion button
    if (isType3) {
        max1 = max2;
        msg4 = msg7;
    }

    if (amount > max1) { $('#result_mortageEUR').hide(); alert(msg4); }
    else if (amount < min1) { $('#result_mortageEUR').hide(); alert(msg5); }
    else {
        if (months <= 420) {
            // If there is a promo... 
            if (promoTerm > 0) {
                // During Promo Period
                var T_Price = calc(amount, interest1, term);

                //set value
                $('#T_Price').text(T_Price);

                // Number of months after Promo Period
                term2 = term - promoTerm;

                // Payments, made during Promo Period
                loanReminder = amount;
                mainTotal = 0;
                for (i = 1; i <= (promoTerm * 12); i++) {
                    iPayment = (loanReminder - mainTotal) * interest1 / 12;
                    mainPayment = T_Price - iPayment;
                    mainTotal += mainPayment;
                }

                tmp = amount - mainTotal;
            }

            else { //-no promo... for now always here!!!

                //calc annually percent of axpences
                var ape = calcAnnuallyPercentExpences(amount, creditTax, requestTax, months, interest2);
                //$('#T_percent').text(ape);

                term2 = term;
                tmp = amount;
                var T_Price = "0.00";

                //set value
                $('#T_Price').text(T_Price);

            }

            if (term2 > 0) {
                var T_Price2 = calc(tmp, interest2, term2);

                //set value
                $('#T_Price2').text(T_Price2);
            }

            else {
                $('#T_Price2').text('0');
            }

        }


        $('#result_mortage').show();
        $('#result_mortage_label').show();

        changeCurrency('b');
    }

    ///////////////////////////////////UBB's logic refactored///////////////////////////////////////////


    //(ГПР - годишен процент разходи)
    function calcAnnuallyPercentExpences(amount, creditTax, requestTax, months, interest) {

        var p2A = 0.32; //??
        var okA = 0;
        var discountA = new Array;
        var vnoskaA;
        var p3A;
        var p1A = interest;

        var netCredit = amount - amount * creditTax - requestTax; // added requestTax
        vnoskaA = (amount * (interest / 12)) / (1 - Math.pow((1 + interest / 12), (-months)));

        // Binary search
        while (okA == 0) {

            p3A = (p1A + p2A) / 2;
            sumaA = 0;

            for (i = 1; i <= months; i++) {
                discountA[i] = vnoskaA / Math.pow((1 + p3A), (i / 12));

                sumaA += discountA[i];
            }

            sumaA = (parseInt(sumaA * 10000)) / 10000;

            if (netCredit > sumaA) { p2A = p3A; } 	// namaljava gornata granica
            if (netCredit < sumaA) { p1A = p3A; } // uvelichava dolnata granica

            if (netCredit == sumaA) { okA = 1; }
        }

        var result = (parseInt(p3A * 10000)) / 100;

        return result;
    }

}

function changeCurrency(type) {

    if (type == 'b') {
        $('#currency_T_EUR').hide();
        $('#currency_T2_EUR').hide();
        $('#currency_T_BGN').show();
        $('#currency_T2_BGN').show();
    }
    else {
        $('#currency_T_BGN').hide();
        $('#currency_T2_BGN').hide();
        $('#currency_T_EUR').show();
        $('#currency_T2_EUR').show();
    }

}

function hideResult() {

    $('#result_mortage').hide();
    $('#result_mortage_label').hide();
}


$(document).ready(function() {

    $('#credit_type_firstFlatBG').click(function() {

        $('#with_interest').attr("checked", "true")
        resetSumLabels();
        $('#calcType2').hide();
        $('#calcType1').show();
        hideResult();
        add_years(15);
    });

    $('#credit_type1').click(function() {

        $('#no_interest').attr("checked", "true")
        resetSumLabels();
        $('#calcType2').hide();
        $('#calcType1').show();
        hideResult();
        add_years(15);
    });

    $('#credit_type2').click(function() {

        $('#no_interest').attr("checked", "true")
        resetSumLabels();
        $('#calcType2').hide();
        $('#calcType1').show();
        hideResult();
        add_years(15);
    });

    $('#credit_type3').click(function() {

        $('#no_interest').attr("checked", "true")
        resetSumLabels();
        $('#calcType1').hide();
        $('#calcType2').show();
        hideResult();
        clear_years();
    });

    if ($('#credit_type5')) {
        $('#credit_type5').click(function() {

            $('#no_interest').attr("checked", "true")
            resetSumLabels();
            $('#calcType2').show();
            $('#calcType1').hide()

            //$('#credit_type3').hide();
            //$('#credit_type4').show();
            hideResult();
            clear_years();
        });
    }


    $('#calc_mortage').click(function() {

        $('#result_mortage_firstyear').hide();
    
        if ($('#credit_type_firstFlatBG').is(':checked') || $('#credit_type1').is(':checked') || $('#credit_type2').is(':checked') || $('#credit_type5').is(':checked')) {
            calculateBG();
        }

        if ($('#credit_type_firstFlatEU').is(':checked') || $('#credit_type3').is(':checked') || $('#credit_type4').is(':checked') || $('#credit_type6').is(':checked') || $('#credit_typeEU1').is(':checked') || $('#credit_typeEU2').is(':checked') || $('#credit_typeEU3').is(':checked') || $('#credit_typeEU4').is(':checked')) {
            calculateEU();
        }

    });
});



