﻿var timeout = 300;
var closetimer = 0;
var ddmenuitem = 0;
document.onclick = nav_close;

$(document).ready(function() {

    initSearch();
    initNav();
    initStockCheck();
    initFavCategoryChoose();
    initBlockUI();
    initCartTaxEstimate();

    // clear default text
    $(".setdefault").focus(function() {
        if ($(this).val() == $(this).attr("title")) {
            $(this).val("");
        }
    });

});


function initSearch() {

    // search toggle
    $("#search-toggles a").click(function() {

        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", "product.aspx");
        }

        $("#q").focus();
        return false;

    });

}

function initNav() {

    // show nav
    $("#nav > li").bind("mouseover", function() {

        if (closetimer) {
            window.clearTimeout(closetimer);
            closetimer = null;
        }

        nav_close();
        ddmenuitem = $(this).find("ul").css("visibility", "visible");
    });

    // hide nav
    $("#nav > li").bind("mouseout", function() {
        closetimer = window.setTimeout(nav_close, timeout);
    });

}

function initSearchResults() {

    if ($("#search-results").length) {

        // handle compare check
        $("td.compare-col input").click(function() {

            var compareCount = $("td.compare-col input:checked").length;
            if (compareCount == 4) {
                $("td.compare-col input:not(:checked)").attr("disabled", true);
            } else {
                $("td.compare-col input").attr("disabled", false);
            }

        });

        // handle compare
        $(".compare").click(function() {
            var $comparedCheckboxes = $("td.compare-col input:checked");
            if ($comparedCheckboxes.length < 2) {
                alert("Please check at least two products to compare.");
            } else {
                var allChecked = '';
                $comparedCheckboxes.each(function() {
                    allChecked += ',' + $(this).val();
                });
                window.location = "compare.aspx?skus=" + allChecked.substring(1);
            }
            return false;
        });

    }

}

function initStockCheck() {

    $(".stockcheck-immediate").each(stockCheckHandler);
    $(".stockcheck").click(stockCheckHandler);

}

function nav_close() {
    if (ddmenuitem) ddmenuitem.css("visibility", "hidden");
}

function stockCheckHandler() {

    var $callingAnchor = $(this);
    var $parent = $callingAnchor.closest(".stockcheck-parent");
    var $container = $callingAnchor.parent();
    var offset = $callingAnchor.offset();
    var zip = $("#ctl00_tb_zip").val();
    var sku = $parent.find(".sku").text() || $parent.find(".stockcheck-sku input").val();
    var qty = $parent.find(".qty input").val() || $parent.find(".stockcheck-qty input").val();

    if (sku != '' && qty != '' && qty > 0) {

        if ((zip == '') || !(isValidPostalZipCode(zip))) {
            $("#zip-container")
                    .css({ "top": "" + (offset.top - 50).toString() + "px", "left": "" + (offset.left + 10).toString() + "px" })
                    .show()
                    .unbind("click").bind("click", function(targ) {
                        var $target = $(targ.target);
                        if ($target.is("a")) {

                            if ($target.attr("id") == 'zip-save') {
                                //ensure zip/postal code is valid format
                                if (isValidPostalZipCode($("#ctl00_tb_zip").val())) {
                                    // save zip                                
                                    $.ajax({
                                        type: "POST",
                                        timeout: 7000,
                                        url: "services.asmx/SetZipCodeCookie",
                                        contentType: "application/json; charset=utf-8",
                                        dataType: "json",
                                        data: '{zip: "' + $("#ctl00_tb_zip").val() + '"}'
                                    });
                                    // close
                                    $("#zip-container").hide();
                                    // get stock
                                    stockCheck($container, sku, qty);
                                } else {
                                    alert("Please enter a valid Zip Code (US) or Postal Code (Canada).\n\neg. US Zip Code: 44240 or 44240-5555\n\neg. Canadian Postal Code: G3H 6A3");
                                }
                            } else {
                                // close
                                $("#zip-container").hide();
                            }
                            return false;
                        }
                    });
        } else {
            // get stock
        stockCheck($container, sku, qty);
        }

    } else {
        alert("A valid sku and quantity is required to perform a stock check.");
    }
	
	return false;

}

function stockCheck($container, sku, qty) {

    var retryLink = '<a href="#" class="stockcheck stockretry"><em>Try Again</em></a>';
    var waitingHtml = '<span class="stock-checking" title="Checking inventory..."></span>';
    $container.html(waitingHtml);

    // 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: "' + $("#ctl00_tb_zip").val() + '", sku:"' + sku + '", qty:"' + qty + '"}',
        success: function(data) {
            var inventoryStatus = data.d;
            if (inventoryStatus) {
                $container.html(inventoryStatus);
            } else {
                $container.html(retryLink);
                $(".stockretry").unbind("click").bind("click", stockCheckHandler);
            }
        },
        error: function() {
            $container.html(retryLink);
            $(".stockretry").unbind("click").bind("click", stockCheckHandler);
        }
    });

}


function initFavCategoryChoose() {

    $(".favcat-link").click(favCategoryEventHandler);

}

function favCategoryEventHandler() {

	var that = this;
    var offset = $(that).offset();
    var $parent = $(that).closest(".favcat-parent");
    var sku = $parent.find(".sku").text();
    var favgoto = false;
    var catid = "0";

    if (sku != '') {

        $("#favcat-container")
                    .css({ "top": "" + (offset.top - 50).toString() + "px", "left": "" + (offset.left + 10).toString() + "px" })
                    .show()
                    .click(function(targ) {
                        var $target = $(targ.target);
                        if ($target.is("a")) {
                            if ($target.attr("id") == 'favcat-submit') {
                                // add to faves
                                favgoto = $('input[name=favcat-goto]').is(':checked')
                                catid = $("select.favcat-choose").val();
                                $.ajax({
                                    type: "POST",
                                    url: "services.asmx/AddFavouriteToCategory",
                                    contentType: "application/json; charset=utf-8",
                                    dataType: "json",
                                    data: '{sku:"' + sku + '", catid:"' + catid + '"}',
                                    success: function() {
                                        //only change the text if it is a normal link - not a button
                                        if ($(that).hasClass('bt') == false) {
                                            $(that).html('<strong><em>Add to Favorites (added)</em></strong>');
                                        }
                                    }
                                });
                                // close or transfer to favourite page
                                if (favgoto) {
                                    $('input[name=favcat-goto]').attr('checked', false); //reset checkbox
                                    location.href = "favourites.aspx";
                                }
                                else {
                                    $("#favcat-container").hide();
                                }
                            } else {
                                // close
                                $("#favcat-container").hide();
                            }
							return false;
                        }
                    });

    } else {
        alert("A valid sku is required to Add to Favorites.");
    }

	return false;

}


function initBlockUI() {
    //init any elements attached to the 'blockUI' plugin here

    //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();
    })

}

function isValidPostalZipCode(postalZipCode) {

    var zipPat = /^((\d{5}-\d{4})|(\d{5})|([A-Z]\d[A-Z]\s*\d[A-Z]\d))$/; //allows middle space in Canadian Postal Code as well as lowercase letters
    if (!zipPat.test(postalZipCode)) {
        return false;
    }
    return true;

}

function initCartTaxEstimate() {

    $(".cart-taxestimate-link").click(cartTaxEstimate);

}

function cartTaxEstimate() {

    var that = this;
    var offset = $(that).offset();
    var zip = $("#ctl00_tb_zip").val();

    if ((zip == '') || !(isValidPostalZipCode(zip))) {
        $("#zip-container")
                .css({ "top": "" + (offset.top - 50).toString() + "px", "left": "" + (offset.left + 10).toString() + "px" })
                .show()
                .unbind("click").bind("click", function(targ) {
                    var $target = $(targ.target);
                    if ($target.is("a")) {
                        if ($target.attr("id") == 'zip-save') {
                            //ensure zip/postal code is valid format
                            if (isValidPostalZipCode($("#ctl00_tb_zip").val())) {
                                // save zip - run synchonously for cart page postback / cookie retrieval
                                $.ajax({
                                    type: "POST",
                                    timeout: 7000,
                                    url: "services.asmx/SetZipCodeCookie",
                                    contentType: "application/json; charset=utf-8",
                                    dataType: "json",
                                    data: '{zip: "' + $("#ctl00_tb_zip").val() + '"}',
                                    async: false
                                });
                                // close
                                $("#zip-container").hide();
                                //simulating click of the hidden asp:button control for cart recalc
                                $(".cart-taxestimate-submit").click();
                            } else {
                                alert("Please enter a valid Zip Code (US) or Postal Code (Canada).\n\neg. US Zip Code: 44240 or 44240-5555\n\neg. Canadian Postal Code: G3H 6A3");
                            }
                        } else {
                            // close
                            $("#zip-container").hide();
                        }
                    }
					return false;
                });
    } else {
        //simulating click of the hidden asp:button control for cart recalc
        $(".cart-taxestimate-submit").click();
    }

	return false;
	
}



