﻿/* --------------------------------------------------------------------------- */
/* NG.core
/* Global JS
/* --------------------------------------------------------------------------- */
var NG = NG || {};

NG.core = {

    init: function () {
        var self = this;
        self.$news = $('.newsletterSub');
        self.$overlay = $('#modal');
        self.$context = $('#content');
        self.$shoppingBasket = $('#basket');
        self.$shoppingBasket.$count = $('#basketCount');
        self.$pageOptions = $('.filterOptionsSize');
        self.$pageOptions.$filterOptions = $('#filterOptions');
        self.updateBasket();
        self.bindBagEvents();


        $('.waterMarkInput').focus(function () { if ($(this).val() == $(this).attr("title")) { $(this).val(""); } }).blur(function () { if ($(this).val() == "") { $(this).val($(this).attr("title")); } });


        // amount of time (ms) for cursor to be over top nav before submenu appears
        var intentInterval = 75;
        // amount of time (ms) for submenu to fade in for
        var megaFadeIn = 0;
        // amount of time (ms) for submenu to fade out for
        var megaFadeOut = 0;

        function addMega() { addMega2($(this)); }
        function addMega2(a) {
            var t = $("div:first", a);
            t.stop().fadeIn(megaFadeIn, function () { a.addClass("hovering"); a.addClass("menuOn"); });
        }

        function removeMega() { removeMega2($(this)); }
        function removeMega2(a) {

            var t = $("div:first", a);
            t.stop(true, true).fadeOut(megaFadeOut, function () { a.removeClass("hovering"); a.removeClass("menuOn"); });
        }


        function checkMegaOver() {
            var a = $(this);
            if (!a.data('events')) {
                a.data('megaOver', true)
            .hoverIntent({ over: addMega, out: removeMega, interval: intentInterval }); addMega2(a);
            }
        }

        function checkMegaOut() {
            var a = $(this);
            if (a.data('megaOver')) {
                a.data('megaOver', false); removeMega2(a);
            }
        }

        $("li.mega,li.miga").hoverIntent({ over: addMega, out: removeMega, interval: intentInterval });
        $("li.mega,li.miga").live('mouseover', checkMegaOver);
        $("li.mega,li.miga").live('mouseout', checkMegaOut);

   },

    showModal: function (content) {

        $.fancybox(content, {
            padding: 0
        });
    },

    closeModal: function (autoTime) {
        if (autoTime > 0) {
            setTimeout(function () {
                $.fancybox.close();
            }, autoTime);
        } else {
            $.fancybox.close();
        }
    },


    isValidEmailAddress: function (emailAddress) {
        var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        return pattern.test(emailAddress);
    },

    /* ------------------------------------------------------- */
    /* updateBasket
    /* ------------------------------------------------------- */
    updateBasket: function () {
        var self = this;
        $.ajax({
            type: 'POST',
            url: 'ActionService.asmx/GetDeskBasket',
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                //alert(msg.d);
                self.$shoppingBasket.html(msg.d);
                self.getBasketCount();

            },
            error: function (xhr, msg) {
                alert(msg + '\n' + xhr.responseText);
            }
        });

    },



    bindBagEvents: function () {
        // toggle bag visibility
        this.$shoppingBasket.$count.click($.proxy(this, 'toggleBagClick'));
        this.$shoppingBasket.delegate('.basketClose', 'click', $.proxy(this, 'toggleBagClick'));
        this.$shoppingBasket.delegate('.removeBasketItem', 'click', $.proxy(this, 'onRemoveBasketItemClick'));
        this.$context.delegate('.addToBasketSm', 'click', $.proxy(this, 'onAddToCartButtonSmClick'));
        //this.$pageOptions.$filterOptions.click($.proxy(this, 'toggleOptionsClick'));
        // this.$pageOptions.delegate('.filterClose', 'click', $.proxy(this, 'toggleOptionsClick'));
        this.$pageOptions.delegate('.pageSizeSet', 'click', $.proxy(this, 'onPageSizeClick'));
        this.$news.click($.proxy(this, 'onNewletterSubClick'));
    },
    onPageSizeClick: function (e) {
        e.preventDefault();
        var target = $(e.target);
       // alert(target.text());
        $.cookie('pagesize', target.text(), { expires: 1 }); // set cookie
        window.location.reload();

    },
    onNewletterSubClick: function (e) {
        e.preventDefault();
        var email = $('#newsEmail').val();
        var name = $('#newsName').val();
        var valid = true;
        if (name == 'Name:') {
            valid = false;
        }
        if (email == 'Email:') {
            valid = false;
        }
        if (!this.isValidEmailAddress(email)) {
            valid = false;
        }
        if (valid) {
            $.ajax({
                type: "POST",
                url: "ActionService.asmx/DoNewsletterSubscribe",
                data: "{'name': '" + name + "', 'emailAddress': '" + email + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    //alert(data.d);
                    if (data.d) {
                        $("#newsName").hide();
                        $("#newsEmail").hide();
                        $(".newsletterSub").hide()

                        $(".newsletter").append("<strong>Newsletter subscription successful. Thank you</strong>");
                    }
                },
                error: function (xhr, msg) {
                    alert(msg + '\n' + xhr.responseText);
                }
            });
        } else {
        $('.newsletter').append("Please enter your name and your email address");
        }
    },
    onAddToCartButtonSmClick: function (e) {
        e.preventDefault();

        var target = $(e.target).parent();


        var productIDValSplitter = (target.attr('rel')).split("_");


        var pid = productIDValSplitter[0];
        var vid = productIDValSplitter[1];

        var add = true;

        if (add) {
            this.addToCartQuick(pid, vid, 1, this.addToCartSmCallback);

        }
        return false;
    },

    addToCartQuick: function (pid, dvarid, qty, callback) {
        var self = this;
        $.ajax({
            type: "POST",
            url: "ActionService.asmx/AddToCartDesk",
            data: "{'sProductId': '" + pid + "', 'sVariantId': '" + dvarid + "', 'sCartType': '0', 'sQuantity': '" + qty + "', 'sShippingAddressId': '', 'sVariantStyle': '', 'textOption': '','sCustomerEnteredPrice': 'false','colorOptions': 'false', 'sizeOptions':'false', 'upsellProductIds':'', 'sShoppingCartRecordId':'', 'sIsEditKit':'','kitItemValues':''}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                //alert(data.d);
                if (data.d) {
                    callback(data.d);
                }
            },
            error: function (xhr, msg) {
                alert(msg + '\n' + xhr.responseText);
            }
            //                error: function (e) {
            //                    // add to basket failed
            //                    alert('add to basket failed=' + e.valueOf());
            //                    //self.$overlay.html($('#tmpl_basket_failed').html());
            //                    //NG.core.refreshOverlay();
            //                }
        });
    },
    addToCartSmCallback: function (content) {

        NG.core.showModal(content);

        NG.core.updateBasket();

        NG.core.toggleBagClick(null, 'visible');
        //        self.$productoptions.find('.add_basket').removeClass('disabled loading');
    },
    toggleBagClick: function (e, visibility) {
        if (visibility) {
            this.$shoppingBasket.$count[visibility === 'visible' ? 'addClass' : 'removeClass']('active');
            this.$shoppingBasket[visibility === 'visible' ? 'slideDown' : 'slideUp']('fast');
        } else {
            this.$shoppingBasket.$count.toggleClass('active');
            this.$shoppingBasket.slideToggle('fast');
        }

        if (e) e.preventDefault();
    },

    //    toggleOptionsClick: function (e, visibility) {

    //        if (visibility) {
    //            this.$pageOptions.$filterOptions[visibility === 'visible' ? 'addClass' : 'removeClass']('active');
    //            this.$pageOptions[visibility === 'visible' ? 'slideDown' : 'slideUp']('fast');
    //        } else {
    //            this.$pageOptions.$filterOptions.toggleClass('active');
    //            this.$pageOptions.slideToggle('fast');
    //        }

    //        if (e) e.preventDefault();
    //    },

    onRemoveBasketItemClick: function (e) {
        // alert('remove');
        var $link = $(e.target);
        var productIDValSplitter = $link.attr('rel').split("_");

        var pid = productIDValSplitter[0];
        var vid = productIDValSplitter[1];

        if ((pid > 0) && (vid > 0)) {
            this.removeBasketItem(pid, vid);
        }

        e.preventDefault();
    },
    getBasketCount: function () {
        var self = this;
        $.ajax({
            type: "POST",
            url: "ActionService.asmx/GetBasketQuantity",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                // alert(data.d);
                if (data.d) {
                    // alert(data.d);
                    self.$shoppingBasket.$count.html(data.d);

                }
            },
            error: function (xhr, msg) {
                alert(msg + '\n' + xhr.responseText);
            }
        });
    },
    removeBasketItem: function (pid, vid) {
        var self = this;
        $.ajax({
            type: "POST",
            url: "ActionService.asmx/RemoveFromBasketDesk",
            data: "{'productID': '" + pid + "', 'variantID': '" + vid + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                // alert(data.d);
                if (data.d) {
                    //alert(data.d);
                    self.$shoppingBasket.html(data.d);
                    self.scrollTo(self.$shoppingBasket.$count);
                    self.updateBasket();
                    self.toggleBagClick(null, 'visible');
                }
            },
            error: function (xhr, msg) {
                alert(msg + '\n' + xhr.responseText);
            }
        });

    },



    /* ------------------------------------------------------- */
    /* prepareContentToggling
    /* Show & Hide content after trigger class
    /* ------------------------------------------------------- */

    prepareContentToggling: function () {
        var $hideTrigger = this.$context.find('.hideTrigger'),
            $hideContent = $hideTrigger.next().hide();

        $hideTrigger.click(function (e) {
            $(this).toggleClass("open").next().slideToggle("fast");
            e.preventDefault()
        });
    },


    /* ------------------------------------------------------- */
    /* preloadImage
    /* Pass the image path of the image you wish to preload
    /* ------------------------------------------------------- */
    preloadImage: function (src, callback) {
        callback = callback || $.noop;
        $(new Image()).attr('src', src).load(callback);
        return true;
    },

    /* ------------------------------------------------------- */
    /* switchImage
    /* Replace the old image with new image.
    /* Must pass isSwatch as 'true' if switching with a swatch
    /* ------------------------------------------------------- */
    /* oldImg (object)
    /* newImg (object)
    /* dimensions (object) e.g. {s: 'icon', m: 'medium', l: 'large'}
    /* isSwatch (boolean)
    /* ------------------------------------------------------- */
    switchImage: function (oldImg, newImg, dimensions, isSwatch) {
        isSwatch = isSwatch || false;
        newImg = newImg.attr('src');

        // new main image
        var newSource;

        if (!isSwatch) {
            newSource = newImg.replace('/' + dimensions.s + '/', '/' + dimensions.m + '/');
        } else {
            newSource = newImg.replace('/swatches/', '/' + dimensions.m + '/');
        }

        // fade main image out, change its src value and then fade it in
        oldImg.stop(true, true).animate({ 'opacity': '0' }, 200, function () {
            NG.core.preloadImage(newSource, function () {
                oldImg.attr('src', newSource);
                oldImg.animate({ 'opacity': '1' }, 200);
            });
        });

        return newSource;
    },

    /* ------------------------------------------------------- */
    /* scrollTo
    /* Pass the object/selector you wish to scroll to
    /* ------------------------------------------------------- */
    /* el (string selector or object)
    /* speed (optional, string or integer)
    /* ------------------------------------------------------- */
    scrollTo: function (el, speed, offset) {
        speed = speed || 'fast';
        offset = offset || 0;

        if (typeof (el) === 'string') {
            el = $(el);
        }

        $('html, body').animate({
            scrollTop: el.offset().top - offset
        }, speed);
    }

};



$(function () {
   NG.core.init();
})
