﻿/***

o2More V5 MVC
2010 www.aislondon.com

***/

(function ($) {

    /* 
    Scope
    This initialises the namespace if it has not been initialised elsewhere
    */
    $.o2More = $.o2More || {};

    /*
    Global fields
    Any global objects that you need access to are defined here
    */
    var g_ready = false;
    var g_self = this;

    /* 
    API methods
    If the class has any API methods then put them here
    (methods that can be called directly on objects e.g. $("body").customMethod();
    */
    $.fn.preferences = function () {
        return this.each(function () {
            //alert("API method called on " + this);
        });
    };

    /* Class */
    $.o2More.init = function (options) {
        var c_self = this;
        var c_ready = false;
        c_self.options = $.extend({}, $.o2More.init.defaults, options);

        /*
        Instance methods
        */
        c_self.functions = {
            interval: function () {
                /*
                Insert tasks to be repeated at set intervals
                */
                c_self.functions.debuglog("interval event");
                setTimeout(c_self.functions.interval, c_self.options.intervalFrequency);
            },
            initialise: function (context) {
                context.each(function (index) {

                });
            },

            //open all pdf links in a new window, change title attribute of link to reflect this -keep this -MT
            setPDFLinks: function () {
                debug("configuring PDF links");
                $("a").filter(function () {
                    return this.href.match(RegExp(".pdf|.PDF+\"")) != null
                }).each(function () {
                    if ($(this).attr("title") == null) {
                        $(this).attr("title", "PDF, opens in a new window");
                    };
                    $(this).attr("target", "_blank");
                });

            },
            //this might conflict with new tooltips functionality -MT
            configureExternalLinks: function () {
                // Loop through all links that are absolute or with rel="External"
                // don't process ones that go to O2 More pages
                debug("configuring external links");
                $("a[rel=\"External\"],a[href^=http]:not([rel=\"External\"])")
                    .filter("a:not([href^=http://www.o2more.co.uk])")
                    .filter("a:not([href^=http://staging.aislondon.com])")
                    .filter("a:not([href^=http://www.o2blueroom.co.uk])")
                    .filter("a:not([href^=http://localhost])")
                    .filter("a:not([rel=Internal])")
                    .each(function () {

                        //add external for GA -MT
                        $(this).attr("rel", "External");

                        // If the URL is definitely external OR its container is "event-bookmark"
                        if (this.href.indexOf(location.hostname) == -1 || $(this).parent().parent().attr("id") == "event-bookmark") {

                            if ($(this).attr("class") != "videolink") {
                                var anchor = $(this);
                                var titleText = anchor.attr("title") + "";

                                if (titleText != "" && titleText.indexOf("(opens in a new window)") != -1) {
                                    $(anchor).attr("title", titleText + " (opens in a new window)").attr("target", "_blank");
                                }
                                else {
                                    $(anchor).attr("title", "Opens in a new window").attr("target", "_blank");
                                }

                            }
                        }
                    });
            },

            setupSignIn: function () {
                var signInOverlay = $("#signInOverlay");
                var signInBox = $("#divSignInBox");
                var signInMenu = $("#divSignInRegister");
                var eventSignInLinks = $(".lnkSignIn_Event");

                var errorPanel = signInBox.find('.sign-in-error');
                if (errorPanel.length == 0) {
                    signInBox.find('.userDetails').show();
                } else {
                    debug("hiding login form");
                    signInBox.find('.userDetails').hide();
                };

                //only needs it in IE8, no idea what it'll be in IE9 -MT
                if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "8") {
                    //alert("in IE8");
                    signInBox.find(".form-row .inputContainer").keydown(function (event) {
                        //alert(window.event.keyCode);

                        if (window.event.keyCode == 13) {
                            //prevent default .net from firing
                            event.returnValue = false;
                            event.cancel = true;

                            signInBox.find("input#butSignIn").click();
                            return false;
                        }
                    });
                }

                if (signInMenu.hasClass('signedIn')) {
                    dialogClose();
                } else {

                    signInMenu.find("#lnkSignIn").live('click', function () {
                        var pageWidth = $(document).width();
                        var pageHeight = $(document).height();

                        var viewportHeight = $(window).height();

                        signInOverlay.css({
                            "opacity": 0.8,
                            "width": '100%', //width and height are for IE6
                            "height": pageHeight
                        });

                        signInBox.css({
                            "top": viewportHeight / 2 - signInBox.height() / 2
                        });

                        if (signInBox.css("display") == "none") {
                            signInOverlay.fadeIn(200);
                            signInBox.fadeIn(200);
                            pageScrollTop();
                        }
                        else {
                            dialogClose();
                        }
                        return false;
                    });

                    $("#divSignInBox .closeBtn").live('click', function () {
                        dialogClose();
                        return false;
                    });
                };

                eventSignInLinks.live('click', function () {
                    var pageNr = $(".pagination-numbers:first").find(".pageNumber").text();
                    var signInVal = $("#SignInUrl").val() + "/" + pageNr;
                    $("#SignInUrl").val(signInVal);
                    signInMenu.find("#lnkSignIn").click();
                    return false;
                });

                function dialogClose() {
                    signInOverlay.fadeOut(200);
                    signInBox.fadeOut(200);
                    signInBox.find('.feedback-message').hide();
                    signInBox.find('input.input-validation-error').removeClass('input-validation-error');

                    // see if there is a error panel displayed, hide it and replace with user form
                    var errorPanel = signInBox.find('.sign-in-error');
                    if (errorPanel.length > 0 && errorPanel.is(':visible')) {
                        errorPanel.hide();
                        signInBox.find('.userDetails').show();
                    };
                };

            },

            checkboxSetup: function (checkAllBox, childrenBoxes) {
                checkAllBox.click(function () {
                    if ($(this).attr('checked') == true) {
                        childrenBoxes.each(function () {
                            $(this).attr('checked', true);
                        })
                    } else {
                        childrenBoxes.each(function () {
                            $(this).attr('checked', false);
                        })
                    }
                    setTimeout(triggerPrefSave, 100);
                });

                childrenBoxes.click(function () {
                    var allChecked = true;
                    childrenBoxes.each(function () {
                        if ($(this).attr('checked') == false) allChecked = false
                    })
                    if ($(this).attr('checked') == false) {
                        checkAllBox.attr('checked', false);
                    }
                    else if ($(this).attr('checked') == true && allChecked == true) {
                        checkAllBox.attr('checked', true);
                    }
                    setTimeout(triggerPrefSave, 100);
                });

                function triggerPrefSave() {
                    if ($("#pref-slider-dropdown").length > 0) {
                        debug("trigger preferences save");
                        $("#pref-slider-dropdown .button input").click();
                    }
                }
            },

            setMyAccountCheckBoxes: function () {

                if ($("#user-preferences-container").length > 0) {
                    debug("set my account checkboxes");
                    var userPrefDDList = $("#user-preferences-container .user-preference-item");
                    var userPrefDDToggle = userPrefDDList.find(".pref-head .list-toggle");

                    userPrefDDToggle.click(function () {
                        $(this).prefDDOpenClose();
                    });

                    jQuery.fn.prefDDOpenClose = function () {

                        var thisPrefBox = $(this).parents(".user-preference-item");
                        var thisPrefList = $(this).parents(".user-preference-item").find(".pref-sub-categories");

                        if (thisPrefBox.hasClass("closed")) {

                            thisPrefList.find("li").each(function () {
                                $(this).css("height", "18px");
                            });

                            var thisHeight = (18 + 4) * thisPrefList.find("li").length;

                            if ($.browser.msie && $.browser.version == "7.0") {
                                thisPrefList.css({
                                    height: "auto",
                                    paddingTop: 4,
                                    paddingBottom: 8
                                });
                                thisPrefBox.removeClass("closed");
                            } else {
                                thisPrefList
                                    .animate({
                                        height: thisHeight,
                                        paddingTop: 4,
                                        paddingBottom: 8
                                    }, 300, function () {
                                        thisPrefBox.removeClass("closed");
                                    });
                            };
                        } else {

                            if ($.browser.msie && $.browser.version == "7.0") {
                                thisPrefList.css({
                                    height: 0,
                                    paddingTop: 0,
                                    paddingBottom: 0
                                });
                                thisPrefBox.addClass("closed");
                            } else {
                                thisPrefList
                                    .animate({
                                        height: 0,
                                        paddingTop: 0,
                                        paddingBottom: 0
                                    }, 300, function () {
                                        thisPrefBox.addClass("closed");
                                    });
                            };

                        };
                    };

                    // set my account checkboxes autocomplete
                    $('#user-preferences-container .user-preference-item').each(function (i) {
                        if ($(this).children("ul").length != 0) {
                            var _checkAllBox = $(this).find("h3.pref-head input.checkAll");
                            var _childrenBoxes = $(this).find(".pref-sub-categories li input");

                            c_self.functions.checkboxSetup(_checkAllBox, _childrenBoxes)
                        }

                    });

                };
            },

            setupOffersScroller: function () {
                if ($("#pref-slider-categories").length > 0) {
                    debug("setting categories scroller");
                    var scrollerItemWidth = 90;
                    var scrollerItemMargin = 10;
                    var animationSpeed = 500;

                    var scrollerBoxContainer = $("#pref-slider-categories");
                    var scrollerBox = scrollerBoxContainer.find("#categories-list");
                    var scrollerItemsList = scrollerBox.find("li");
                    var currentActiveItem = scrollerItemsList.filter(".active");

                    var scrollerLeftArrow = scrollerBoxContainer.find(".arrow-left");
                    var scrollerRightArrow = scrollerBoxContainer.find(".arrow-right");

                    scrollerRightArrow.css("background-position", "0px -11px");

                    scrollerBox.css({
                        width: (scrollerItemWidth + scrollerItemMargin) * scrollerItemsList.length,
                        position: "absolute",
                        left: "0px",
                        top: "0px"
                    });

                    var scrollAmount = (scrollerItemsList.length - 8) * (scrollerItemWidth + scrollerItemMargin);
                    var currentPos = 0;

                    if (scrollerItemsList.index(currentActiveItem) > 7) {
                        scrollerBox.css({
                            left: "-" + scrollAmount + "px"
                        });
                        currentPos = scrollAmount;
                        scrollerLeftArrow.css("background-position", "0px -11px");
                        scrollerRightArrow.css("background-position", "0px 0px");
                    };

                    scrollerRightArrow.click(function () {
                        if (currentPos == 0) {
                            scroll("right");
                        }
                    });

                    scrollerLeftArrow.click(function () {
                        if (currentPos > 0) {
                            scroll("left");
                        }
                    });

                    //parent categories scroll function
                    function scroll(direction) {
                        if (direction == "left") {
                            debug("scroll left");
                            scrollerBox.animate({
                                left: "0px"
                            }, animationSpeed);
                            currentPos = 0;
                            scrollerLeftArrow.css("background-position", "0px 0px");
                            scrollerRightArrow.css("background-position", "0px -11px");

                        } else if (direction == "right") {
                            debug("scroll right");
                            scrollerBox.animate({
                                left: "-" + scrollAmount + "px"
                            }, animationSpeed);

                            currentPos = scrollAmount;
                            scrollerLeftArrow.css("background-position", "0px -11px");
                            scrollerRightArrow.css("background-position", "0px 0px");
                        }
                    };

                    if ($("#pref-slider-dropdown").length != 0) {

                        var _checkAllBox = $("#pref-slider-dropdown #sub-categories li.checkAll input");
                        var _childrenBoxes = $("#pref-slider-dropdown #sub-categories li").not(".checkAll").find("input");

                        c_self.functions.checkboxSetup(_checkAllBox, _childrenBoxes)
                    }
                };
            },

            setupOfferSignInClick: function () {
                if ($(".offer").length > 0) {

                    var signInLinks = $(".offer .sign-in-links .offer-sign-in");
                    if (signInLinks.length > 0) {
                        debug("setting offers sign-in links");
                        signInLinks.each(function () {
                            // on click pass the href to ajax sign-in
                            $(this).click(function () {
                                var ajaxSignInLink = $("#lnkSignIn");
                                ajaxSignInLink.attr("href", $(this).attr("href"));
                                ajaxSignInLink.click();
                                debug(ajaxSignInLink.attr("href"));
                                return false; // stop default
                            });
                        });
                    }
                }
            },

            setupRegFormSignClick: function () {

                var regFormSignInLinks = $(".regBoxBottom a.reg-sign-in");
                if (regFormSignInLinks.length > 0) {
                    regFormSignInLinks.live('click', function () {
                        debug("sign in link click");
                        $("#lnkSignIn").click();
                        return false;
                    });
                };
            },

            setupNonAjaxForm: function () {     //run on every non-ajax form to display loader and disable the form submit button
                var nonAjaxForm = $(".non-ajax");
                if (nonAjaxForm.length > 0) {
                    debug("setting up non-ajax forms");
                    var formButton = nonAjaxForm.find(".button input");
                    formButton.click(function () {
                        $(this).parents(".button").next(".ajax-loader").show();
                        //toggleBtnLock();
                        return true;
                    });
                }
            },

            setupGA: function () {
                _gaq = [];
                _gaq.push(['_setAccount', 'UA-4274186-23']);
                _gaq.push(['_trackPageview']);

                (function () {
                    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
                    //ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/u/ga_debug.js';  //turn on for debugging if required
                    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
                    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
                })();

                // track all external links
                $("a[rel=\"External\"]").click(function () {
                    $(this)._trackGAurl("External URL");
                });

                // track button clicks
                $(".button a, .button input").live("click", function () {
                    debug("button click");
                    $(this)._trackGAurl("Button Click");
                });

            },

            getVoucherCode: function (object) {
                debug("get voucher code");

                //alert($(object).attr("class"));
                var offerIDsList = $(object).attr("class").split(" ");

                var thisOfferId = offerIDsList[1];
                var thisBoxId = offerIDsList[2];

                var thisOfferHeader = $("#" + thisBoxId).find(".redeem-background");
                thisOfferHeader.animate({ opacity: 1 }, 150).delay(100).animate({ opacity: 0 }, 700);

                _gaq.push(['_trackEvent', "Offer Redemption", "Get Voucher", thisOfferId]);

                // reset FB functionality
                window.fbAsyncInit();
            },

            setRedeemLinks: function (myObject) {
                debug("setting redeem links");
                debug(myObject);
                var responseJson = myObject.get_response().get_object();

                debug(responseJson.CategoryId);

                if (responseJson.CategoryId != null) {
                    var thisOfferID = responseJson.CategoryId;
                    var thisOfferCategeory = responseJson.CategoryName;
                    var thisOfferCategoryImage = responseJson.ImageUrl;
                    var thisRedeemLink = responseJson.RedemptionUrl;

                    // find modal box and populate with stuff -MT
                    debug("show add offer dialog");
                    var addCategoryBox = $("#addCategoryModal");
                    var pageOverlay = $("#signInOverlay");

                    addCategoryBox.find(".image-box").css("background-image", thisOfferCategoryImage);
                    var addLink = addCategoryBox.find(".button .add-button"); var addLinkHref = addLink.attr("href");
                    addLink.attr("href", addLinkHref + "/" + thisOfferID);
                    addCategoryBox.find(".AddPreferenceCategory").text(thisOfferCategeory);

                    var pageHeight = $(document).height();
                    var viewportHeight = $(window).height();

                    pageOverlay.css({
                        "opacity": 0.8,
                        "height": pageHeight
                    });

                    addCategoryBox.css({
                        "top": viewportHeight / 2 - addCategoryBox.height() / 2
                    });

                    if (addCategoryBox.css("display") == "none") {
                        pageOverlay.fadeIn(200);
                        var tmpAddCategoryBox = addCategoryBox.clone();
                        $("body").append(tmpAddCategoryBox);
                        tmpAddCategoryBox.fadeIn(200);

                        // close modal box
                        tmpAddCategoryBox.find(".closeBtn").click(function () {
                            debug("close add offer dialog");
                            dialogClose();
                            return false;
                        });

                        tmpAddCategoryBox.find(".button .cancel-button").click(function () {
                            dialogClose();
                            return false;
                        });
                        addLink.click(function () {
                            dialogClose();
                            return true;
                        });

                        function dialogClose() {
                            pageOverlay.fadeOut(200);
                            tmpAddCategoryBox.fadeOut(200, function () { tmpAddCategoryBox.remove(); }); //delete the box completely
                        };
                    };

                }

                debug("opening window: " + responseJson.RedemptionUrl);


                // do stuff with single redeem link on click 
                thisRedeemLink.click(function () {
                    if ($(this).attr("rel") == "True") {


                    };

                    _gaq.push(['_trackEvent', "Offer Redemption", "Redeem at Site", thisOfferId]);
                });
            },

            detectIE6: function () {
                if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "6") {
                    //alert("IE6");
                    var msgBox = $("#no-js-header");
                    msgBox.find("h2").text("O2More no longer supports Internet Explorer 6");
                    msgBox.show();
                };
            },

            fixPng: function () {
                if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "6") {
                    DD_belatedPNG.fix('.pngFix');
                }
            },

            preload: function () {
                debug("preloading images");
                //c_self.functions.preloadImages();
            },
            preloadImages: function () {
                for (var i = 0; i < arguments.length; i++) {
                    $("<img>").attr("src", arguments[i]);
                }
            }

        };

        //c_self.functions.initialise($("body"));
        c_self.functions.preload();

        c_self.functions.setupSignIn();
        c_self.functions.configureExternalLinks();
        c_self.functions.setupGA();

        c_self.functions.setMyAccountCheckBoxes();

        c_self.functions.setupNonAjaxForm();
        c_self.functions.setupRegFormSignClick();

        c_self.functions.setupOfferSignInClick();
        c_self.functions.setupOffersScroller();

        c_self.functions.detectIE6();

        //IE6 only
        c_self.functions.fixPng();

        c_ready = true;

    };

    // defaults
    $.o2More.init.defaults = {
        //TODO:
        animationSpeed: "1000",
        intervalFrequency: "10000"
    };

    // optional - initialise one or more instances of the class
    $(document).ready(function () {
        $.br_init = new $.o2More.init();

        $(".redeem-offer-link").live("click", function () {
            setRedeemLinks(this);
        });

    });

})(jQuery);

function setRedeemLinks(obj) {
    debug("setting redeem links");

    var offerId = $(obj).attr("id").split("-")[1];

    $.get("/AddFavouriteCheck/" + offerId,
   function (responseJson) {

       var thisOfferID = responseJson.CategoryId;
       var thisOfferCategeory = responseJson.CategoryName;
       var thisOfferCategoryImage = responseJson.ImageUrl;
       var thisRedeemLink = responseJson.RedemptionUrl;

       if (thisOfferID != null) {

           debug(thisOfferCategoryImage);

           // find modal box and populate with stuff -MT
           debug("show add offer dialog");

           var addCategoryBox = $("#addCategoryModal");
           var pageOverlay = $("#signInOverlay");

           addCategoryBox.find(".image-box").css("background", "url(../" + thisOfferCategoryImage + ") 0 -90px no-repeat");

           var addLink = addCategoryBox.find(".button .add-button"); var addLinkHref = addLink.attr("href");
           addLink.attr("href", addLinkHref + "/" + thisOfferID);

           addCategoryBox.find(".AddPreferenceCategory").text(thisOfferCategeory + "");

           var pageHeight = $(document).height();
           var viewportHeight = $(window).height();

           pageOverlay.css({
               "opacity": 0.8,
               "height": pageHeight
           });

           addCategoryBox.css({
               "top": viewportHeight / 2 - addCategoryBox.height() / 2
           });

           if (addCategoryBox.css("display") == "none") {
               pageOverlay.fadeIn(200);
               //var tmpAddCategoryBox = addCategoryBox.clone(true);
               var tmpAddCategoryBox = addCategoryBox;
               //tmpAddCategoryBox.appendTo("#background");
               $("body").append(tmpAddCategoryBox);
               tmpAddCategoryBox.fadeIn(200);

               // close modal box
               tmpAddCategoryBox.find(".closeBtn").click(function () {
                   debug("close add offer dialog");
                   dialogClose();
                   return false;
               });

               tmpAddCategoryBox.find(".button .cancel-button").click(function () {
                   dialogClose();
                   return false;

               });
               tmpAddCategoryBox.find(".button .add-button").click(function () {
                   dialogClose();
                   return true;
               });

               function dialogClose() {
                   pageOverlay.fadeOut(200);
                   tmpAddCategoryBox.fadeOut(200); //delete the box completely

               };
           };

       }

   });

    _gaq.push(['_trackEvent', "Offer Redemption", "Redeem at Site", offerId]);

};
