﻿///<reference name="MicrosoftAjax.js"/>

var RepaymentStrategiesPage = function(tableLocationId,paymentOptionsScheduleLocation){
    RepaymentStrategiesPage.Instance = this;
    this.LoanTableLocation = $get(tableLocationId);
    this.LoanTableBuilder = new LoanTableBuilder();
    this.LoanTableBuilder.SetCustomEventFunction(function(){RepaymentStrategiesPage.Instance.SetCalculationIsValid(false);});
    this.LoanTableId;
    this.PaymentScheduleLocation = $get(paymentOptionsScheduleLocation);
    this.PaymentSchedule = new PaymentOptionsSchedule();
    this.Step1Validator = new Validator('calcStep1Validation');
    this.SetPageWrapper("repaymentStrategiesPage");
    this.FinalStep = $get("calc-calculator-step3");
    
    
    /************************************************************************/
    ///This function gets passed to this.PaymentSchedule.SetOnSelectFunction
    ///so that the Final Calculation window will appear on table select
    /*======================================================================*/
    this.FinalCalculation = function(){
        var thisFunc = arguments.callee;
        var siblingList = 
            RepaymentStrategiesPage.Instance.PaymentScheduleLocation.parentNode.getElementsByTagName('table');
        var activeList = [];
        var firstPayment = 0;
        var totalLoanCost = 0;
        
        for(var i=0; siblingList[i]; i++){
            if(siblingList[i].className == "active"){
                activeList.push(siblingList[i]);
            }
        }
        for(var i=0; activeList[i]; i++){
            var selFirstMonth = activeList[i].firstChild.nextSibling.firstChild.nextSibling.firstChild.nextSibling.firstChild.firstChild.nextSibling;
            var selTotalCost = activeList[i].firstChild.nextSibling.nextSibling.firstChild.firstChild.nextSibling.firstChild;
            var firstMonthPay = (window.ActiveXObject) ? njs.Converter.MoneyToNumber(selFirstMonth.innerText) :
                                        njs.Converter.MoneyToNumber(selFirstMonth.textContent);
            var totalPay = (window.ActiveXObject) ? njs.Converter.MoneyToNumber(selTotalCost.innerText) :
                                        njs.Converter.MoneyToNumber(selTotalCost.textContent);
            firstPayment += parseFloat(firstMonthPay);
            totalLoanCost += parseFloat(totalPay);
        }
        firstPayment = njs.Converter.NumberToMoney(firstPayment);
        totalLoanCost = njs.Converter.NumberToMoney(totalLoanCost);
        
        $get('FinalCalculationHeader').innerHTML =
            activeList.length+" of "+Math.ceil(siblingList.length/3)+" loans selected";
          
        $get('FinalCalculationSummary').innerHTML =
            "Please select one payment method from each loan group";
        
        if(activeList.length == siblingList.length/3){
            $get('FinalCalculation').style.display ='none';
            $get('FinalCalculationHeader').innerHTML = 
                "Loan Repayment Summary";
        
            $get('FinalCalculationSummary').innerHTML =
                "First Payment&nbsp;&nbsp;&nbsp;&nbsp;"+firstPayment+
                "<br/>Total Cost&nbsp;&nbsp;&nbsp;"+totalLoanCost;
        }
        $get('FinalCalculation').style.display ='block';
    }
    /*======================================================================*/
    /************************************************************************/
    
    this.PaymentSchedule.SetOnSelectFunction(this.FinalCalculation); 
    this.SetActiveNavigationLink();
}
RepaymentStrategiesPage.prototype = new CalculatorPage;
    
    
RepaymentStrategiesPage.prototype.AddLoan = function(newTableId){
    this.HideStep('FinalCalculation');
    if(RepaymentStrategiesPage.Instance.Step1Validator.Validate(document.getElementsByTagName('input'))){
        this.LoanTableId = newTableId;
        this.LoanTableBuilder.BuildTable(   this.LoanTableLocation, 
                                            this.LoanTableId, 
                                            {'Balance':'loanBalance'}, 
                                            {'Interest Rate':'interestRate'}, 
                                            {'Months to Repay':'term'}  );
        this.DisplayStep(2);
        this.SetCalculationIsValid(false);
    }
}

RepaymentStrategiesPage.prototype.AddLoanOnEnter = function(e, newTableId){
    if(this.KeyEventIsValid(e))
        RepaymentStrategiesPage.Instance.AddLoan(newTableId);
}

RepaymentStrategiesPage.prototype.Calculate = function() {
    if (!this.IsServiceAvailable) return;
    this.IsServiceAvailable = false;
    this.DisplayProcessingInContainer(this.PaymentScheduleLocation);
    RepaymentStrategiesPage.Instance.DisplayStep(3);

    var LoanPackage = LoanPackageBuilder.CreateLoanPackageFromLoanTable(this.LoanTableId, ['Balance', 'InterestRate', 'Term']);
    njs.services.Calculators.CalculateLoanPaymentOptions(LoanPackage.Loans,
                                                            this.onComplete,
                                                            this.onError);
    this.HideStep('FinalCalculation');
    this.SetCalculationIsValid(true);
}

RepaymentStrategiesPage.prototype.onComplete = function(data) {
    RepaymentStrategiesPage.Instance.IsServiceAvailable = true;        
    RepaymentStrategiesPage.Instance.ClearContainer(
        RepaymentStrategiesPage.Instance.PaymentScheduleLocation);
    
    RepaymentStrategiesPage.Instance.PaymentScheduleLocation.appendChild(    
        RepaymentStrategiesPage.Instance.
                PaymentSchedule.GetPaymentOptions(data));
                
    RepaymentStrategiesPage.Instance.
            PaymentSchedule.SetSelectable();
}  

RepaymentStrategiesPage.prototype.onError = function(){
    RepaymentStrategiesPage.Instance.ClearContainer(
        RepaymentStrategiesPage.Instance.PaymentScheduleLocation);
} 