﻿var SSI = {
    init: function () {
        // event handlers
        $("#search-toggles a").click(this.onSearchToggle);
        $(".setdefault").focus(this.onClearDefault).blur(this.onResetDefault);
        // other init
        this.blockUIsetup();
        this.Navigation.init();
        this.Zip.init();
        this.StockCheck.init();
        this.Favourites.init();
    },
    blockUIsetup: function () {
        //cart related edit buttons
        $(".bt_cart_edit").click(function () {
            $.blockUI({
                message: '<br/><h1>Please wait...</h1>',
                timeout: 100000
            });
        });

        //unblock window after unload (needed for FireFox back button issue)
        $(window).unload(function () {
            $.unblockUI();
        })
    },
    onSearchToggle: function (e) {
        e.preventDefault();
        var idx = $("#search-toggles a").index(this);
        if (idx == 0) {
            $("#toggle-dn").attr("class", "toggle-dn");
            $("#toggle-up").attr("class", "toggle-up");
            $("#query-frm").attr("action", "/search.aspx");
        } else {
            $("#toggle-dn").attr("class", "toggle-up");
            $("#toggle-up").attr("class", "toggle-dn");
            $("#query-frm").attr("action", "/item/number/sku/p"); 
        }
        $("#q").focus();
    },
    onClearDefault: function () {
        if (this.value === this.title) {
            this.value = '';
        }
    },
    onResetDefault: function () {
        if (this.value === '') {
            this.value = this.title;
        }
    }
};

SSI.Navigation = {
    timeout: 300,
    closetimer: 0,
    ddmenuitem: 0,
    init: function () {
        // handlers
        $("#nav > li").mouseover(this.onNavMouseover).mouseout(this.onNavMouseout);
    },
    close: function () {
        if (SSI.Navigation.ddmenuitem) {
            SSI.Navigation.ddmenuitem.css("visibility", "hidden");
        }
    },
    onNavMouseover: function () {
        if (SSI.Navigation.closetimer) {
            window.clearTimeout(SSI.Navigation.closetimer);
            SSI.Navigation.closetimer = null;
        }
        SSI.Navigation.close();
        SSI.Navigation.ddmenuitem = $(this).find("ul").css("visibility", "visible");
    },
    onNavMouseout: function () {
        SSI.Navigation.closetimer = window.setTimeout(SSI.Navigation.close, SSI.Navigation.timeout);
    }
};

SSI.Zip = {
    $popupContainer: null,
    $zip: null,
    zip: null,
    onSaveCallback: null,
    onCancelCallback: null,
    init: function () {
        this.$popupContainer = $("#zip-container");
        this.$zip = $("#ctl00_tb_zip");
        this.$zip.val(SSI.Cookies.read("postalZip") || '');
        this.zip = this.$zip.val();

        // events
        $("#zip-save").click(this.onPopupContainerSaveClick);
        $("#zip-cancel").click(this.onPopupContainerCancelClick);
    },
    open: function(offset) {
        SSI.Zip.$popupContainer.css({ "top": "" + (offset.top - 50).toString() + "px", "left": "" + (offset.left + 10).toString() + "px" }).show();
    },
    close: function () {
        SSI.Zip.$popupContainer.hide();
        // callback
        if (SSI.Zip.onCancelCallback && typeof SSI.Zip.onCancelCallback === 'function') {
            SSI.Zip.onCancelCallback();
            SSI.Zip.onCancelCallback = null;
        }
    },
    validate: function (code) {
        //allows middle space in Canadian Postal Code as well as lowercase letters
        return /(^\d{5}(-\d{4})?$)|(^[A-z]\d[A-z]\s*\d[A-z]\d$)/.test(code);
    },
    onPopupContainerSaveClick: function (e) {
        e.preventDefault();
        SSI.Zip.zip = SSI.Zip.$zip.val();
        if (SSI.Zip.validate(SSI.Zip.zip)) {
            // set cookie
            SSI.Cookies.create("postalZip", SSI.Zip.zip, 30);
            // close
            SSI.Zip.close();
            // callback
            if (SSI.Zip.onSaveCallback && typeof SSI.Zip.onSaveCallback === 'function') {
                SSI.Zip.onSaveCallback();
                SSI.Zip.onSaveCallback = null;
            }
        } else {
            alert("Please enter a valid Zip Code (US) or Postal Code (Canada).\n\nex. US Zip Code: 44240 or 44240-5555\n\nex. Canadian Postal Code: G3H 6A3");
        }
    },
    onPopupContainerCancelClick: function (e) {
        e.preventDefault();
        SSI.Zip.close();
    }
};

SSI.StockCheck = {
    $container: null,
    sku: null,
    qty: null,
    init: function () {
        // handlers
        $(".stockcheck-parent").delegate(".stockcheck, .stockretry", "click", this.onStockCheck);
        $(".stockcheck-immediate").click();
    },
    onStockCheck: function (e) {
        e.preventDefault();

        var $callingAnchor = $(this),
            $parent = $callingAnchor.closest(".stockcheck-parent"),
            offset = $callingAnchor.offset();

        SSI.StockCheck.$container = $container = $callingAnchor.parent();
        SSI.StockCheck.sku = $parent.find(".sku").text() || $parent.find(".stockcheck-sku input").val();
        SSI.StockCheck.qty = $parent.find(".qty input").val() || $parent.find(".stockcheck-qty input").val();

        if (SSI.StockCheck.sku !== '' && SSI.StockCheck.qty !== '' && SSI.StockCheck.qty > 0) {
            if (SSI.Zip.zip === '' || !SSI.Zip.validate(SSI.Zip.zip)) {
                // show zip-code popup
                SSI.Zip.open(offset);
                // set callback 
                SSI.Zip.onSaveCallback = SSI.StockCheck.check;
            } else {
                SSI.StockCheck.check();
            }
        } else {
            alert("A valid sku and quantity is required to perform a stock check.");
        }

    },
    check: function () {

        var retryLink = '<a href="#" class="stockcheck stockretry"><em>Try Again</em></a>';
        SSI.StockCheck.$container.html('<span class="stock-checking" title="Checking inventory..."></span>');

        // get inventory status. Results: N/A or integer value
        $.ajax({
            type: "POST",
            timeout: 7000,
            url: "/services.asmx/GetInventoryStatus",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: '{zip: "' + SSI.Zip.zip + '", sku:"' + SSI.StockCheck.sku + '", qty:"' + SSI.StockCheck.qty + '"}',
            success: function (data) {
                var inventoryStatus = data.d;
                if (inventoryStatus) {
                    SSI.StockCheck.$container.html(inventoryStatus);
                } else {
                    SSI.StockCheck.$container.html(retryLink);
                }
            },
            error: function () {
                SSI.StockCheck.$container.html(retryLink);
            }
        });

    }
};

SSI.Favourites = {
    $popupContainer: null,
    $container: null,
    $callingAnchor: null,
    sku: null,
    init: function () {
        this.$popupContainer = $("#favcat-container");
        // handlers
        $(".favcat-parent").delegate(".favcat-link", "click", this.onPopupContainerShow);
        $("#favcat-submit").click(this.onPopupContainerSaveClick);
        $("#favcat-cancel").click(this.onPopupContainerCancelClick);
    },
    onPopupContainerShow: function (e) {
        e.preventDefault();

        var $callingAnchor = $(this),
            $parent = $callingAnchor.closest(".favcat-parent"),
            offset = $callingAnchor.offset();

        SSI.Favourites.$callingAnchor = $callingAnchor;
        SSI.Favourites.sku = $parent.find(".sku").text();


        if (SSI.Favourites.sku !== '') {
            SSI.Favourites.$popupContainer.css({ "top": "" + (offset.top - 50).toString() + "px", "left": "" + (offset.left + 10).toString() + "px" }).show();
        } else {
            alert("A valid sku is required to Add to Favorites.");
        }

    },
    onPopupContainerSaveClick: function (e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: "/services.asmx/AddFavouriteToCategory",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: '{sku:"' + SSI.Favourites.sku + '", catid:' + $(".favcat-choose").val() + '}',
            success: function () {
                if ($('#favcat-goto').is(':checked')) {
                    location.href = "/favourites.aspx";
                } else {
                    if (SSI.Favourites.$callingAnchor.hasClass("bt")) {
                        alert("That product was added to your favorites.");
                    } else {
                        SSI.Favourites.$callingAnchor.html('<strong><em>Add to Favorites (added)</em></strong>');
                    }                    
                    SSI.Favourites.$popupContainer.hide();
                }
            },
            error: SSI.Utilities.handleJsonError
        });

    },
    onPopupContainerCancelClick: function (e) {
        e.preventDefault();
        SSI.Favourites.$popupContainer.hide();
    }
};

SSI.Cookies = {
    create: 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();
        }
        document.cookie = name + "=" + value + expires + "; path=/";
    },
    read: function (name) {
        var nameEQ = name + "=",
            ca = document.cookie.split(';'),
            i = 0;
        for (i; 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;
    },
    erase: function (name) {
        SSI.Cookies.create(name, "", -1);
    }
};

SSI.Utilities = {
    round: function (number, decimalPlaces) {
        return Math.round(parseFloat(number) * Math.pow(10, decimalPlaces)) / Math.pow(10, decimalPlaces);
    },
    roundFixed: function (number, decimalPlaces) {
        return this.round(number, decimalPlaces).toFixed(decimalPlaces);
    },
    handleJsonError: function (xhr, textStatus, errorThrown) {
        var err = eval("(" + xhr.responseText + ")");
        alert(err.Message);
    },
    centredPopup: function ($container) {
        var windowWidth = $(window).width(),
            windowHeight = $(window).height();
            scrollTop = $(window).scrollTop(),
            containerHeight = $container.height(),                        
            containerWidth = $container.width();
        return { top: (windowHeight / 2 + scrollTop - containerHeight / 2), left: (windowWidth / 2 - containerWidth / 2) };
    },
    getQuerystringParams: function () {
        var vars = [],
            hash,
            hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
};

$(function () {
    SSI.init();
});

document.onclick = SSI.Navigation.close;


