﻿$.console.log('begin loading current-offers.js');
$.createSingleton('X.CurrentOffers', function () {
    this.model = null;
    this.modelTrim = null;
    this.isRegional = false;
},
{
    init: function () {
        $('.model-current-offers-link').bind("click", X.CurrentOffers.onModelModalOpenerLinkClick);
        $('.model-trim-current-offers-link').bind("click", X.CurrentOffers.onModelTrimModalOpenerLinkClick);

        // Add form validation for the global zipcode search
        var options =
		{
		    containerQuery: '.modal .offers-local-search',
		    triggerQuery: '.modal .offers-local-search .btn',
		    triggerHandler: function (result) {
		        $('.err-field').removeClass('err-field');
		    },
		    failureHandler: function (result) {
		        result.errors[0].srcElement.parent().addClass('err-field');
		    },
		    successHandler: function (result) {
		        var zip = $(':text.search-zip', result.container.containerElm).val();
		        window.setGlobalZip(zip);
		        window.coZip = true;
		        X.Omniture.trigger({ data: { prop8: zip, prop9: 'CURRENT OFFERS'} });
		        X.CurrentOffers.load({ zip: zip });
		    }
		};
        new $.validation.Group(options);

        options.containerQuery = '#bap-options-summary .offers-local-search';
        options.triggerQuery = '#bap-options-summary .offers-local-search .btn';
        new $.validation.Group(options);

        options.containerQuery = '#raq-current-offers .offers-local-search';
        options.triggerQuery = '#raq-current-offers .offers-local-search .btn';
        new $.validation.Group(options);

        // Moved from underneath the document ready
        options.containerQuery = '#current-offers-go';
        options.triggerQuery = '#current-offers-go .submit';
        options.failureHandler = function (result) {
            result.container.containerElm.addClass('err-container');
        };
        options.successHandler = function (result) {
            $.cookie('zipcode', $('#offers-local-search-inline').val(), { expires: 30, path: '/' });
            $('#current-offers-form').submit();
        };
        new $.validation.Group(options);
    },

    reset: function () {
        $('#modal-current-offers').addClass('wait-available');

        $('.lease-offers').html('<h5>Lease Offers</h5><p>Loading, please wait...</p>');
        $('.finance-offers').html('<h5>Finance Offers</h5><p>Loading, please wait...</p>');
    },

    load: function (data) {
        this.reset();

        if (!data) { data = {}; }

        if (!data.zip) {
            data.zip = '';
            this.isRegional = false;
        }
        else {
            this.isRegional = true;
        }

        var url;
        if (data.modelTrim) {
            this.model = null;
            this.modelTrim = data.modelTrim;
        }
        else if (data.model) {
            this.model = data.model;
            this.modelTrim = null;
        }
        else if (this.modelTrim) {
            data.modelTrim = this.modelTrim;
        }
        else if (this.model) {
            data.model = this.model;
        }
        else {
            data.model = window.model;
        }

        if (data.modelTrim) {
            //url = configUrlTemplate(serviceUrls.currentOffersModelTrim, data.modelTrim, data.zip);
            url = "/currentoffer/currentofferservice.aspx?vehicletype=n&modelid=" + data.modelTrim + "&zip=" + data.zip + "&type=trim";
        }
        else {
            url = "/currentoffer/currentofferservice.aspx?vehicletype=n&modelseries=" + data.model + "&zip=" + data.zip + "&type=model";
            //url = configUrlTemplate(serviceUrls.currentOffersModel, data.model, data.zip);
        }
        //alert(url);
        X.JsonRequestManager.call('current-offers',
		{
		    cache: true,
		    url: url,
		    success: this.onLoad.delegate(this),
		    error: function (textStatus, msg) { alert('Error loading current offers data. Reason: ' + msg); }
		});
    },

    onLoad: function (offers) {
        // Split the offer types into their own arrays
        var leaseOffers = [];
        var financeOffers = [];
        for (var idx = 0, len = offers.length, offer; idx < len; idx++) {
            offer = offers[idx];
            if (offer.SalesProgramTypeCD == 1 || offer.SalesProgramTypeCD == 3) { //if its 1,3 then it's lease
                leaseOffers[leaseOffers.length] = offer;
            }
            else { //then it's finance
                financeOffers[financeOffers.length] = offer;
            }
        }

        // Loop through the lease offers first
        var leaseHtml = ['<h5>Lease Offers</h5>'];
        var leaseOffersLen = leaseOffers.length;
        if (leaseOffersLen > 0) {
            for (var idx = 0, offer; idx < leaseOffersLen; idx++) {
                offer = leaseOffers[idx];

                leaseHtml[leaseHtml.length] = '<div class="offer';
                if (idx === 0) {
                    leaseHtml[leaseHtml.length] = ' first';
                }
                if ((idx + 1) === leaseOffersLen) {
                    leaseHtml[leaseHtml.length] = ' last';
                }
                leaseHtml[leaseHtml.length] = '">';
                leaseHtml[leaseHtml.length] = this._getLeaseOfferHtml(offer, idx);
                leaseHtml[leaseHtml.length] = '</div>';
            }
        }
        else {
            if (this.isRegional) {
                leaseHtml[leaseHtml.length] = '<p>Please see your local Acura dealer for available offers.</p>';
            }
            else {
                leaseHtml[leaseHtml.length] = '<p>Please enter your zip code in the box above to find offers in your area.</p>';
            }
        }
        $('.lease-offers').html(leaseHtml.join(''));

        // Next through the finance offers
        var financeHtml = ['<h5>Finance Offers</h5>'];
        var financeOffersLen = financeOffers.length;
        if (financeOffersLen > 0) {
            for (var idx = 0, offer; idx < financeOffersLen; idx++) {
                offer = financeOffers[idx];

                financeHtml[financeHtml.length] = '<div class="offer';
                if (idx === 0) {
                    financeHtml[financeHtml.length] = ' first';
                }
                if ((idx + 1) === financeOffersLen) {
                    financeHtml[financeHtml.length] = ' last';
                }
                financeHtml[financeHtml.length] = '">';
                financeHtml[financeHtml.length] = this._getFinanceOfferHtml(offer, idx);
                financeHtml[financeHtml.length] = '</div>';
            }
        }
        else {
            if (this.isRegional) {
                financeHtml[financeHtml.length] = '<p>Please see your local Acura dealer for available offers.</p>';
            }
            else {
                financeHtml[financeHtml.length] = '<p>Please enter your zip code in the box above to find offers in your area.</p>';
            }
        }
        $('.finance-offers').html(financeHtml.join(''));

        //start
        if (this.isRegional) {
            try {
                if ((!BAPDealerSite) && ((financeOffersLen < 1) || (leaseOffersLen < 1)) && (typeof X.bap.controller.ConfigManager == "object")) {
                    //var offerClasses = ['.lease-offers', '.finance-offers'];
                    var offerClasses = [];
                    if (leaseOffersLen < 1) { offerClasses.push('.lease-offers'); }
                    if (financeOffersLen < 1) { offerClasses.push('.finance-offers'); }

                    for (i = 1; i < (offerClasses.length + 1); i++) {
                        //remove existing offer
                        $(offerClasses[i - 1] + ' > p').remove();
                        //build html for replacement
                        var containerIteration = $(".inline-locate-dealer-container").length;
                        $(offerClasses[i - 1]).each(function (j, el) {
                            var cNum = containerIteration + (j + 1);
                            var tHtml = '';
                            tHtml += '<p>Please use the Dealer Locator below to find your local Acura dealer for available offers.</p>';
                            tHtml += '<div id="inlineLocateDealerContainer' + cNum + '" class="inline-locate-dealer-container">';
                            tHtml += '  <h6>Locate a Dealer</h6>';
                            tHtml += '  <div class="fieldgroup">';
                            tHtml += '    <input type="text" id="inline-locate-dealer-zipcode' + cNum + '" name="inline-locate-dealer-zipcode' + cNum + '" class="txt default-text search-zip required val-zipcode" value="Enter Zip Code" />';
                            tHtml += '    <a href="#" class="btn d" title="Go"><span>Go</span></a>';
                            tHtml += '  </div>';
                            tHtml += '</div>';
                            //apply replacement html
                            $(el).append(tHtml);

                            // Set all search-zip fields value(s) to the zipcode from the cookie (if any)
                            var storedZip = $.cookie('zipcode');
                            if (storedZip) {
                                $('.search-zip').val(storedZip);
                            }

                            //add 'default-text' functionality to fields-
                            $('#inline-locate-dealer-zipcode' + cNum).each(function (idx) {
                                var defaultValue = this.value;
                                $(this)
                            .focus(function () { if (this.value === defaultValue) { this.value = ''; } })
                            .blur(function () { if (this.value === '') { this.value = defaultValue; } });
                            });

                            //setup options for zip form validation/send
                            options =
                            {
                                containerQuery: '#inlineLocateDealerContainer' + cNum,
                                triggerQuery: '#inlineLocateDealerContainer' + cNum + ' .btn',
                                successHandler: function (result) {
                                    var zip = $(result.container.elements[0]).val();
                                    $.cookie('zipcode', zip, { expires: 30, path: '/' });
                                    X.Omniture.trigger({ data: { prop8: zip, prop9: 'DL:ZIP CODE SEARCH:BAP'} });
                                    X.bap.controller.ConfigManager.callLocateDealer(zip);
                                }
                            };
                            new $.validation.Group(options);
                        });
                        //
                    }
                }
            } catch (e) {
            }
        }
        //end

        $('a.full-desc-link').click(function (evt) {
            evt.preventDefault();
            var linkElm = $(this);
            var descElm = $('.offer-description-terms', linkElm.parent());
            if (!linkElm.hasClass('selected-contrast-content')) {
                linkElm.addClass('selected-contrast-content');
                descElm.slideDown('slow');
            }
            else {
                linkElm.removeClass('selected-contrast-content');
                descElm.slideUp('fast');
            }
        });

        $('.offer-printable-link > a').click(X.PopupFactory._onClick);

        $('#modal-current-offers').removeClass('wait-available');
    },

    // Called in the scope of the link
    onModelModalOpenerLinkClick: function (evt) {
        evt.preventDefault();
        X.CurrentOffers.load({ model: this.rel });
    },

    onModelTrimModalOpenerLinkClick: function (evt) {
        evt.preventDefault();
        X.CurrentOffers.load({ modelTrim: this.rel });
    },

    _getOfferHtml: function (offer) {
        if (!offer) { return ''; }
        var html = [];

        html[html.length] = '<div class="offer-container">';

        // Offer Name
        html[html.length] = '<h6>' + offer.Name + '</h6>';

        // Short Description
        html[html.length] = '<div class="offer-deal">';
        html[html.length] = offer.ShortDescription;
        html[html.length] = '</div>';
        html[html.length] = '<div class="offer-deal">';
        html[html.length] = offer.ShortDisclaimer;
        html[html.length] = '</div>';

        // Full Description and Terms
        html[html.length] = '<div class="offer-link offer-terms-link">';
        html[html.length] = '<a href="#" class="full-desc-link contrast-content">Full Description and Terms</a>';

        // Hidden Full Details & Terms
        html[html.length] = '<div class="offer-description-terms" style="display:none;">';
        html[html.length] = '<p class="offer-description">';
        html[html.length] = offer.Description;
        html[html.length] = '</p>';
        html[html.length] = '<p class="offer-terms">';
        html[html.length] = offer.TermsAndConditions;
        html[html.length] = '</p>';
        html[html.length] = '</div>';

        html[html.length] = '</div>';

        // Printable Offer Cert
        html[html.length] = '<div class="offer-link offer-printable-link contrast-content">';
        if (offer.Type !== 'featuredlease') {
        	html[html.length] = '<a href="#" rel="{id:\'print-' + offer.Id + '\',url:\'/tools/shopping/PrintOffer.aspx?model=' + window.model + "&modelID=" + offer.Model.ModelID + "&id=" + offer.Id + '\',width:510,height:540,scrollbars:1}" class="contrast-content popup-opener">Print Offer</a>';
           }
           //$('.payment-result-more-links a.print-offer-link').attr("rel", "{id:'print-" + specialId + "' ,url:'/tools/shopping/PrintOffer.aspx?model=" + window.model + "&modelID=" + special.ModelID + "&zip=&id=" + specialId + "&o=f',width:510,height:540,scrollbars:'yes'}");
        html[html.length] = '</div>';

        html[html.length] = '</div>';

        return html.join('');
    },

    _getLeaseOfferHtml: function (offer, index) {
        if (!offer) { return ''; }
        var html = [];
        if (index > 0)
            html[html.length] = '<div class="offer offer-not-first">';
        else
            html[html.length] = '<div class="offer">';

        // Offer Name
        html[html.length] = '<span class="title">' + offer.Model.SalesProgramName + '</span>';

        //check if it is 0 lease offer
        var totalDueAtSigning = offer.Model.LeasePaymentInfo.TotalDueAtSigning;
        if (totalDueAtSigning == 0) {
            html[html.length] = '<div class="price-bar-single price-bar-extended-offer">';
            html[html.length] = '<div class="price-bar-amount"><div class="units">$</div>0</div>';
            html[html.length] = '<div class="price-bar-detail-large">';
            html[html.length] = '<p>down payment</p><p>security deposit</p><p>first month\'s payment</p><p>due at lease signing<em>Excludes taxes, titles and fees.</em></p>';
            html[html.length] = '<p><strong>$' + offer.Model.LeasePaymentInfo.BaseMonthlyPayment + '</strong> a month for ' + (offer.Model.LeasePaymentInfo.TermMonths - 1) + ' months thereafter</p>';
            html[html.length] = '</div>';
            html[html.length] = '</div>';
        } else {
            html[html.length] = '<div class="price-bar-single">';
            html[html.length] = '<div class="price-bar-amount">';
            html[html.length] = '<div class="units">$</div>';
            html[html.length] = offer.Model.LeasePaymentInfo.BaseMonthlyPayment;
            html[html.length] = '</div>';
            html[html.length] = '<div class="price-bar-detail-large">';
            html[html.length] = '<p>per month for ' + offer.Model.LeasePaymentInfo.TermMonths + ' months</p>';
            html[html.length] = '<p>$' + totalDueAtSigning + ' total due at signing</p>';
            html[html.length] = '</div>';
            html[html.length] = '</div>';
        }

        html[html.length] = '<p class="price-bar-subtitle">' + offer.Model.ShortDisclaimer + '</p>';

        // Full Description and Terms
        html[html.length] = '<div class="offer-link offer-terms-link">';
        html[html.length] = '<a href="#" class="full-desc-link contrast-content" onclick="trackBAPSummaryOmnitureCurrentOfferModule(\'DESC TERMS ' + offer.Id + ' CURR OFFRS\');">Full Description and Terms</a>';

        // Hidden Full Details & Terms
        html[html.length] = '<div class="offer-description-terms" style="display:none;">';
        html[html.length] = '<p class="offer-description">';
        html[html.length] = offer.Model.SpecialDescription;
        html[html.length] = '</p>';
        html[html.length] = '<p class="offer-terms">';
        html[html.length] = offer.Model.TermAndConditions;
        html[html.length] = '</p>';
        html[html.length] = '</div>';

        html[html.length] = '</div>';

        // Printable Offer Cert
        html[html.length] = '<div class="offer-link offer-printable-link contrast-content">';
        if (offer.Model.IsFeatured == true) {
        	html[html.length] = '<a href="#" rel="{id:\'print-' + offer.Id + '\',url:\'/tools/shopping/PrintOffer.aspx?model=' + window.model + "&modelID=" + offer.Model.ModelID + "&id=" + offer.Id + '\',width:510,height:540,scrollbars:1}" class="contrast-content popup-opener">Print Offer</a>';
        }
        html[html.length] = '</div>';

        html[html.length] = '</div>';

        return html.join('');
    },

    _getFinanceOfferHtml: function (offer, index) {
        if (!offer) { return ''; }
        var html = [];

        if (index > 0)
            html[html.length] = '<div class="offer offer-not-first">';
        else
            html[html.length] = '<div class="offer">';

        // Offer Name
        html[html.length] = '<span class="title">' + offer.Model.SalesProgramName + '</span>';

        //offer focus
        html[html.length] = '<div class="price-bar-single">';
        html[html.length] = '<div class="price-bar-amount">' + offer.PaymentTerms.FinanceTerms[0].SampleFinancePayment.SampleAPR + '</div>'
        html[html.length] = '<div class="price-bar-detail-large"><p>% APR</p>';
        html[html.length] = '<p>for ' + offer.PaymentTerms.FinanceTerms[0].SampleFinancePayment.SampleTerm + ' months</p>';
        html[html.length] = '</div>';
        html[html.length] = '</div>';

        //short disclaimer
        html[html.length] = '<p class="price-bar-subtitle">';
        html[html.length] = offer.Model.ShortDisclaimer;
        html[html.length] = '</p>';

        // Full Description and Terms
        html[html.length] = '<div class="offer-link offer-terms-link">';
        html[html.length] = '<a href="#" class="full-desc-link contrast-content" onclick="trackBAPSummaryOmnitureCurrentOfferModule(\'DESC TERMS ' + offer.Id + ' CURR OFFRS\');">Full Description and Terms</a>';

        // Hidden Full Details & Terms
        html[html.length] = '<div class="offer-description-terms" style="display:none;">';
        html[html.length] = '<p class="offer-description">';
        html[html.length] = offer.Model.SpecialDescription;
        html[html.length] = '</p>';
        html[html.length] = '<p class="offer-terms">';
        html[html.length] = offer.Model.TermAndConditions;
        html[html.length] = '</p>';
        html[html.length] = '</div>';

        html[html.length] = '</div>';

        // Printable Offer Cert
        html[html.length] = '<div class="offer-link offer-printable-link contrast-content">';
        if (offer.Model.IsFeatured == true) {
        	html[html.length] = '<a href="#" rel="{id:\'print-' + offer.Id + '\',url:\'/tools/shopping/PrintOffer.aspx?model=' + window.model + "&modelID=" + offer.Model.ModelID + "&id=" + offer.Id + '\',width:510,height:540,scrollbars:1}" class="contrast-content popup-opener">Print Offer</a>';
        }
        html[html.length] = '</div>';

        //special offer attribute
        if (offer.IsGraduateSpecial == true) {
            html[html.length] = '<div class="special-financing-grads">';
            html[html.length] = 'Special Financing for college grads.';
            html[html.length] = '<a href="http://www.acurafinancialservices.com/lease/lease_gradprogram.aspx">Learn more.</a>';
            html[html.length] = '</div>';
        }

        html[html.length] = '</div>';

        return html.join('');
    }
});

$(document).ready(X.CurrentOffers.init);

$.console.log('end loading curent-offers.js');

function trackBAPSummaryOmnitureCurrentOfferModule(p16) {
    X.Omniture.trigger({ data: { prop16: p16, prop23: omniData['pageName'], prop1: window.model, prop2: window.modelYear} });
}

