﻿var HousingCostModelDefaultValues = new function () {
    this.price = '';
    this.deposit = '';

    this.bottomLoanInterestFee = '';
    this.bottomLoan2InterestFee = '';
    this.topLoanInterestFee = '';
    this.bottomLoanRepaymentYear = '';
    this.topLoanRepaymentYear = '';

    this.electricity = '';
    this.sweeping = '';
    this.maintenance = '';
    this.insurance = '';
    this.sanitation = '';
    this.heating = '';
    this.waterSewage = '';
    this.jointPropertyFee = '';
    this.shoveling = '';
    this.other = '';


    this.operatingcosts = '';

    this.init = function() {
        this.price = $('.txt_price').val();
        this.deposit = $('.txt_deposit').val();
        this.bottomLoanInterestFee = $('.txt_fee_bottomLoanIntrestFee').val();
        this.bottomLoan2InterestFee = $('.txt_fee_bottomLoanIntrestFee_2').val();
        this.topLoanInterestFee = $('.txt_fee_topLoanInterestFee').val();
        this.electricity = $('.txt_electricity').val();
        this.sweeping = $('.txt_sweeping').val();
        this.maintenance = $('.txt_maintenance').val();
        this.insurance = $('.txt_insurance').val();
        this.sanitation = $('.txt_sanitation').val();
        this.heating = $('.txt_heating').val();
        this.waterSewage = $('.txt_waterSewage').val();
        this.jointPropertyFee = $('.txt_jointPropertyFee').val();
        this.shoveling = $('.txt_shoveling').val();
        this.other = $('.txt_other').val();

        this.operatingcosts = $('.lbl_sumDrift').html();
    };

    this.resetPriceDepositValues = function () {
        $('.txt_price').val(this.price);
        $('.txt_deposit').val(this.deposit);

        $('#price-slider').slider('option', 'value', parseInt(this.price.replace(/ /g, '')));
        $('#deposit-slider').slider('option', 'value', parseInt(this.deposit.replace(/ /g, '')));

        CurrentHousingCostModel.updateValues();
    };


    this.resetInterestValues = function () {
        $('.txt_fee_bottomLoanIntrestFee').val(this.bottomLoanInterestFee);
        $('.txt_fee_topLoanInterestFee').val(this.topLoanInterestFee);
        $('.txt_fee_bottomLoanIntrestFee_2').val(this.bottomLoan2InterestFee);

        var bottomLoanRepaymentDropDown = $('.bottomLoanRepayment');
        bottomLoanRepaymentDropDown.children().removeClass('selected');
        bottomLoanRepaymentDropDown.children().first().addClass('selected');
        bottomLoanRepaymentDropDown.prev().html($(bottomLoanRepaymentDropDown).children().first().find('a').html());

        var bottomLoan2RepaymentDropDown = $('.bottomLoanRepayment2');
        bottomLoan2RepaymentDropDown.children().removeClass('selected');
        bottomLoan2RepaymentDropDown.children().first().addClass('selected');
        bottomLoan2RepaymentDropDown.prev().html($(bottomLoan2RepaymentDropDown).children().first().find('a').html());

        var topLoanRepaymentDropDown = $('.topLoanRepayment');
        topLoanRepaymentDropDown.children().removeClass('selected');
        topLoanRepaymentDropDown.children().first().addClass('selected');
        topLoanRepaymentDropDown.prev().html($(topLoanRepaymentDropDown).children().first().find('a').html());

        CurrentHousingCostModel.updateValues();
    };

    this.resetOperatingCostsValues = function () {
        $('.txt_electricity').val(this.electricity);
        $('.txt_sweeping').val(this.sweeping);
        $('.txt_maintenance').val(this.maintenance);
        $('.txt_shoveling').val(this.shoveling);
        $('.txt_insurance').val(this.insurance);
        $('.txt_sanitation').val(this.sanitation);
        $('.txt_heating').val(this.heating);
        $('.txt_waterSewage').val(this.waterSewage);
        $('.txt_jointPropertyFee').val(this.jointPropertyFee);
        $('.txt_other').val(this.other);
        $('.lbl_sumDrift').html(this.operatingcosts);
        $('.lbl_month_drift').html(this.operatingcosts);


        CurrentHousingCostModel.updateValues();
    };

};


var CurrentHousingCostModel = new function () {
    this.objectId = '';
    this.price = 0;
    this.deposit = 0;

    this.bottomLoan = 0;
    this.bottomLoan2 = 0;
    this.topLoan = 0;
    this.sumLoan = 0;
    this.bottomLoanInterestFee = 0;
    this.bottomLoan2InterestFee = 0;
    this.topLoanInterestFee = 0;
    this.bottomLoanRepaymentMonth = 0;
    this.bottomLoan2RepaymentMonth = 0;
    this.topLoanRepaymentMonth = 0;

    this.electricity = 0;
    this.sweeping = 0;
    this.maintenance = 0;
    this.insurance = 0;
    this.sanitation = 0;
    this.heating = 0;
    this.waterSewage = 0;
    this.jointPropertyFee = 0;
    this.shoveling = 0;
    this.other = 0;

    this.month_interestFee = 0;
    this.month_repayment = 0;
    this.month_drift = 0;
    this.month_monthlyFee = 0;
    this.month_propertyFee = 0;
    this.beforeTaxReduction = 0;
    this.taxreduction = 0;
    this.costs = 0;

    this.borrowingRequirement = 0;

    this.Init = function (objectId, price) {
        this.objectId = objectId;
        this.price = price;
    };

    this.getCalculateAbleValues = function () {
        this.price = this.getPropertyValue('.txt_price');
        this.deposit = this.getPropertyValue('.txt_deposit');

        this.bottomLoan = parseInt($('.lbl_fee_bottomloan').html().replace(/ /g, ''));
        this.bottomLoan2 = parseInt($('.lbl_fee_bottomloan_2').html().replace(/ /g, ''));
        this.topLoan = parseInt($('.lbl_fee_toploan').html().replace(/ /g, ''));
        this.sumLoan = parseInt($('.lbl_fee_sumLoan').html().replace(/ /g, ''));
        this.bottomLoanInterestFee = parseFloat($('.txt_fee_bottomLoanIntrestFee').val().replace(/ /g, '') == '' ? 0 : $('.txt_fee_bottomLoanIntrestFee').val().replace(/ /g, '').replace(',', '.')) / 100;
        this.bottomLoan2InterestFee = parseFloat($('.txt_fee_bottomLoanIntrestFee_2').val().replace(/ /g, '') == '' ? 0 : $('.txt_fee_bottomLoanIntrestFee_2').val().replace(/ /g, '').replace(',', '.')) / 100;
        this.topLoanInterestFee = parseFloat($('.txt_fee_topLoanInterestFee').val().replace(/ /g, '') == '' ? 0 : $('.txt_fee_topLoanInterestFee').val().replace(/ /g, '').replace(',', '.')) / 100;

        this.bottomLoanRepaymentMonth = (parseInt($('.bottomLoanRepayment li.selected').find('a').attr('rel')) * 12);
        this.bottomLoan2RepaymentMonth = (parseInt($('.bottomLoanRepayment2 li.selected').find('a').attr('rel')) * 12);
        this.topLoanRepaymentMonth = (parseInt($('.topLoanRepayment li.selected').find('a').attr('rel')) * 12);

        this.electricity = this.getPropertyValue('.txt_electricity');
        this.sweeping = this.getPropertyValue('.txt_sweeping');
        this.maintenance = this.getPropertyValue('.txt_maintenance');
        this.sanitation = this.getPropertyValue('.txt_sanitation');
        this.insurance = this.getPropertyValue('.txt_insurance');
        this.heating = this.getPropertyValue('.txt_heating');
        this.waterSewage = this.getPropertyValue('.txt_waterSewage');
        this.jointPropertyFee = this.getPropertyValue('.txt_jointPropertyFee');
        this.shoveling = this.getPropertyValue('.txt_shoveling');
        this.other = this.getPropertyValue('.txt_other');

        this.borrowingRequirement = this.price - this.deposit > 0 ? this.price - this.deposit : 0;
    };

    this.getCalculateAbleMonthValues = function () {
        this.month_interestFee = this.getPropertyValue('.lbl_month_interestFee');
        this.month_repayment = this.getPropertyValue('.lbl_month_repayment');
        this.month_drift = this.getPropertyValue('.lbl_month_drift');
        this.month_monthlyFee = this.getPropertyValue('.lbl_month_monthlyFee');
        this.month_propertyFee = this.getPropertyValue('.lbl_month_propertyFee');
        this.beforeTaxReduction = this.getPropertyValue('.lbl_beforeTaxReduction');
        this.taxreduction = this.getPropertyValue('.lbl_taxreduction');
        this.costs = this.getPropertyValue('.lbl_costs');
    };

    this.updateHousingCost = function () {
        this.getCalculateAbleValues();
        var sum = this.electricity + this.sweeping + this.maintenance + this.insurance + this.sanitation + this.heating + this.waterSewage + this.jointPropertyFee + this.shoveling + this.other;
        $('.lbl_sumDrift').html(addSpacing(sum));
        $('.lbl_month_drift').html(addSpacing(sum));
    };


    this.updateBottomTopLoan = function () {
        var bottomLoan = this.calculateBottomLoan(this.borrowingRequirement, this.price);
        var bottomLoan2 = this.calculateBottomLoan2(this.borrowingRequirement, this.price, bottomLoan);

        $('.lbl_fee_bottomloan').html(addSpacing(Math.round(bottomLoan)));
        $('.lbl_fee_bottomloan_2').html(addSpacing(Math.round(bottomLoan2)));
        $('.lbl_fee_toploan').html(addSpacing(Math.round(this.borrowingRequirement - bottomLoan - bottomLoan2)));
        $('.lbl_fee_sumLoan').html(addSpacing(this.borrowingRequirement));
    };

    this.updateMonthlyInterestFee = function () {
        this.getCalculateAbleValues();
        var topFee = (this.topLoan * this.topLoanInterestFee) / 12;
        var bottomFee = (this.bottomLoan * this.bottomLoanInterestFee) / 12;
        var bottom2Fee = (this.bottomLoan2 * this.bottomLoan2InterestFee) / 12;


        $('.lbl_fee_bottomLoanCost').html(addSpacing(Math.round(bottomFee)));
        $('.lbl_fee_bottomLoanCost_2').html(addSpacing(Math.round(bottom2Fee)));
        $('.lbl_fee_topLoanCost').html(addSpacing(Math.round(topFee)));

        $('.lbl_fee_costs').html(addSpacing(Math.round(topFee) + Math.round(bottomFee + Math.round(bottom2Fee))));
        $('.lbl_month_interestFee').html(addSpacing(Math.round(topFee) + Math.round(bottomFee) + Math.round(bottom2Fee)));
    };

    this.updataLoanRepayment = function () {
        this.getCalculateAbleValues();
        var topLoanRepayment = Math.round(this.topLoan / this.topLoanRepaymentMonth);
        var bottomLoanRepayment = this.bottomLoanRepaymentMonth != 0 ? Math.round(this.bottomLoan / this.bottomLoanRepaymentMonth) : 0;
        var bottomLoanRepayment2 = this.bottomLoan2RepaymentMonth != 0 ? Math.round(this.bottomLoan2 / this.bottomLoan2RepaymentMonth) : 0;
        $('.lbl_fee_bottomLoanRepayment').html(addSpacing(bottomLoanRepayment));
        $('.lbl_fee_bottomLoanRepayment_2').html(addSpacing(bottomLoanRepayment2));
        $('.lbl_fee_topLoanRepayment').html(addSpacing(topLoanRepayment));
        $('.lbl_fee_totalRepayment').html(addSpacing(bottomLoanRepayment + bottomLoanRepayment2 + topLoanRepayment));
        $('.lbl_month_repayment').html(addSpacing(bottomLoanRepayment + bottomLoanRepayment2 + topLoanRepayment));
    };

    this.updateTaxReduction = function () {
        this.getCalculateAbleValues();
        var bottomLoan = this.calculateBottomLoan(this.borrowingRequirement, this.price);
        var bottomLoan2 = this.calculateBottomLoan2(this.borrowingRequirement, this.price, bottomLoan);
        var topLoan = this.borrowingRequirement - bottomLoan - bottomLoan2;

        var taxReduction = this.calculateTaxReduction(bottomLoan, bottomLoan2, topLoan);
        $('.lbl_taxreduction').html(addSpacing(taxReduction));
    };


    this.getHousingCost = function () {
        this.getCalculateAbleValues();

        $.ajax({
            type: 'POST',
            url: '/Templates/WebMethods/HousingCosts.asmx/GetHousingCostsLarge',
            data: '{ "objectid" : "' + this.objectId +
            '", "price" : ' + this.price +
            ', "deposit" : ' + this.deposit +
            ', "interestRate" : ' + this.bottomLoanInterestFee +
            ', "topInterestRate" : ' + this.topLoanInterestFee +
            ', "electricity" : ' + this.electricity * 12 +
            ', "heating" : ' + this.heating * 12 +
            ', "maintenance" : ' + this.maintenance * 12 +
            ', "insurance" : ' + this.insurance * 12 +
            ', "jointPropertyFee" : ' + this.jointPropertyFee * 12 +
            ', "sweeping" : ' + this.sweeping * 12 +
            ', "shoveling" : ' + this.shoveling * 12 +
            ', "sanitation" : ' + this.sanitation * 12 +
            ', "waterSewage" : ' + this.waterSewage * 12 +
            ', "other" : ' + this.other * 12 + '}',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            async: false,
            success: function (msg) {
                $('lbl_costs').html(addSpacing(msg.d));
            },
            error: function (msg, textStatus, errorThrown) {
                $('lbl_costs').html(msg.d + ' ' + textStatus);
            }
        });
    };


    //Helper methods
    this.calculateBottomLoan = function (borrowingRequirement, price) {
        var maxBottomLoan = 0.75;
        if (borrowingRequirement > price * maxBottomLoan)
            return price * maxBottomLoan;
        return Math.round(borrowingRequirement);
    };

    this.calculateBottomLoan2 = function (borrowingRequirement, price, bottomLoan) {
        var maxBottomLoan = 0.75;
        var bottomLoan2 = 0.10;

        return borrowingRequirement > price * (maxBottomLoan + bottomLoan2)
            ? price * bottomLoan2
            : borrowingRequirement - bottomLoan;
    };


    this.getPropertyValue = function (className) {
        var items = $(className);
        if (items.length <= 0) {
            return 0;
        }
        var func = items.filter(":input").length > 0 ? "val" : "html";
        var value = $(className)[func]().replace(/ /g, '');
        if (value == '' || value == '-') {
            value = 0;
        }
        return parseInt(value);
    };

    this.calculateTaxReduction = function (bottomLoan, bottomLoan2, topLoan) {
        var yearlyInterestRate = bottomLoan * this.bottomLoanInterestFee + bottomLoan2 * this.bottomLoan2InterestFee + topLoan * this.topLoanInterestFee;
        var monthlyTaxReduction;
        if (yearlyInterestRate < 200000) {
            monthlyTaxReduction = (yearlyInterestRate * 0.3) / 12;
        } else {
            monthlyTaxReduction = (((yearlyInterestRate - 200000) * 0.21) + (200000 * 0.3)) / 12;
        }
        return Math.round(monthlyTaxReduction);
    };

    //calculates new monthly cost based on the current values. Values need to be set before this method is called
    this.calculateNewCost = function () {
        this.getCalculateAbleMonthValues();
        var sum = this.month_interestFee + this.month_repayment + this.month_drift + this.month_monthlyFee + this.month_propertyFee;
        $('.lbl_beforeTaxReduction').html(addSpacing(sum));
        $('.lbl_costs').html(addSpacing(sum - this.taxreduction));

        $('.lbl_caCosts').html(addSpacing(roundToNearestHundredth(sum - this.taxreduction)));

        $('.info.general').html('Beräkningen är generell och utgår från simulerad belåning och kostnader.');
    };

    this.updateValues = function () {
        CurrentHousingCostModel.getHousingCost();
        CurrentHousingCostModel.updateBottomTopLoan();
        CurrentHousingCostModel.updateMonthlyInterestFee();
        CurrentHousingCostModel.updataLoanRepayment();
        CurrentHousingCostModel.updateTaxReduction();
        CurrentHousingCostModel.calculateNewCost();
    };
};


var HousingCostMiniModelDefaultValues = new function() {
    this.price = '';
    this.deposit = '';

    this.Init = function() {
        this.price = $('.txt_price_mini').val();
        this.deposit = $('.txt_deposit_mini').val();
    };

    this.resetPriceDepositValues = function() {
        $('.txt_price_mini').val(this.price);
        $('.txt_deposit_mini').val(this.deposit);

        $('#price-slider-mini').slider('option', 'value', parseInt(this.price.replace( / /g , '')));
        $('#deposit-slider-mini').slider('option', 'value', parseInt(this.deposit.replace( / /g , '')));

        CurrentHousingCostMiniModel.getHousingCostMini();
    };
};


var CurrentHousingCostMiniModel = new function() {
    this.objectId = '';
    this.price = 0;
    this.deposit = 0;

    this.Init = function(objectId, price) {
        this.objectId = objectId;
        this.price = price;
    };

    this.getHousingCostMini = function() {
        var price = CurrentHousingCostModel.getPropertyValue('.txt_price_mini');
        var deposit = CurrentHousingCostModel.getPropertyValue('.txt_deposit_mini');

        $.ajax({
            type: 'POST',
            url: '/Templates/WebMethods/HousingCosts.asmx/GetHousingCostsMini',
            data: '{ "objectid" : "' + this.objectId +
            '", "price" : ' + price +
            ', "deposit" : ' + deposit + ' }',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            async: false,
            success: function(msg) {
                $('.lbl_monthlyCost').html(addSpacing(roundToNearestHundredth(msg.d)));
                $('.info.general-mini').html('Beräkningen är generell och utgår från simulerad belåning och kostnader.');
            },
            error: function(msg, textStatus, errorThrown) {
                $('.lbl_monthlyCost').html(msg.d + ' ' + textStatus);
            }
        });
    };
};

function roundToNearestHundredth(number) {
    return (Math.ceil(number / 100.0)) * 100;
}

function IsValidKeyPress(key) {
    if (key == 46
            || key == 8
            || (key >= 48 && key <= 57)
            || (key >= 96 && key <= 105))
        return true;
    else
        return false;
}

// Spacing for numbers > 999
function addSpacing(nStr) {
    nStr += '';
    nStr = nStr.replace(/ /g,"");
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ' ' + '$2');
    }    
    return x1 + x2;
}


function InitClearButtons() {
    $('.clearPrice').click(function (event) {
        event.preventDefault();
        HousingCostModelDefaultValues.resetPriceDepositValues();
    });
    $('.clearInterest').click(function (event) {
        event.preventDefault();
        HousingCostModelDefaultValues.resetInterestValues();
    });
    $('.clearOperating').click(function (event) {
        event.preventDefault();
        HousingCostModelDefaultValues.resetOperatingCostsValues();
    });
}


// Events for Dialog/HousingCosts.ascx
function InitializeEvents(objectId, price) {
    InitClearButtons();
    $('.print').click(function () {
        $('body').attr('id', 'printHousingCost');
        window.print();    
        setTimeout(function() {
            $('body').removeAttr('id');
        }, 1000);
       
    });
    
    $('#lightbox-1 input').keyup(function (e) {
        if (IsValidKeyPress(e.keyCode)) {
            $(this).val(addSpacing($(this).val()));
        }
        else {
            event.preventDefault();
        }
    });

    $('#lightbox-1 input').focus(function () {
        $(this).select();
    });

    $('.price_deposit').keyup(function (event) {
        if (IsValidKeyPress(event.keyCode)) {
            CurrentHousingCostModel.updateValues();
            $(this).parent().next().slider('option', 'value', parseInt($(this).val().replace(/ /g, '')));
        }
        else {
            event.preventDefault();
        }
    });


    $('.housingCostsInterestFee').keyup(function(event) {
        if (IsValidKeyPress(event.keyCode)) {
            CurrentHousingCostModel.updateMonthlyInterestFee();
            CurrentHousingCostModel.updateTaxReduction();
            CurrentHousingCostModel.calculateNewCost();
        }
        else {
            event.preventDefault();
        }          
    });
      
    $('.housingCostsOperatingCost').keyup(function(event){
        if (IsValidKeyPress(event.keyCode)) {
            CurrentHousingCostModel.updateHousingCost();
            CurrentHousingCostModel.calculateNewCost();
        }
        else {
            event.preventDefault();
        }          
    });


    $('#price-slider').slider({
        range: "min",
        value: price,
        min: price > 200000 ? price - 200000 : 0,
        max: Math.round(price * 1.4),
        step: 25000,
        animate: true,
        slide: function (event, ui) {
            $("#price-slider").slider(ui.value);
            $('.txt_price').val(addSpacing(ui.value));
            CurrentHousingCostModel.updateValues();  
        }
    });


    $('#deposit-slider').slider({
        range: "min",
        value: $('.txt_deposit').val().replace(/ /g, ''),
        min: 0,
        max: price,
        step: 25000,
        animate: true,
        slide: function (event, ui) {
            $("#deposit-slider").slider(ui.value);
            $('.txt_deposit').val(addSpacing(ui.value));
            CurrentHousingCostModel.updateValues();
        }
    });


    $('.dropdowns li').click(function (e) {
        $(this).parent().prev().html($(this).find('a').html());
        $(this).parent().children().removeClass('selected');
        $(this).addClass('selected');
        $(this).parent().slideToggle('fast');
        CurrentHousingCostModel.updataLoanRepayment();
        CurrentHousingCostModel.calculateNewCost();
        e.preventDefault();
    }); 

    $('.dropdowns_head').click(function (e) {
        $(this).next().slideToggle('fast');
        $(this).addClass('expanded');
        ActivateParentClickEvent(e);
    });    
}

function ActivateParentClickEvent(e) {
    var dropdowns = $('.expanded');
    for (var i = 0; i < dropdowns.length; i++) {
        var dropdown = dropdowns[i];
        if (dropdown !== e.target) {
            $(dropdown).removeClass('expanded');
            $(dropdown).next().hide();
        }
    }

    e.stopPropagation();
    $('.popup-holder').one("click", function () {
        $('.bottomLoanRepayment').hide('fast');
        $('.bottomLoanRepayment2').hide('fast');
        $('.topLoanRepayment').hide('fast');
    });
}


function InitializeMiniEvents(objectId, price){
    $('.clearMini').click(function (event) {
        event.preventDefault();
        HousingCostMiniModelDefaultValues.resetPriceDepositValues();
    });

    $('.txt_price_mini').keyup(function (event) {
        if (IsValidKeyPress(event.keyCode)) {
            CurrentHousingCostMiniModel.getHousingCostMini();
            $("#price-slider-mini").slider('option', 'value', parseInt($(this).val()));
        }
        else {
            event.preventDefault();
        }
    });

    $('.txt_deposit_mini').keyup(function (event) {
        if (IsValidKeyPress(event.keyCode)) {
            CurrentHousingCostMiniModel.getHousingCostMini();
            $("#deposit-slider-mini").slider('option', 'value', parseInt($(this).val()));
        }
        else {
            event.preventDefault();
        }

    });


    $( "#price-slider-mini" ).slider({			
        range: "min",			
        value: price,
        min: price > 200000 ? price - 200000 : 0,			
        max: Math.round(price*1.4),
        step: 25000,
        animate: true,	
        slide: function( event, ui ) {				
            $("#price-slider-mini").slider(ui.value);
            $('.txt_price_mini').val(addSpacing(ui.value));
            CurrentHousingCostMiniModel.getHousingCostMini();           		
        }		
    });		
      

    $("#deposit-slider-mini").slider({
        range: "min",
        value: $('.txt_deposit_mini').val().replace(/ /g, ''),
        min: 0,
        max: price,
        step: 25000,
        animate: true,
        slide: function (event, ui) {
            $("#deposit-slider-mini").slider(ui.value);               
            $('.txt_deposit_mini').val(addSpacing(ui.value));
            CurrentHousingCostMiniModel.getHousingCostMini();             
        }
     });
}
