﻿var SelfAssessmentCalculator = function() {
    // Trys and converts the given value to a decimal    
    var ToDecimal = function(value) {
        var decimalValue;
        
        decimalValue = parseInt(value.replace(/,/g, ""));
        
        return isNaN(decimalValue) ? 0 : decimalValue;
    };
    
    // setups the text inputs marked as read only
    var SetupReadyOnlyInputs = function() {
        $(".readOnly").each(function(i) {            
            this.readOnly = "readyOnly";
        });
    };          
    
    // sums up the values of all input fields marked by the css selector
    var SumInputs = function(selector) {        
        var total = 0;
        
        $(selector).each(function(i) {
            var value = ToDecimal(this.value);
            
            // the price formatter sees everything in cents
            total = total + value;
        });
        
        return total;
    };
    
    // setup the on change event handler to kick off the calculation  
    var SetupInputChangeEventHandler = function() {
        $("input").change(function() { 
            var value = ToDecimal(this.value);
            if (value == 0) {                     
                this.value = "";
            } else {
                this.value = value;
            }
            SelfAssessmentCalculator.DoCalculation();
            SelfAssessmentCalculator.DoCalculationQuick(); 
            SelfAssessmentCalculator.FormatInput();
        });       
    };  
    
    // Helper function to update a given label  
    var UpdateTotalLabel = function(selector, value) {
        $(selector)[0].value = value;
    };  
      
    // format a money string
    var CurrencyFormatted = function (num) {
        num = num.toString().replace(/\$|\,/g,'');
        if(isNaN(num))
        num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num*100+0.50000000001);
        cents = num%100;
        num = Math.floor(num/100).toString();
        if(cents<10)
        cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
        num.substring(num.length-(4*i+3));
        return (((sign)?'':'-') + num);
    }
      
    return {
        // init the forms
        Init: function() {     
            $(".disclaimerFooter").addClass("hidden");       
            SetupReadyOnlyInputs();        
            SetupInputChangeEventHandler();
        },
        // Perform the detail calculation
        DoCalculation: function() {                        
            var debtsTotal = SumInputs(".AInput");
            var extraCostsTotal = SumInputs(".BInput");
            var houseHoldExpensesTotal = SumInputs(".CInput");
            var yearToSupport = ToDecimal($("#numberOfYear")[0].value);
            var yearToSupportTotal = houseHoldExpensesTotal * 12 * yearToSupport;
            var futureGoalTotal = SumInputs(".FutureGoal");
            var estimateOngoingIncome = SumInputs(".PartnerIncome") * 12;
            var totalExistingCover = SumInputs(".ExistingCover");
            var estimatedCover = debtsTotal + extraCostsTotal + yearToSupportTotal + futureGoalTotal;
            var remaningIncome = yearToSupport * estimateOngoingIncome;
            
            UpdateTotalLabel("#debtsTotal", debtsTotal);
            UpdateTotalLabel("#totalExtraCost", extraCostsTotal);
            UpdateTotalLabel("#totalHouseHoldExpenses", houseHoldExpensesTotal);
            UpdateTotalLabel("#totalYearsOfExpenses", yearToSupportTotal);
            UpdateTotalLabel("#totalFutureGoal", futureGoalTotal);
            UpdateTotalLabel("#totalExistingCover", totalExistingCover);

            UpdateTotalLabel("#estimatedCoverRequired", estimatedCover);
            UpdateTotalLabel("#lessExistingCover", totalExistingCover);
            UpdateTotalLabel("#lessRemainingIncome", remaningIncome);
            UpdateTotalLabel("#shortfallToBeCovered", estimatedCover - totalExistingCover - remaningIncome);
        },
        // Perform the quick calculation
        DoCalculationQuick: function() {            
            var quickPlus = SumInputs(".QuickPlus");
            var quickMinus = SumInputs(".QuickMinus");
            var houseHoldExpensesTotal = SumInputs(".TotalHouseHoldExpensesQuick");
            var yearToSupport = SumInputs(".NumberOfYearQuick");
            var yearToSupportTotal = houseHoldExpensesTotal * 12 * yearToSupport;                        
            
            UpdateTotalLabel("#totalYearsOfExpensesQuick", yearToSupportTotal);
            UpdateTotalLabel("#estimatedCoverRequiredQuick", quickPlus + yearToSupportTotal);
            UpdateTotalLabel("#shortfallToBeCoveredQuick", quickPlus + yearToSupportTotal - quickMinus);            
            
        },
        // Format the input
        FormatInput: function() {
            $(".money").each(function(i) {  
                this.value = CurrencyFormatted(this.value);
            });
        }        
    }       
}();

$(document).ready(function() {
    SelfAssessmentCalculator.Init();
});