﻿window.Promocode =
{
    init: function (initData) {
        window.Promocode.products = initData.Products; //expects an array
        window.Promocode.help = initData.Help; //expects a string

        var patternString = "", ids_array = [];

        for (var i = 0; i < Promocode.products.length; i++) {
            ids_array.push(Promocode.products[i].ContentId);
        }

        if (ids_array.length > 0) {
            patternString = "\\?.*\\Witemid=(" + ids_array.join("|") + ")(\\W|$)";
            Promocode.matchRegEx = new RegExp(patternString, "i");
            Promocode.matchRegEx.compile(Promocode.matchRegEx);
            $("a").bind("click", Promocode.processLink);
        }
    },
    processLink: function (event) {
        Promocode.currentData = null;

        event.currentTarget = event.currentTarget ? event.currentTarget : window.event.srcElement;

        if (event.currentTarget && event.currentTarget.href && event.currentTarget.href.length > 0) {

            var match = event.currentTarget.href.match(Promocode.matchRegEx);

            if (match.legnth == 0) return;

            var matchedContentId = match[1]; //based on pattern string
            var matchedProduct = null;

            for (var i = 0; i < Promocode.products.length; i++) {
                if (Promocode.products[i].ContentId == matchedContentId) {
                    matchedProduct = Promocode.products[i];
                    break;
                }
            }

            if (matchedProduct == null) return;

            //finally, we have a valid product to work with

            event.preventDefault();

            Promocode.currentData = { product: matchedProduct, origDest: event.currentTarget.href, origTarget: event.currentTarget.target, $html: null };

            Promocode.setupHtml();

            jQuery(Promocode.currentData.$html).modal({
                containerId: 'simplemodal-promoInterstitial-container',
                //maxWidth: 432,
                minHeight: 532, //for positioning purposes only                
                //maxHeight: 532, //for positioning purposes only                
                //closeClass: '',
                onOpen: function (dialog) {
                    dialog.overlay.fadeIn('slow', function () {
                        dialog.data.show();

                        //no fade for IE7 and IE8 because we use transparent PNG for border and the transparent pngs render as solid black when opacity is applied, IE6 is fine because it has pngfix applied
                        if ($.browser.msie && (8 >= parseInt($.browser.version, 10) && parseInt($.browser.version, 10) >= 7)) {
                            dialog.container.show();
                            Promocode._setDefaultFocus();
                        }
                        else
                            dialog.container.fadeIn('slow', function () { Promocode._setDefaultFocus(); });
                    });
                },
                onShow: function (dlg) {
                    //alert($(dlg.container).css('height'));
                    //$(dlg.container).css('height', 'auto');
                    //$.modal.setContainerDimensions();
                }
            });
        }
    },

    _setDefaultFocus: function () {
        //it seems that we have to let render first before calling focus
        setTimeout(function () { $("#promoInterstitial_entryContainer input.text", Promocode.currentData.$html).focus(); }, 1);
    },
    setupHtml: function () {

        Promocode.currentData.$html = $('<div id="promoInterstitialWrapper"><div id="promoInterstitial">' +

        '<img src="/site_assets/images/promointerstitial/close_off.png" class="hoverimg closeicon" />' +
        '<div id="promoInterstitial_title">Thank you for choosing ' + Promocode.currentData.product.Name + '</div>' +
        '<div id="promoInterstitial_intro">' + Promocode.currentData.product.IntroMsg + '</div>' +

        '<div id="promoInterstitial_entryContainer">' +
        '   <p>Now, if you have a promotion code, enter it below. Otherwise, click "continue" to proceed with the account opening process.</p>' +
        '   <p>Promotional Code (optional)<br /><input type="text" class="text" /><img src="/site_assets/images/promointerstitial/help_off.png" id="promoInterstitial_entryContainer_helpicon" class="hoverimg" /></p>' +
        '   <div id="promoInterstitial_entryContainer_helpwrapper"><div id="promoInterstitial_entryContainer_helpinner"><div id="promoInterstitial_entryContainer_helcontent">' + Promocode.help + '</div><img src="/site_assets/images/promoInterstitial/arrow_down.png" /></div></div>' +
        '   <div id="promoInterstitial_entryContainer_invalidCode" ></div>' +
        '   <p><input type="image" id="promoInterstitial_entryContainer_continue" src="/site_assets/images/promoInterstitial/btn_continue_off.png" class="hoverimg" /><span class="loading_indicator">Loading ...</span></p>' +
        '</div>' +

        '<div id="promoInterstitial_resultsContainer"><form>' +
        '   <p><span id="promoInterstitial_resultsContainer_code" class=""></span><br /><span id="promoInterstitial_resultsContainer_name" class=""></span></p>' +
        '   <div id="promoInterstitial_resultsContainer_description" class=""></div>' +
        '   <p><a id="promoInterstitial_resultsContainer_reset" class="" href="#">Change Promotional Code</a></p>' +
        '   <p><input type="radio" checked="checked" id="promoInterstitial_resultsContainer_termsAgree" name="terms_agree" value="true" /><label for="promoInterstitial_resultsContainer_termsAgree">I agree to the promotional <a id="promoInterstitial_resultsContainer_termsLink" href="/promo_terms.aspx?contentId={0}&promoCode={1}" target="_blank" >Terms & Conditions </a></label><br /><input type="radio" id="promoInterstitial_resultsContainer_termsDisagree" name="terms_agree" value="false" /><label for="promoInterstitial_resultsContainer_termsDisagree">Proceed without promotional code</label></p>' +
        '   <p id="promoInterstitial_resultsContainer_buttonsRow"><span id="promoInterstitial_resultsContainer_currentDate"></span><input type="image" id="promoInterstitial_resultsContainer_continue" src="/site_assets/images/promoInterstitial/btn_begin_app_off.png" class="hoverimg" /><span class="loading_indicator">Loading ...</span></p>' +
        '</form></div>' +

        '</div></div>')

        Promocode.currentData.$html = borderer(Promocode.currentData.$html);

        $(".hoverimg", Promocode.currentData.$html).bind("mouseenter", function () {
            if (this.src) {
                this.src = this.src.replace("_off.", "_on.");

                $(this).bind("mouseleave", function () {
                    if (this.src) this.src = this.src.replace("_on.", "_off.");
                });
            }
        });



        $(".closeicon", Promocode.currentData.$html).click(function () {
            jQuery.modal.close();
        });

        $("#promoInterstitial_entryContainer_continue", Promocode.currentData.$html).click(function () {
            Promocode.continueFromEntry();
        });

        $("#promoInterstitial_resultsContainer_continue", Promocode.currentData.$html).click(function () {
            Promocode.currentData.termsAgree = $('#promoInterstitial_resultsContainer_termsAgree', Promocode.currentData.$html).is(":checked");
            Promocode.proceed();
        });

        if (Promocode.help && (Promocode.help.length > 0)) {
            $("#promoInterstitial_entryContainer_helpicon", Promocode.currentData.$html).bind("mouseenter", function (event) {
                $("#promoInterstitial_entryContainer_helpinner", Promocode.currentData.$html).show().css("top", (-$("#promoInterstitial_entryContainer_helpinner").outerHeight() - 38) + "px");
            })
            .bind("mouseleave", function () {
                $("#promoInterstitial_entryContainer_helpinner", Promocode.currentData.$html).hide();
            });
        }
        else {
            $("#promoInterstitial_entryContainer_helpicon", Promocode.currentData.$html).hide();
        }

        $("#promoInterstitial_resultsContainer_reset", Promocode.currentData.$html).click(function (event) {
            event.preventDefault();
            //reset

            var $htmlParent = null;

            if (Promocode.currentData.$html != null) {
                $htmlParent = Promocode.currentData.$html.parent();
            }

            Promocode.currentData.$html.remove();

            Promocode.currentData = { product: Promocode.currentData.product, origDest: Promocode.currentData.origDest, origTarget: Promocode.currentData.origTarget, $html: null };
            Promocode.setupHtml();

            if ($htmlParent != null)
                $htmlParent.empty().append(Promocode.currentData.$html);

            Promocode._setDefaultFocus();
        });

        $("#promoInterstitial_entryContainer input.text", Promocode.currentData.$html).keypress(function (e) {
            var code = (e.keyCode ? e.keyCode : e.which);
            if (code == 13) Promocode.continueFromEntry();
        });

    },
    continueFromEntry: function () {
        Promocode.currentData.codeToCheck = $("#promoInterstitial_entryContainer input.text", Promocode.currentData.$html).val().replace(/^\s*/, "").replace(/\s*$/, ""); //trim
        Promocode.currentData.promo = null;

        //verify the promo code
        if (Promocode.currentData.codeToCheck.length > 0) {
            $("#promoInterstitial .loading_indicator", Promocode.currentData.$html).show();
            $.ajax({
                type: "POST",
                url: '/promo.asmx/VerifyPromo',
                data: JSON.stringify({ promoCode: Promocode.currentData.codeToCheck, contentId: Promocode.currentData.product.ContentId }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    msg = msg.d;

                    //promo code is valid
                    if (msg.Status == "ok") {
                        Promocode.currentData.promo = msg.Message;

                        $("#promoInterstitial_entryContainer_invalidCode", Promocode.currentData.$html).empty().hide();

                        $("#promoInterstitial_entryContainer", Promocode.currentData.$html).hide();
                        $("#promoInterstitial_resultsContainer", Promocode.currentData.$html).show();

                        $("#promoInterstitial_resultsContainer_code", Promocode.currentData.$html).html(Promocode.currentData.promo.Code);
                        $("#promoInterstitial_resultsContainer_name", Promocode.currentData.$html).html(Promocode.currentData.promo.Name);
                        $("#promoInterstitial_resultsContainer_description", Promocode.currentData.$html).html(Promocode.currentData.promo.Description);

                        var termsUrl = $("#promoInterstitial_resultsContainer_termsLink", Promocode.currentData.$html).attr("href");
                        termsUrl = termsUrl.replace("{0}", encodeURIComponent(Promocode.currentData.product.ContentId));
                        termsUrl = termsUrl.replace("{1}", encodeURIComponent(Promocode.currentData.promo.Code));
                        $("#promoInterstitial_resultsContainer_termsLink", Promocode.currentData.$html).attr("href", termsUrl);

                        $("#promoInterstitial_resultsContainer_currentDate").html(Promocode.currentData.promo.Timestamp);

                        $("#promoInterstitial_resultsContainer_continue", Promocode.currentData.$html).focus();


                    }
                    //promo code is invalid
                    else if (msg.Status == "invalid") {
                        var invalidCodeMessage = "<p>The code you entered <b>" + Promocode.currentData.codeToCheck + "</b> is not valid.</p>";
                        invalidCodeMessage += " " + Promocode.currentData.product.InvalidCodeMsg;
                        $("#promoInterstitial_entryContainer_invalidCode", Promocode.currentData.$html).html(invalidCodeMessage).show();
                        $("#promoInterstitial_entryContainer input.text", Promocode.currentData.$html).val("");
                        Promocode._setDefaultFocus();
                    }
                    else {
                        alert("error");
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("error");
                },
                complete: function () {
                    $("#promoInterstitial .loading_indicator", Promocode.currentData.$html).hide();
                }
            });

        }
        else {
            Promocode.proceed();
        }
    },
    proceed: function () {

        var productName = Promocode.currentData.product.Name;
        var promoCode = Promocode.currentData.promo && Promocode.currentData.termsAgree ? Promocode.currentData.promo.Code : null;
        var promoName = Promocode.currentData.promo && Promocode.currentData.termsAgree ? Promocode.currentData.promo.Name : null;
        var termsAgree = Promocode.currentData.termsAgree;
        var newDest = "";

        $("#promoInterstitial .loading_indicator", Promocode.currentData.$html).show();

        //GA
        if (pageTracker)
            pageTracker._trackEvent("promo", productName, promoCode);

        //record metrics
        $.ajax({
            type: "POST",
            url: '/promo.asmx/RecordMetric',
            data: JSON.stringify({ productName: productName, promoCode: promoCode, promoName: promoName }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                msg = msg.d;
            },
            error: function (jqXHR, textStatus, errorThrown) {
                ; ; //alert("error");                
            },
            complete: function () {
                $("#promoInterstitial .loading_indicator", Promocode.currentData.$html).hide();
            }
        });

        if (promoCode && termsAgree) {
            newDest = Promocode.currentData.origDest + (Promocode.currentData.origDest.indexOf("?") > -1 ? '' : '?');
            newDest += "&PromoCode=" + encodeURIComponent(promoCode);
        }
        else {
            newDest = Promocode.currentData.origDest;
        }

        if (Promocode.currentData.origTarget == "_blank") {
            window.open(newDest);
            jQuery.modal.close();
        }
        else
            window.location.href = newDest;
    },
    currentData: null,
    products: null,
    help: null,
    matchRegEx: null
}

