﻿/////////////////////////////////////
// LaerdalJS.js
/////////////////////////////////////

//Root Namespace
/////////////////////////////////////
if (typeof laerdal === "undefined") var laerdal = {};
/////////////////////////////////////

//MUST Declare Sub Namespaces
if (!laerdal.ui) laerdal.ui = {};
if (!laerdal.cart) laerdal.cart = {};
if (!laerdal.shopItems) laerdal.shopItems = {};
if (!laerdal.iframe) laerdal.iframe = {};
/////////////////////////////////////

laerdal.trace = function(msg) {
    if(typeof console != 'undefined' && console.trace)
        console.trace(msg)
}

laerdal.log = function(msg) {
    if (typeof console != 'undefined' && console.log)
        console.log(msg)
}

laerdal.ui.tabs = {
    currentTabId: "",
    iframesLoaded: [],
    // implement / override in client code
    loadAjax: function(loadTabEl, cmd, qryOpts) {
        alert('implement laerdal.ui.tabs.loadAjax(cmd)');
    },

    showTab: function(id) {
        id = id.replace('/', '');
        if (id.indexOf("group") == 0)
            id = "shop";
        else if (id == '')
            id = 'main';
        if (id == this.currentTabId)
            return;

        this.currentTabId = id;
        var tabContent = $("#content_" + id);
        if (tabContent.length == 0)
            return;

        $(".product-tab-panel").hide();
        tabContent.show();
        $("ul#product-tabs li a").removeClass("selected");

        var title = $("ul#product-tabs li a#tab_" + id).addClass("selected").text().replace('\u203a', '');
        
        $.address.title($.address.title().split(' | ')[0] + ' | ' + title);
        var cmd = $("input[name=ajaxcmd]", tabContent);
        if (cmd.length > 0) {
            var opts = cmd.val().split('|');
            if (opts[0] == 'iframe') {
                var reload = opts[1] == null ? false : opts[1] == 'true' ? true : false;
                if (!laerdal.ui.tabs.iframesLoaded["#content_" + id] || reload) {
                    var iframe = $(tabContent).find('iframe');
                    iframe.attr('src', opts[2])
                    laerdal.ui.tabs.iframesLoaded["#content_" + id] = true;
                }
            }
            else {
                laerdal.ui.tabs.loadAjax(tabContent, cmd);
            }
        }
    },

    // call on document ready
    loadFromUrl: function() {
        var t = location.hash.replace("#", "");
        if (t.length > 0)
            laerdal.ui.tabs.showTab(t);
    }
}



/////////////////////////////////////
//Namespace: cart
//Info: Methods related to the Cart
/////////////////////////////////////
laerdal.cart = {

    addItemToCart: function($qty, $btn, itemNo) {
        $btn.hide();
        var $loadImg = $('<img class="loader" src="' + _appRoot + '/images/static/ajax-loader-small.gif" />');
        $btn.after($loadImg);

        var handler1 = function(o) {
            $loadImg.fadeOut();
            $btn.show();
            var $existingPopup = $("#cboxLoadedContent .addedToCartInfo");
            var html = (o.ResponseHTML ?  o.ResponseHTML : o);
            if ($existingPopup.length > 0)
                $existingPopup.fadeOut('fast', function() { $(this).replaceWith(html) });
            else {
                $.fancybox({ content: '<div style="width: 800px">' + html + '</div>' });
            }
            //Update call to action shopping cart item total
            laerdal.cart.updateCartSummary(o);
        }

        var args = { "method": "add", "partId": itemNo, "qty": parseInt($qty.val()), "source": "shop" };
        $.ajax({ url: _siteRoot + "/Services/Cart.ashx", type: "POST", dataType: "json", data: args, success: handler1 });
    },

    updateCartSummary: function(result) {
        if (typeof (result) == "object") {
            var showWithTax = result.ShowSinglePriceWithTax;
            laerdal.call2Action.updateCartSummary(showWithTax ? result.TotalAfterTax : result.TotalBeforeTax, result.Count);
        }
    }

}

/////////////////////////////////////
//Namespace: call2Action
//Info: Methods related to the Call2Action box
/////////////////////////////////////
laerdal.call2Action = {

    updateCartSummary: function(price, itemCount) {
        var hasItems = itemCount && itemCount > 0;
        $("#call2action .cartSummary").toggle(hasItems);
        $("#call2action a#cart-link").toggleClass('expanded', hasItems);
        $("#call2action .totalPrice").html(price);
    }

}
    
/////////////////////////////////////
//Namespace: shopItems
//Info: Methods related to ShopItemList.ascx usercontrol
/////////////////////////////////////
laerdal.shopItems = {

    addOnEnter: function(evt, itemNo) {
        if (evt.keyCode == 13)
            this.addItemToCart(itemNo);
    },
    addItemToCart: function(itemNo, ic) {  // ic=inputcontainer
        var $container = ic ? $(ic) : $("#item_" + itemNo);
        var $qty = $(".qty", $container);
        var $btn = $("a.cart,.CartButton,.CartButton2", $container);

        laerdal.cart.addItemToCart($qty, $btn, itemNo);
    },

    removeFavItem: function(partNo) {
        var self = this;
        var handler1 = function(result) {
            $(".product-items #item_" + partNo).each(function(i) {
                var index = $(this).index();
                $(this).animate({ opacity: "hide" }, "slow", function() { $(this).remove(); self.rearrangeAfterRemove(index - 2); });
            });
        };

        var args = { method: "delFav", partId: partNo };
        $.ajax({ url: _siteRoot + "/Services/Cart.ashx", type: "POST", dataType: "json", data: args, success: handler1 });
    },

    rearrangeAfterRemove: function(index) {
        var offsetSelector = (index < 0) ? '' : ":gt(" + (index) + ")";
        
        $(".product-items li" + offsetSelector).each(function(i2, val) {
            $el = $(val);
            if ($el.hasClass("sep")) {
                $el.remove();
            } else if ($el.hasClass("col-1")) {
                $el.removeClass("col-1").addClass("col-3").after('<li class="sep"></li>');
            } else if ($el.hasClass("col-2")) {
                $el.removeClass("col-2").addClass("col-1");
            } else if ($el.hasClass("col-3")) {
                $el.removeClass("col-3").addClass("col-2");
            }
        });
    },

    checkNoData: function(text) {

    }
}

/////////////////////////////////////
//Namespace: Auto Resize IFrame
//Info: Resizes the height of an IFrame according to its content, does not work on remote content
/////////////////////////////////////
laerdal.iframe = {

    resize: function(frameId) {

        var frame = document.getElementById(frameId);

        function iResize() {
            var innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
            frame.height = innerDoc.body.offsetHeight + 10;
        }

        // Check if browser is Safari or Opera.
        if ($.browser.safari || $.browser.opera) {
            // Start timer when loaded.
            $('#' + frameId).load(function() {
                setTimeout(iResize, 100);
            });

            // Safari and Opera need a kick-start.
            var iSource = frame.src;
            frame.src = '';
            frame.src = iSource;
        }
        else {
            $('#' + frameId).load(function() {
                var innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
                frame.height = innerDoc.body.scrollHeight + 10;
            });
        }

    }
}

