﻿if (!mecca)
    var mecca = {};

mecca.ShoppingCart = function(options) {
    var defaults = {
        fromCart: false
    }

    var options = $.extend(defaults, options);
    var fromCart = options.fromCart;
    //console.log("fromcart: " + fromCart);

    var addToCart = function(skuId) {
        var param = 'sku=' + skuId;
        $.ajax({
            type: "POST",
            url: "/shoppingcart/addedOverlay.aspx",
            data: param,
            success: function(text) { showOverlay(text); }
        });
    }

    var showOverlay = function(text) {
        $('div.container').after(text);
        $('li.sub-nav-basket a strong').text($('#overlayCartTotalQty').text());
        setupCartButtons();
        fixPosition();
        //window.scroll(0,0);
        $(window).bind('resize.overlay', function() { fixPosition(); });
        $(window).bind('scroll.overlay', function() { fixPosition(); });
        $('div.lightbox').animate({ opacity: 1 }, 250, function() { $(this).css('filter', ''); });
        $('div.lightbox-overlay').animate({ opacity: 0.65 }, 250, function() { $('select').css('visibility', 'hidden'); });

        //$('#lightbox-overlay, div.lightbox').animate({opacity:1}, 250);


        $('a.b-continue-shopping, div.lightbox-overlay').click(function() {
            updateCartHover();
            $('div.lightbox-overlay, div.lightbox').animate({ opacity: 0 }, 250, function() {
                $(this).remove();
                $(window).unbind('resize.overlay');
                $(window).unbind('scroll.overlay');
                $('select').css('visibility', 'visible');
            });
        });

        Cufon.refresh();
    }

    var setupCartButtons = function() {
        $('div.lightbox table.basket li.ctrl-add a').unbind("click").click(function(e) {
            doOneButton($(this), this.rel, 1,
                    $(this).closest('tr').find('li.ctrl-current-qty'),
                    $(this).closest('tr').find('td.total strong')
                );
            if (e.preventDefault) { e.preventDefault(); }
        });

        $('div.lightbox table.basket li.ctrl-subtract a').unbind("click").click(function(e) {
            if (!$(this).hasClass('disabled')) {
                doOneButton($(this), this.rel, -1,
                        $(this).closest('tr').find('li.ctrl-current-qty'),
                        $(this).closest('tr').find('td.total strong')
                    );
            }
            if (e.preventDefault) { e.preventDefault(); }
        });

        $('.basket-link + div.overlay-box table.basket li.ctrl-add a').unbind("click").click(function(e) {
            doOneButton($(this), this.rel, 1,
                    $(this).closest('tr').find('li.ctrl-current-qty'),
                    $(this).closest('tr').find('td.price strong'),
                    $('table.basket + ul.total li').eq(0),
                    $('table.basket + ul.total li').eq(1)
                );
            if (e.preventDefault) { e.preventDefault(); }
        });

        $('.basket-link + div.overlay-box table.basket li.ctrl-subtract a').unbind("click").click(function(e) {
            if (!$(this).hasClass('disabled')) {
                doOneButton($(this), this.rel, -1,
                        $(this).closest('tr').find('li.ctrl-current-qty'),
                        $(this).closest('tr').find('td.price strong'),
                        $('table.basket + ul.total li').eq(0),
                        $('table.basket + ul.total li').eq(1)
                    );
            }
            if (e.preventDefault) { e.preventDefault(); }
        });

        $('.basket-link + div.overlay-box table.basket td.remove-col a').unbind("click").click(function(e) {
            var param = 'sku=' + this.rel;
            $.ajax({
                type: "POST",
                url: "/shoppingcart/removeSKU.aspx",
                data: param,
                dataType: 'json',
                row: $(this).closest('tr'),
                success: function(result) {
                    this.row.fadeOut(250, function() { $(this).remove(); });
                    var temp = $('.basket-link + div.overlay-box table.basket + ul.total li');
                    temp.eq(0).text('Total cost for ' + result.cartQty + ' items:');
                    temp.eq(1).text(result.cartTotal);
                    $('li.sub-nav-basket a strong').text(result.cartQty);
                }
            });
        });

        $('.shopping-basket table.basket li.ctrl-add a').unbind("click").click(function(e) {
            if (!$(this).hasClass('disabled')) {
                doOneButton($(this), this.rel, 1,
                        $(this).closest('td').find('li.ctrl-current-qty'),
                        $(this).closest('tr').find('.total strong'),
                        $('.sb-sidebar dl.b-costs dt').eq(0),
                        $('.sb-sidebar dl.b-costs dd strong').eq(0),
                        $('.sb-sidebar dl.b-costs dd strong').eq(1),
                        $('.sb-sidebar dl.b-costs dt.total-price + dd strong')
                    );
            }
            if (e.preventDefault) { e.preventDefault(); }
        });

        $('.shopping-basket table.basket li.ctrl-subtract a').unbind("click").click(function(e) {
            if (!$(this).hasClass('disabled')) {
                doOneButton($(this), this.rel, -1,
                        $(this).closest('td').find('li.ctrl-current-qty'),
                        $(this).closest('tr').find('.total strong'),
                        $('.sb-sidebar dl.b-costs dt').eq(0),
                        $('.sb-sidebar dl.b-costs dd strong').eq(0),
                        $('.sb-sidebar dl.b-costs dd strong').eq(1),
                        $('.sb-sidebar dl.b-costs dt.total-price + dd strong')
                    );
            }
            if (e.preventDefault) { e.preventDefault(); }
        });


        $('.shopping-basket table.basket td.remove-col a').unbind("click").click(function(e) {
            var param = 'sku=' + this.rel;
            if (fromCart)
                param += '&fromcart=1';

            $.ajax({
                type: "POST",
                url: "/shoppingcart/removeSKU.aspx",
                data: param,
                dataType: 'json',
                row: $(this).closest('tr'),
                success: function(result) {
                    this.row.fadeOut(250, function() {
                        $(this).remove();
                        //$('.basket thead th').css('border-bottom', '1px solid #9b9b9b');
                        $('.sb-sidebar dl.b-costs dt').eq(0).text('Total cost for ' + result.cartQty + ' items:');
                        $('.sb-sidebar dl.b-costs dd strong').eq(0).text(result.cartTotal);
                        $('li.sub-nav-basket p strong').text(result.cartQty);
                        $('.sb-sidebar dl.b-costs dd strong').eq(1).text(result.shippingFee);
                        $('.sb-sidebar dl.b-costs dt.total-price + dd strong').text(result.cartTotalPlusShipping);

                        //KK. when delete basket, if 0 then.. hide the button next input
                        if (result.cartQty <= 0) {
                            $("input.b-checkout-now").hide();
                            $('.shopping-basket table.basket tbody').html('<tr><td colspan="6" class="cart-empty"><p>Your Shopping cart is currently empty.</p><p>Why not browse our <a href="/Catalogue/">catalogue</a> or shop <a href="/TheBestSellersList/">The Best Sellers List.</a></p></td></tr>');
                        }

                        $(".sb-sidebar, .sb-content").equalizeCols();

                    });


                    //$('.basket thead').css('border-bottom', thBorder);
                }
            });
            if (e.preventDefault) { e.preventDefault(); }
        });
    }

    var doOneButton = function(button, skuId, diff, qty, total, cartQty, cartTotal, shippingFee, cartTotalPlusShipping) {
        var param = 'sku=' + skuId + '&diff=' + diff;
        if (fromCart)
            param += '&fromcart=1';

        $.ajax({
            type: "POST",
            url: "/shoppingcart/modifySKUQuantity.aspx",
            data: param,
            dataType: 'json',
            qty: qty,
            total: total,
            cartQty: cartQty,
            cartTotal: cartTotal,
            shippingFee: shippingFee,
            cartTotalPlusShipping: cartTotalPlusShipping,
            button: button,
            success: function(result) {
                this.qty.text(result.qty);
                this.total.text(result.total);
                $('li.sub-nav-basket a strong').text(result.cartQty);
                if (this.cartQty)
                    this.cartQty.text('Total cost for ' + result.cartQty + ' items:');
                if (this.cartTotal)
                    this.cartTotal.text(result.cartTotal);
                if (this.shippingFee)
                    this.shippingFee.text(result.shippingFee);
                if (this.cartTotalPlusShipping)
                    this.cartTotalPlusShipping.text(result.cartTotalPlusShipping);
                if (result.qty <= 1)
                    button.parent().parent().find('li.ctrl-subtract a').addClass('disabled');
                else
                    button.parent().parent().find('li.ctrl-subtract a').removeClass('disabled');
                if (result.disableAdd)
                    button.parent().parent().find('li.ctrl-add a').addClass('disabled');
                else
                    button.parent().parent().find('li.ctrl-add a').removeClass('disabled');

            }
        });
    }

    var fixPosition = function() {
        var lWidth = $('div.lightbox div.overlay-box').width();
        var lHeight = $('div.lightbox div.overlay-box').height();
        if (lWidth > 0 && lHeight > 0) {
            var cWidth = $(window).width();
            //var cHeight = window.innerHeight
            //    || document.documentElement && document.documentElement.clientHeight
            //    || document.body.clientHeight;
            var cHeight = $(window).height();


            var left = (cWidth / 2) - (lWidth / 2);
            left = left < 0 ? 0 : left;
            var top = (cHeight / 2) - (lHeight / 2);
            top += $(window).scrollTop();
            top = top < 0 ? 0 : top;
            $('div.lightbox').css({
                top: top + 'px',
                left: left + 'px'
            });
        }
    }

    var updateCartHover = function() {
        if (window.location.href.toLowerCase().split('shoppingcart').length == 1) {
            $.ajax({
                type: "POST",
                url: "/shoppingcart/basketHoverMenu.aspx",
                success: function(text) {
                    $('li.sub-nav-basket .basket-link + div.overlay-box').remove();
                    $('li.sub-nav-basket .basket-link').after(text);
                    setupCartButtons();
                    $('li.continue-shopping a.h-continue-shopping').click(function() { $('li.sub-nav-basket').mouseout(); })
                    $("ul.sub-nav").superfish({ speed: 200, autoArrows: false }).find('div.overlay-box').bgIframe({ opacity: false });
                }
            });
        }
    }

    var setupAddButtons = function() {
        $('a.b-add-plus[rel]').unbind('click.addToCart').bind('click.addToCart', function(e) {
            addToCart(this.rel);
            if (e.preventDefault) { e.preventDefault(); }
        });
    }

    var setupHelpLinks = function() {
        $('ul.quick-help a').unbind('click.moreInfo').bind('click.moreInfo', function(e) {
            $("div.help-popup .securityContent").css('display', 'none');
            $("div.help-popup .helpContent").css('display', 'block');
            showHelpOverlay();
            if (e.preventDefault) { e.preventDefault(); }
        });
    };

    var setupSecurityCodeLink = function() {
        $('a.a-security-code-info').unbind('click.securityCodeInfo').bind('click.securityCodeInfo', function(e) {
            $("div.help-popup .securityContent").css('display', 'block');
            $("div.help-popup .helpContent").css('display', 'none');
            showHelpOverlay();
            if (e.preventDefault) { e.preventDefault(); }
        });
    };

    var showHelpOverlay = function() {
        $(window).bind('resize.overlay', function() { fixPosition(); });
        $(window).bind('scroll.overlay', function() { fixPosition(); });
        $('div.help-popup').css({ opacity: 0, display: 'block' })
        $('div.lightbox-overlay').css({ opacity: 0, display: 'block' })
        $('div.help-popup').animate({ opacity: 1 }, 250, function() { $(this).css('filter', ''); });
        $('div.lightbox-overlay').animate({ opacity: 0.65 }, 250, function() { $('select').css('visibility', 'hidden'); });
        fixPosition();

        $('div.help-popup div.overlay-box .back-to-basket-link a, div.lightbox-overlay').click(function() {
            $('div.lightbox-overlay, div.help-popup').animate({ opacity: 0 }, 250, function() {
                $(this).css({ display: 'none' });
                $(window).unbind('resize.overlay');
                $(window).unbind('scroll.overlay');
                $('select').css('visibility', 'visible');

                setupHelpLinks();
            });
        });
    };

    var init = function() {
        setupAddButtons();
        setupHelpLinks();
        //This cause an error on Shopping Basket.
        //This used for Medusa Mystic Link        
        if (typeof (setupPromoLinks) == 'function') {
            setupPromoLinks();
        }

        setupSecurityCodeLink();
    } ();

    return { updateCartHover: updateCartHover, setupAddButtons: setupAddButtons, setupCartButtons: setupCartButtons };
}

var prettifyError = function(){

    var x = $(".error-summary li").filter(function(){ return ($(this).css('display') != '' && $(this).css('display') != 'none'); });
    
    if (x.length > 0) {
        var message = "<strong>" + $(x[0]).html();

        x.not(':first').not(':last')
                    .each(function(){message += "</strong>, <strong>" + $(this)
                    .html() + "</strong>";});

        if(x.length > 1) {
                    x.slice(-1)
                    .each(function(){message += " & <strong>" + $(this)
                    .html();});
                    }
        message += "</strong>.";
        $(".error-summary-holder .errorsList").html(message);
        var offset = $(".sb-header").offset().top;

        $('html,body').animate({scrollTop: offset}, 500, function(){
            $(".error-summary-holder").animate( {height:'115px'}, 500);
        });
        
        //console.log(message);
        
    }
}
