﻿var mpapi;
var mpCartItems = {};

$(window).load(function() {

    if (typeof(window["loadApi"]) == "function") {
        loadApi(onApiLoaded);
    }
});

var afterApiLoadedFunction = function() { };

function onApiLoaded(api) {
    mpapi = api;
    afterApiLoadedFunction();
}

function catchReturnKey(e) {
    if (e.keyCode) {
        if (e.keyCode == 13) {
            e.keyCode = 0;
            doSearch($("#searchTextInput").val());
            return false;
        }
    }
    else if (e.which) {
        if (e.which == 13) {
            e.which = 0;
            doSearch($("#searchTextInput").val());
            return false;
        }
    }
}


$(function() {

    if (!Array.indexOf) {
        Array.prototype.indexOf = function(obj) {
            for (var i = 0; i < this.length; i++) {
                if (this[i] == obj) {
                    return i;
                }
            }
            return -1;
        }
    }

    function openCart() {
        $("#cart").slideDown().addClass("open");
        addOpenPanel("cart");
    }

    function addOpenPanel(id) {

        var $openpanels = $("#openpanels");
        var items = $openpanels.val().split(",");
        var index = items.indexOf(id);
        if (index >= 0) {
        } else {
            // add item
            items.push(id);
        }

        $openpanels.val(items.join(","));
    }

    function removeOpenPanel(id) {

        var $openpanels = $("#openpanels");
        var items = $openpanels.val().split(",");
        var index = items.indexOf(id);
        if (index >= 0) {
            // remove item
            items.splice(index, 1);
        }

        $openpanels.val(items.join(","));
    }

    $("#searchSubmitButton").click(function() {
        doSearch($("#searchTextInput").val());
        return false;
    })
    $("#searchTextInput").keypress(catchReturnKey);

    $("#checkout").click(function() {
        // double check user is logged in, before adding products
        if (!mpapi.getUser().isAnonymous()) {
            addProductsToCart(mpapi, mpCartItems);
            document.location = MPSettings.checkoutUrl;
        } else {
            // add products, force login and then redirect to check out. user has been logged in before

            var href = document.location.href.toString();
            var hash = document.location.hash.toString();
            if (hash != "") {
                href = href.substr(0, href.length - hash.length);
            }
            href += "#cart";
            var newHref = MPSettings.loginUrl + "?successUrl=" + encodeURIComponent("http://" + document.location.host + "/FromCheckout.aspx?go=" + encodeURIComponent(MPSettings.checkoutUrl)) + "&failureUrl=" + encodeURIComponent(href);
            document.location = newHref;
        }

        return false;
    });


    $(".loginfromcart").click(function() {
        // double check user is logged in, before adding products
        if (mpapi.getUser().isAnonymous()) {
            // force user login before adding products and redirect to this page

            var href = document.location.href.toString();
            var hash = document.location.hash.toString();
            if (hash != "") {
                href = href.substr(0, href.length - hash.length);
            }
            href += "#cart";

            var newHref = MPSettings.loginUrl + "?successUrl=" + encodeURIComponent("http://" + document.location.host + "/FromLogin.aspx?go=" + encodeURIComponent(href)) + "&failureUrl=" + encodeURIComponent(href);
            document.location = newHref;
        } else {
            // User was actually logged in, but we didn't know

            var itemCount = 0;
            for (var p in mpCartItems) {
                itemCount++;
            }

            if (itemCount > 0) {
                // 1. add prodducts 
                addProductsToCart(mpapi, mpCartItems);
                // 2. goto fromlogin to get user information and redirect to shopping cart
                document.location = "/FromLogin.aspx?go=" + encodeURIComponent(MPSettings.checkoutUrl);
            } else {
                var href = document.location.href.toString();
                var hash = document.location.hash.toString();
                if (hash != "") {
                    href = href.substr(0, href.length - hash.length);
                }
                href += "#cart";
                document.location = "/FromLogin.aspx?go=" + encodeURIComponent(href);
            }
        }

        return false;
    });

    $(".notifyHighlight").notifyHighlight();

    /*
    $("<a href='#''>Grid</a>").click(function() {
    $("#page").toggleClass("grid");
    return false;
    }).css({ 'position': 'fixed', 'left': 0, 'top': 0, 'background': '#ccc', 'padding': '10px' }).appendTo("body");
    */

    // resize search input
    var $currentSection = $("#currentsection").eq(0);
    var $quicksearch = $("input.quicksearch");
    var newWidth = 384;

    if ($currentSection.length > 0) {
        var csWidth = parseInt($currentSection.width());
        var csOffset = $currentSection.offset();
        var qsWidth = parseInt($quicksearch.width());
        var qsOffset = $quicksearch.offset();
        var leftPoint = parseInt(csOffset.left) + csWidth + 20;
        var addWidth = parseInt(qsOffset.left) - leftPoint;
        newWidth = qsWidth + addWidth;
    }

    $quicksearch.width(newWidth);

    // drop down menus
    $("#header a.dropdown, .productslist a.dropdown").linkDropDown();

    // cart open/close
    $("#mycart,#cart a.close").click(function() {

        $("#cart").slideToggle().toggleClass("open");

        if ($("#cart").hasClass("open")) {
            addOpenPanel("cart");
        } else {
            removeOpenPanel("cart");
        }

        return false;
    });

    // check if cart is open
    if (document.location.hash == "#cart") {
        openCart();
    }


    $("h2.subserietitle a").click(function() {
        var $heading = $(this).parent();
        var $div = $heading.parent();

        if ($div.hasClass("closedsubserial")) {
            $heading.next().slideDown();
            $div.removeClass("closedsubserial");
            addOpenPanel($heading.attr("id"));
        } else {
            $heading.next().slideUp();
            $div.addClass("closedsubserial");
            removeOpenPanel($heading.attr("id"));
        }

        return false;
    });

    $(".scroll").anchorscroll();

    $(".openscroll").anchorscroll({
        callbefore: function(link) {
            var $link = $(link);
            var anchor = $link.attr("href");
            var $heading = $(anchor);
            var $div = $heading.parent();

            if ($div.hasClass("closedsubserial")) {
                $heading.next().show();
                $div.removeClass("closedsubserial");
                addOpenPanel($heading.attr("id"));
            }
        }
    });

    $(".carousel,.bigcarousel,.customcarousel").lcarousel();
});

function addProductsToCart(api, cartItems) {

    var cart = api.getCart();
    var catalog = api.getCatalog();

    cart.setAutoCommit(false)
    cart.clear();
    addProducts(catalog,
            cartItems,
            cart);
    cart.commit();
}

function addProducts(catalog, items, cart) {

    for (var identifier in items) {

        var cartItem = items[identifier];
        var itemType = cartItem.type;
        var quantity = cartItem.quantity;
        var searchParams = itemType + ":" + identifier;

        var criteria = catalog.newCatalogSearchCriteria(searchParams);
        criteria.setMaxResultSize(50);
        var iterator = catalog.searchCatalog(criteria).getCatalogItems().iterator();

        while (iterator.hasNext()) {
            var catalogItem = iterator.next();
            var product = catalogItem.getProduct();
            if (product != null) {
                cart.addProduct(product, product.getOrdering().getOrderOption(), quantity);
            }
        }
    }
}

function cartToString(cart) {
    var string = 'Cart[totalNetAmount=' + cart.getTotalNetPrice().getAmount() + ',totalGrossAmount=' + cart.getTotalGrossPrice().getAmount() + ']';
    var iter = cart.getCartItems().iterator();
    for (null; iter.hasNext(); null) {
        string += '\n+ ' + cartItemToString(iter.next());
    }
    return string;
}

function cartItemToString(cartItem) {
    return 'CartItem[title=' + cartItem.getTitle() + ',totalNetAmount=' + cartItem.getTotalNetPrice().getAmount() + ',totalGrossAmount=' + cartItem.getTotalGrossPrice().getAmount() + ']';
}



// Animation for scrollinglinks
(function($) {

    $.fn.anchorscroll = function(options) {

        return this.each(function() {

            //var $link = $(this);
            var opt = $.extend({
                callbefore: null,
                callback: null
            }, options);

            if (typeof opt.callbefore != "function") {
                opt.callbefore = function() { };
            }
            if (typeof opt.callback != "function") {
                opt.callback = function() { };
            }

            $(this).click(function(event) {
                //prevent the default action for the click event
                event.preventDefault();
                
                // call before
                opt.callbefore(this);

                //get the full url - like mysitecom/index.htm#home
                var full_url = this.href;

                //split the url by # and get the anchor target name - home in mysitecom/index.htm#home
                var parts = full_url.split("#");
                var trgt = parts[1];

                //get the top offset of the target anchor
                var target_offset = $("#" + trgt).offset();
                var target_top = target_offset.top;

                //goto that anchor by setting the body scroll top to anchor top
                $('html, body').animate({ scrollTop: target_top }, 500, undefined, opt.callback);
            });
        });
    }
})(jQuery);
   

// Drop down for links
(function($) {

    // The current drop down
    var $current = null;

    $.fn.linkDropDown = function(options) {

        return this.each(function() {

            var $link = $(this);
            var opt = $.extend({
                dropDownSelector: ".dropdown"
            }, options);

            var $dropDown = $link.next().eq(0);

            $(document).click(function() {
                if ($current != null) {
                    $current.slideUp(50);
                    $current = null;
                }
            });

            $link.click(function() {
                if ($current != null) {
                    if ($current != $dropDown) {
                        $current.slideUp(50);
                        $dropDown.slideDown(50);
                        $current = $dropDown;
                    } else {
                        $current.slideUp(50);
                        $current = null;
                    }
                } else {
                    $dropDown.slideDown(50);
                    $current = $dropDown;
                }
                return false;
            });
        })
    };

})(jQuery);


// Drop down for links
(function($) {

    $.fn.notifyHighlight = function(options) {


        return this.each(function() {
            
            var $this = $(this);
            
            for (var i = 0; i < 5; i++) {
                $this.fadeOut(200).fadeIn(200);
//                $this.animate({ top: "-=15px" }, 100).animate({ top: "+=15px" }, 100)
            }
        })
    };

})(jQuery);



(function($) {

    $.fn.lcarousel = function() {
        return this.each(function(options) {

            options = $.extend({
                wrapper: ".list",
                list: "ul",
                pageindex: ".current",
                pagetotal: ".total",
                back: "a.back",
                forward: "a.forward",
                speed: 600
            }, options);

            var $carousel = $(this);
            var $wrapper = $carousel.find(options.wrapper);
            var $list = $wrapper.find(options.list); // the list
            var $currentpage = $carousel.find(options.pageindex);
            var $totalpages = $carousel.find(options.pagetotal);

            var w = $wrapper.width();
            var iw = $list.find("li").width();

            var h = $list.height();
            var items = $list.children("li").length;
            var itemsPerPage = Math.floor(w / iw);
            var currentPage = 1;
            var totalPages;

            if (items % itemsPerPage == 0)
                totalPages = items / itemsPerPage;
            else
                totalPages = Math.floor(items / itemsPerPage) + 1;

            var moving = false;

            // set pageinfo
            $currentpage.html(currentPage);
            $totalpages.html(totalPages);

            // set width for list	
            $list.width(iw * items);

            var $back = $carousel.children(options.back);
            var $fwd = $carousel.children(options.forward);

            if (totalPages <= 1) {
                $back.css("visibility", "hidden");
                $fwd.css("visibility", "hidden");
                $currentpage.parent().hide();
            }

            function moveList(fromPage, toPage) {

                var dir = (fromPage < toPage) ? "-" : "+";
                moving = true;
                $back.css("visibility", "hidden");
                $fwd.css("visibility", "hidden");

                $list.animate({
                    "left": dir + "=" + (iw * itemsPerPage) + "px"
                }, options.speed, function() {
                    currentPage = toPage;
                    moving = false;
                    $currentpage.html(currentPage);

                    if (currentPage > 1)
                        $back.css("visibility", "visible");
                    if (currentPage < totalPages)
                        $fwd.css("visibility", "visible");

                });
            }

            $back.click(function(e) {
                if (!moving && currentPage > 1) {
                    moveList(currentPage, currentPage - 1);
                }
                return false;
            });

            $fwd.click(function(e) {
                if (!moving && currentPage < totalPages) {
                    moveList(currentPage, currentPage + 1);
                }
                return false;
            });
        });
    }

})(jQuery);

// Quick search support
function doSearch(text) {
    var searchForm = $("#searchForm");
    var searchTextField = $("#searchTextField");
    var categoryCodeField = $("#categoryCodeField");
    var topCategoryCodeField = $("#topCategoryCodeField");
    var filterField = $("#filterField");
    var pageField = $("#pageField");
    searchTextField.val(text);
    categoryCodeField.val(topCategoryCodeField.val());
    filterField.val("");
    pageField.val("1");
    searchForm.submit();
    return false;
}
function doCategorySelect(categoryCode, topCategoryCode) {
    var searchForm = $("#searchForm");
    var categoryCodeField = $("#categoryCodeField");
    var pageField = $("#pageField");

    if (arguments.length == 2) {
        var topCategoryCodeField = $("#topCategoryCodeField");
        topCategoryCodeField.val(topCategoryCode);
    }

    pageField.val("1");
    categoryCodeField.val(categoryCode);
    searchForm.submit();
    return false;
}
function doTopCategorySelect(categoryCode) {
    var searchForm = $("#searchForm");
    var topCategoryCodeField = $("#topCategoryCodeField");
    topCategoryCodeField.val(categoryCode);
    return doCategorySelect(categoryCode);
}


var Cookies = {
    "testCookieName": "CookiesIsEnabledCookie",

    "erase": function(name) {
        this.set(name, "", -1);
    },

    "get": function(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];

            while (c.charAt(0) == ' ')
                c = c.substring(1, c.length);

            if (c.indexOf(nameEQ) == 0)
                return c.substring(nameEQ.length, c.length);
        }
        return null;
    },

    "isEnabled": function() {
        var c = null;

        this.set(this.testCookieName, "cookie", 0);
        c = this.get(this.testCookieName);
        this.erase(this.testCookieName);

        return c != null;
    },

    "set": function(name, value, days) {
        var expires;

        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
        } else {
            expires = "";
        }

        document.cookie = name + "=" + value + expires + "; path=/";
    }
}