razsor.definePackage("razsor.finance");

var FinanceFieldFormatter = {};

FinanceFieldFormatter.formatAmount = function(currencySymbol, amount) {
    if (amount === "-") {
        return "0";
    }
    return currencySymbol + amount;
};

FinanceFieldFormatter.formatMileage = function(mileage) {
    if (mileage === "-") {
        return "N/A";
    }
    return mileage;
};

FinanceFieldFormatter.formatRepApr = function(repApr) {
    if (repApr === "-") {
        return "0.0%";
    }
    return repApr + "%";
};

FinanceFieldFormatter.formatInterestRate = function(interestRate) {
    if (interestRate === "-") {
        return "0.00%";
    }
    return interestRate+"%";
};

razsor
	.defineClass({
    "_className" : "FinanceViewHelper",
    "_package" : razsor.finance,
    "_fieldFormatter" : null,
    "_static" : {
            "showAdvertFinanceVideoPopup" : function(){
            $('.finance-video').colorbox({
                iframe : true,
                innerWidth : 425,
                innerHeight : 344,
                onLoad : function() {
                    razsor.commonfunctions.CommonFunctions.setClassToColorbox('video-popup');
                }
            });
        }
    },
    "_class" : {
        "init" : function() {
            this._fieldFormatter = FinanceFieldFormatter;
        },
        
        "updateFinanceAndCloneIllustration" : function($container, selector, jsonData, advertId) {
            var advertJsonData = jsonData[advertId];
            
            this.removeClonedIllustrations($(selector, $container));
            this.cloneAndAddRequiredIllustrations(selector, $container, advertJsonData);
            this.updateAllFinanceIllustrations(selector, $container, advertJsonData, jsonData);
        },
        
        "updateAllFinanceIllustrations" : function(selector, $container, advertJsonData, jsonData){
             var count;
             for (count=0; count < advertJsonData.length; count++) {
                var individualProductData = advertJsonData[count];
                this.updateFinanceIllustrationContent($($(selector, $container)[count]), individualProductData, jsonData);
            }
        },
        
        "updateFinanceIllustrationContent" : function(context, productData, jsonData) {
            $(".finance-type", context).text(productData.productName);
            $(".totalDeposit", context).text(this._fieldFormatter.formatAmount(jsonData.currencySymbol, productData.totalDeposit));
            $(".balanceToFinance", context).text(this._fieldFormatter.formatAmount(jsonData.currencySymbol, productData.balanceToFinance));
            $(".acceptanceFee", context).text(this._fieldFormatter.formatAmount(jsonData.currencySymbol, productData.acceptanceFee));
            $(".totalAmountPayable", context).text(this._fieldFormatter.formatAmount(jsonData.currencySymbol, productData.totalAmountPayable));
            $(".termsOfAgreement", context).text(productData.termOfAgreement + " months");
            $(".termsOfAgreementStkLst", context).text(productData.termOfAgreement);
            
            $(".interestRate", context).text(this._fieldFormatter.formatInterestRate(productData.interestRate));            
            $(".representativeAPR", context).text(this._fieldFormatter.formatRepApr( productData.representativeApr));
            
            $(".initialPayment", context).text(this._fieldFormatter.formatAmount(jsonData.currencySymbol, productData.initialPayment));
            $(".regularPayments", context).text(this._fieldFormatter.formatAmount(jsonData.currencySymbol, productData.regularMonthlyPayments));
            $(".regularPaymentsStkLst", context).text(this._fieldFormatter.formatAmount(jsonData.currencySymbol, productData.regularMonthlyPayments) + ' x ' +productData.noOfPayments);
            $(".finalPayment", context).text(this._fieldFormatter.formatAmount(jsonData.currencySymbol, productData.finalPayment));

            // these are only required for the advert detail page
            $(".totalPrice", context).text(this._fieldFormatter.formatAmount(jsonData.currencySymbol, productData.totalPrice));
            $(".regularPaymentsName", context).text(productData.noOfPayments + " Regular payments");
            $(".optionsToPurchase", context).text(this._fieldFormatter.formatAmount(jsonData.currencySymbol, productData.optionToPurchaseFinance));
            
            $(".annualMileage", context).text(this._fieldFormatter.formatMileage(productData.annualMileage));
            
            $(".apply-now a", context).attr("href", productData.applyNowUrl);
            $(".finance-video", context).attr("href", productData.videoUrl);
            $(".finance-video span", context).text(productData.videoLinkText);
            
            //stocklist only
            $(".totalFees", context).text(this._fieldFormatter.formatAmount(jsonData.currencySymbol, productData.totalFees));
            
        },
        
        "removeClonedIllustrations" : function ($illustrations) {
            $illustrations.each(function(index){
                if(index > 0){
                  $(this).remove();
                }
            });
        },
        
        "cloneAndAddRequiredIllustrations" : function(selector, $container, advertJsonData){
            var count;
            var numberOfProducts = advertJsonData.length;
            var illustrationToClone = $($(selector, $container)[0]);
            
            $container.removeClass('finance1 finance2 finance3').addClass('finance' + numberOfProducts);
            
            for(count=0; count< (numberOfProducts-1) ; count++){
                 $container.append(illustrationToClone.clone());
                 razsor.finance.FinanceViewHelper.showAdvertFinanceVideoPopup();
            }
        }
        
       
    }
});

var financeViewHelper = new razsor.finance.FinanceViewHelper();

razsor.defineClass({
    "_className" : "FinanceController",

    "_package" : razsor.finance,

    "_static" : {},

    "_class" : {
        "_model" : null,
        "_view" : null,
        "_network" : null,

        "init" : function() {
            this._network = Razsor.Network;
            this._model = new this.__package.FinanceModel();
            this._view = new this.__package.PageFinanceView(this._model);
            this.calculate();
            this._view.onRecalculate = razsor.bind("calculate", this);
        },

        "calculate" : function() {
            this._network.postWithTimeOut({
                url : "/xhr/financequote",
                data : this._model.getQuoteData(),
                successHandler : razsor.bind("_successHandler", this),
                failHandler : razsor.bind("_failHandler", this),
                timeOut : 20000
            });
        },

        "_successHandler" : function(data, textStatus, request) {
            var jsonData = eval('(' + data + ')');
            if (jsonData.status === "ok") {
                this._responseReceived(jsonData);
                this._view.enableFinance();
            } else {
                this._ajaxError();
            }
        },
        "_failHandler" : function(data, textStatus, request) {
            this._ajaxError();
        },
        "_responseReceived" : function(jsonData) {
            this._view.update(jsonData);            
            $('.box-calculator').removeClass("updating");
        },
        "_ajaxError" : function() {
            this._view.technicalProblem();
            $('.box-calculator').removeClass("updating");            
            $(".calculateFinance").val("Update");
        }
    }
});

razsor.defineClass({

    "_className" : "FinanceModel",

    "_package" : razsor.finance,

    "_class" : {
        "_financeVehicles" : null,

        "_term" : null,
        
        "_mileage" : null,
		"_cookieManager" : null,

        "init" : function() {
            this._financeVehicles = [];
			this._cookieManager = DealerWebsite.Utils.CookieManager("dwsUserFinance", {});
        },

        "addFinanceVehicle" : function(financeVehicle) {
            this._financeVehicles.push(financeVehicle);
        },

        "setTerm" : function(term) {
			if (this.isUpsell()) {
				this._cookieManager.setValue('term', term);
			}
            this._term = term;
        },
        
        "setMileage" : function(mileage) {
			if (this.isUpsell()) {
				this._cookieManager.setValue('mileage', mileage);
			}
            this._mileage = mileage;
        },
        
        "setDeposit" : function(deposit) {
			if (this.isUpsell()) {
				this._cookieManager.setValue('deposit', deposit);
			}

            if (deposit !== "") {
                  this._updateDepositOnAllVehicles(deposit);
            }
            else { 
                  this._resetDepositOnAllVehicles();
            }            
		},

		"_updateDepositOnAllVehicles" : function(deposit) {
			var count;
			if (deposit) {
				for (count = 0; count < this._financeVehicles.length; count++) {
	                    this._financeVehicles[count].setDeposit(deposit);
	            }
			}
		},
		
		"_resetDepositOnAllVehicles" : function() {
			var count;
			for (count = 0; count < this._financeVehicles.length; count++) {
                    this._financeVehicles[count].resetDeposit();
            }
		},
            
		"setUpsell" : function(isUpsell) {
			this._cookieManager.setValue('isUpsell', isUpsell);
        },

		"isUpsell" : function() {
			return this._cookieManager.getValue('isUpsell');
		},

		"setInitialValues" : function(deposit, term, mileage) {
			this._updateDepositOnAllVehicles(deposit);
			this._term = term;
			this._mileage = mileage;
		},

        "getQuoteData" : function() {
			if (this._cookieManager.hasValue('deposit')) {
				this._updateDepositOnAllVehicles(this._cookieManager
						.getValue('deposit'));
			}
            var quote = {
				"term" : this._cookieManager.getValue('term', this._term),
				"mileage" : this._cookieManager.getValue('mileage', this._mileage)
            };
            var requests = [];
            var count;
            for (count = 0; count < this._financeVehicles.length; count++) {
                requests[count] =  $.toJSON(this._financeVehicles[count].toJSON());
            }
            quote.requests = requests;
            return quote;
		},

		"getDeposit" : function() {
			return this._cookieManager.getValue('deposit');
		},

		"getTerm" : function() {
			return this._cookieManager.getValue('term', this._term);
		},

		"getMileage" : function() {
			return this._cookieManager.getValue('mileage', this._mileage);
        }
    }
});

razsor.defineClass({
    "_className" : "FinanceVehicle",

    "_package" : razsor.finance,

    "_class" : {
        "_advertId" : null,
        "_value" : null,
        "_regLetter" : null,
        "_regYear" : null,
        "_vehicleId" : null,
        "_deposit" : null,
        "_twentyPercentDeposit" : null,
        "_vehicleMileage" : null,
        "_vehicleType" : null,

        "init" : function(advertId, value, regLetter, regYear, vehicleId, deposit, vehicleMileage, vehicleType) {
            this._advertId = advertId;
            this._value = value;
            this._regLetter = regLetter;
            this._regYear = regYear;
            this._vehicleId = vehicleId;
            this._deposit = deposit;
            this._twentyPercentDeposit = deposit;
            this._vehicleMileage = vehicleMileage;
            this._vehicleType = vehicleType;
        },

        "setDeposit" : function(deposit) {
            this._deposit = deposit;
        },
        "getDeposit" : function() {
            return this._deposit;
        },
        "resetDeposit" : function() {
            this._deposit = this._twentyPercentDeposit;
        },
        "getAdvertId" : function() {
            return this._advertId;
        },
        "getValue" : function() {
            return this._value;
        },
        "getRegLetter" : function() {
            return this._regLetter;
        },
        "getRegYear" : function() {
            return this._regYear;
        },
        "getVehicleId" : function() {
            return this._vehicleId;
        },
        "toJSON" : function() {
            return {
                "advertId" : this._advertId,
                "value" : this._value,
                "regLetter" : this._regLetter,
                "regYear" : this._regYear,
                "vehicleId" : this._vehicleId,
                "deposit" : this._deposit,
                "vehicleMileage": this._vehicleMileage,
                "vehicleType" : this._vehicleType
             };
        }
    }
});

razsor.defineClass({
    "_className" : "AdvertFinanceView",

    "_package" : razsor.finance,

    "_class" : {
        "_dataSection" : null,
        "_financeCalculator" : null,
        "_model" : null,
        "_myFinanceVehicle" : null,
        "_fieldFormatter" : null,

        "init" : function(element, model) {
            this._dataSection = $(element);
            this._financeCalculator = $('.rzc-finance-calculator');
            this._model = model;
            this._createFinanceVehicle();
            this._fieldFormatter = FinanceFieldFormatter;
        },

        "_createFinanceVehicle" : function() {
			this._myFinanceVehicle = new razsor.finance.FinanceVehicle($.trim(this._dataSection.find('.advert-id').text()),
																	   this._dataSection.find('li.price').text(),
																	   this._dataSection.find('li.reg').text(),
																	   this._dataSection.find('li.year').text(), 
																	   this._dataSection.find('li.cid').text(), 
																	   this._dataSection.find('li.depositAmount').text(),
																	   this._dataSection.find('li.vehicleMileage').text(),
																	   this._dataSection.find('li.vehicleType').text());
            this._model.addFinanceVehicle(this._myFinanceVehicle);
        },

        "update" : function(jsonData) {
            var advertId = this._myFinanceVehicle.getAdvertId();
            var myData = jsonData[advertId];
            var $illustration =  $('div.financeIllustration', this._financeCalculator);
            if (myData === undefined || myData.length === 0) {
                $illustration.hide();
                $('.financeNotAvailable').removeClass('rzc-hidden').show();
                $('#financeCalculatorTab').fadeIn();
                return;
            }
            $('.financeNotAvailable').hide();
            
            financeViewHelper.updateFinanceAndCloneIllustration($illustration, 'table', jsonData, advertId);
            
            if (this._model.isUpsell()) {
                $(".apply-now", this._financeCalculator).removeClass("rzc-hidden");
                $(".apply-now a", this._financeCalculator).unbind();
                $(".apply-now a", this._financeCalculator).click(function(event) {
                    event.preventDefault();
                    Razsor.WebTracker.Utils.recordFinanceApplyNowVisit();
                    window.open($(this).attr('href'));
                });
            }

            //TODO Does this need to check all products
            var onlyOneProduct = myData[0];    
            if (onlyOneProduct.acceptanceFeeSpread) {
				$(".acceptanceFeeName", this._financeCalculator).html(
						"Acceptance fee *" );
            } else {
				$(".acceptanceFeeName", this._financeCalculator).html(
						"Acceptance fee &#8224;");
            }

            $illustration.slideDown();
            $('#financeCalculatorTab').fadeIn();
        },

        "enableFinance" : function() {
            this._financeCalculator.removeClass('rzc-hidden');
        }
    }
});

razsor.defineClass({
    "_className" : "StocklistFinanceView",
    "_package" : razsor.finance,

    "_class" : {
        "_dataSection" : null,
        "_financeIllustration" : null,
        "_model" : null,
        "_myFinanceVehicle" : null,
        "_fieldFormatter" : null,

        "init" : function(element, model) {
            this._dataSection = $(element);
            this._financeIllustration = $('.financeIllustration', element);
            this._model = model;
            this._createFinanceVehicle();
            this._fieldFormatter = FinanceFieldFormatter;
        },

        "_createFinanceVehicle" : function() {
			this._myFinanceVehicle = new razsor.finance.FinanceVehicle($.trim(this._dataSection.find('.advert-id').text()),
																	   this._dataSection.find('li.price').text(),
																	   this._dataSection.find('li.reg').text(), 
																	   this._dataSection.find('li.year').text(), 
																	   this._dataSection.find('li.cid').text(), 
																	   this._dataSection.find('li.depositAmount').text(),
																	   this._dataSection.find('li.vehicleMileage').text(),
																	   this._dataSection.find('li.vehicleType').text());
            this._model.addFinanceVehicle(this._myFinanceVehicle);
        },

        "update" : function(jsonData) {
            var advertId = this._myFinanceVehicle.getAdvertId();
            var myData = jsonData[advertId];
                                    
            if (myData === undefined || myData.length === 0) {
               $(".rzc-stocklist .submit-outer .calculateFinance").val("Update");
                this._financeIllustration.hide();
                return;
            }                    
            
            financeViewHelper.updateFinanceAndCloneIllustration($('table', this._financeIllustration), 'tbody tr', jsonData, advertId);
            this._financeIllustration.fadeIn(function(){ $(".rzc-stocklist .submit-outer .calculateFinance").val("Update");});
        },

        "enableFinance" : function() {
            this._financeIllustration.removeClass('rzc-hidden');
        }
    }
});

razsor.defineClass({
    "_className" : "PageFinanceView",

    "_package" : razsor.finance,

    "_class" : {
        "_model" : null,
        "_financeViews" : null,
        "onRecalculate" : function() {
        }, //abstract 

        "init" : function(model) {
            this._model = model;
            this._financeViews = [];
            this._initViews();
            this._initModel();
			this._loadUserPreferences();
            var that = this;
            $(".calculateFinance").click(function() {
                $('.box-calculator').addClass("updating");                
                $('.financeIllustration').hide();
                that.setDepositTermAndMileage();
                that.onRecalculate();
            });
        },

        "_initViews" : function() {
            var that = this;
			$('#advertDetailComponent').each(function(index, element) {
                var financeView = new razsor.finance.AdvertFinanceView($(element), that._model);
                that._financeViews.push(financeView);
            });
			$('.stocklistAdvert').each(function(index, element) {
                var financeView = new razsor.finance.StocklistFinanceView($(element), that._model);
                that._financeViews.push(financeView);
            });
            $(".deposit").numeric();
        },

		"_loadUserPreferences" : function() {
			var depositFromCookie = this._model.getDeposit();
			if (depositFromCookie !== "") {
				$('.deposit').val(this._model.getDeposit());
			}
			$('.term').val(this._model.getTerm());
			$('#mileage').val(this._model.getMileage());
		},

		"_initModel" : function() {
			this._model.setInitialValues($('.deposit').val(),
			$('.term').val(), $('#mileage').val());
        },
        "setDepositTermAndMileage" : function() {
            this._model.setDeposit($('.deposit').val());
					this._model.setTerm($('.term').val());
					this._model.setMileage($('#mileage').val());
        },

        "_hideInformationalText" : function() {
            $(".financeLegalText").hide();
            $(".financeLegend").hide();
            $(".acceptanceFeeSpreadText").hide();
        },

        "update" : function(jsonData) {
			this._model.setUpsell(jsonData.upsell);
			$('.financeTechnicalProblem').hide();
            var representativeAPR;
            $.each(this._financeViews, function(index, element) {
                element.update(jsonData);
            });

            representativeAPR = jsonData.representativeAprFirstQuote;            
            if (representativeAPR === undefined) {
                $('.financeNotAvailable').removeClass('rzc-hidden').show();
                $('.financeIllustration').hide();
                this._hideInformationalText();
                return;
            }
            $('.financeNotAvailable').hide();
            
            $(".legalTextApr").text(representativeAPR + "%");
            $(".financeLegalText").fadeIn();
            $(".financeLegend").fadeIn();
            $(".acceptanceFeeSpreadText").fadeIn();
        },

        "enableFinance" : function() {
            $.each(this._financeViews, function(index, element) {
                element.enableFinance();
            });
        },

        "technicalProblem" : function() {
            $('.financeIllustration').hide();
            $('.financeTechnicalProblem').show();
            this._hideInformationalText();
        }
    }
});

$('document').ready(function() {
    if ($('.finance-quote').length > 0) {
        var controller = new razsor.finance.FinanceController();
    }
});
