﻿/**********************************************
Master Load
**********************************************/
$(document).ready(function() {
    setHint();
    setScrollFollow();
});

/**********************************************
Force Postback
**********************************************/
forcePostBack = function(sender, e) {
    __doPostBack(sender, e);
}

umapPostBack = function (postbackCall, textBoxId) {
    __doPostBack(postbackCall, document.getElementById(textBoxId).value);
}

/**********************************************
Set Hint
***********************************************/
setHint = function() {
    $("[INPUT:text[title!='']").unbind("hint").hint();
}

/**********************************************
Set Scroll Follow
***********************************************/
setScrollFollow = function() {
    $(".ScrollFollow").scrollFollow({speed: 1000,offset: 0,killSwitch: '',onText: '',offText: ''});
}

/**********************************************
Open Modal Windows
***********************************************/
openModal = function(modalId) {
    $("#" + modalId).modal({
        overlay: 100
        , opacity: 80
        , overlayCss: { backgroundColor: '#c4daf0', 'padding-bottom': '20px'}
        , zIndex: 3001
        , position: ['10%', '']
        , closeClass: 'ModalClose'
        , appendTo: 'FORM'
        , persist: true
    });
}

openModalSmall = function(modalId) {
}

openModalMedium = function(modalId) {
}

openModalLarge = function(modalId) {
} 


/**********************************************
Refresh QuickView Shopping Cart
***********************************************/
function refreshQuickView() {
    $("[id $='QuickViewCart']").each(function() {
        this.contentWindow.location.reload(true);
    });
    //$("[id $='QuickViewCart']").attr("src", $("[id $='QuickViewCart']").attr("src"));
}

/**********************************************
Image Mouseover Events
***********************************************/
$(document).ready(function() {
    setImageHover();
});

function setImageHover() {
    var _objHover = null;
    $(".Hover").each(function() {
        if ($(this).attr("src") != null) {
            $(this).hover(function() {
                $(this).attr("src", $(this).attr("src").replace("_off", "_on"));
                $(this).attr("src", $(this).attr("src").replace("_down", "_off"));
            }, function() {
                $(this).attr("src", $(this).attr("src").replace("_on", "_off"));
                $(this).attr("src", $(this).attr("src").replace("_down", "_off"));
            });
        } else { //HyperLink 
            $(this).hover(function() {
                $(this).addClass("HoverText");
                if ($(this).find("IMG").length > 0
                    && $(this).find("IMG").attr("src") != null
                    && $(this).find("IMG").attr("src") != 'undefined') {
                    $(this).find("IMG").attr("src", $(this).find("IMG").attr("src").replace("_off", "_on"));
                    $(this).find("IMG").attr("src", $(this).find("IMG").attr("src").replace("_down", "_off"));
                }
            }, function() {
                $(this).removeClass("HoverText");
                if ($(this).find("IMG").length > 0
                    && $(this).find("IMG").attr("src") != null
                    && $(this).find("IMG").attr("src") != 'undefined') {
                    $(this).find("IMG").attr("src", $(this).find("IMG").attr("src").replace("_on", "_off"));
                    $(this).find("IMG").attr("src", $(this).find("IMG").attr("src").replace("_down", "_off"));
                }
            });
        }
    });
}

/**********************************************
Sliding Account Information 
***********************************************/
$(document).ready(function() {
    $(".btnOpenCloseAccountInfo").hover(function() {
        $(this).find("IMG:last").show();
    }, function() {
        $(this).find("IMG:last").hide(); 
    });
    $(".btnOpenCloseAccountInfo").click(function() {
        $("DIV[id*='AccountInfoWrapper']").slideToggle("slow", function() {
            if ($.cookie('LJCOOKIE_AccountInfoOpen') == '1') {
                $.cookie('LJCOOKIE_AccountInfoOpen', '0');
                $(".btnOpenCloseAccountInfo").find("IMG:first").attr("src", $(".btnOpenCloseAccountInfo").find("IMG:first").attr("src").replace("close", "open"));
            } else {
                $.cookie('LJCOOKIE_AccountInfoOpen', '1');
                $(".btnOpenCloseAccountInfo").find("IMG:first").attr("src", $(".btnOpenCloseAccountInfo").find("IMG:first").attr("src").replace("open", "close"));
            };
        });
    });
});

/**********************************************
Tab Events (including tab mouseover)
***********************************************/
$(document).ready(function() {
    //Handle Mouse Overs First
    $('div.Tabs ul.TabNavigation A IMG').click(function() {
        //Reset Tabs
        $('div.Tabs ul.TabNavigation A IMG').each(function() {
            $(this).attr("src", $(this).attr("src").replace("_down", "_off"))
        });
        //Cleanup Set Selected
        $(this).attr("src", $(this).attr("src").replace("_off", "_down"));
        $(this).attr("src", $(this).attr("src").replace("_on", "_down"));
    });

    var tabContainers = $('div.Tabs > div');
    tabContainers.hide().filter(':first').show();
    $('div.Tabs ul.TabNavigation A IMG').filter(':first').each(function() {
        $(this).attr("src", $(this).attr("src").replace("_off", "_down"));
    });
    $('div.Tabs ul.TabNavigation a').click(function() {
        tabContainers.hide();
        tabContainers.filter(this.hash).show();
        $('div.Tabs ul.TabNavigation a').removeClass('Selected');
        if ($(this).find('IMG').attr("src") != null) {
            $(this).find('IMG').attr("src", $(this).find('IMG').attr("src").replace("_on", "_down"));
        }
        return false;
    }).filter(':first').click();
});


/**********************************************
TabsTwo Events 
***********************************************/
$(document).ready(function() {
    $('DIV.TabsTwo UL.TabNavigation A').click(function() {
        var _button = $(this);
        var _hash = _button.attr("href");

        if (_hash == null || _hash == "")
            _hash = _button.attr("tabid");

        var _parent = _button.closest("DIV.TabsTwo");
        var _offset = _button.context.offsetLeft + (_button.width() / 2);

        _parent.find("DIV.TabContent:visible").hide();
        _parent.find("A.Selected").removeClass("Selected");
        _button.addClass("Selected");
        _parent.find("IMG.SelectedArrow").animate({ "left": _offset + "px" }, "slow");

        $("[id $= '" + _hash.replace("#", "") + "']").show();

        //Save the selected tab on the Default Page only. 
        if (document.location.pathname == "/"
            || document.location.pathname == "/Default.aspx") {
            $.cookie('LJCOOKIE_HomePage_Tab', _hash, { path: '/', expires: 1 });
        }
        if (typeof setUpSellSlider == 'function') {
            setUpSellSlider();
        }
        return false;
    });

    //If a cookie has been saved with a default Tab on the home page, 
    //then select that tab automatically on load. 
    var _cookieTabHash = $.cookie('LJCOOKIE_HomePage_Tab');
    if ((document.location.pathname == "/"
        || document.location.pathname == "/Default.aspx")
        && _cookieTabHash != null && _cookieTabHash != '') {
        $("[href $='" + _cookieTabHash + "'], [tabid $='" + _cookieTabHash + "']").each(function() {
            $(this).click();
        });
    } else {
        //Open the first tabs
        $("DIV.TabsTwo").each(function() {
            $(this).find("UL.TabNavigation A").filter(':first').click();
        });
    }
});

/**********************************************
Flyout Sub Menu
***********************************************/
$(document).ready(function() {
    $(".ListSquareHeaderHover").hover(function() {
        $(this).find(".ListSquareFlyoutWrapper").show();
    }, function() {
        $(this).find(".ListSquareFlyoutWrapper").hide();
    });
});


/**********************************************
Sub Page - Left Navigation
***********************************************/
$(document).ready(function() {
    $(".LeftNavigationHeader").click(function() { //Reset
        if ($(this).next().is(":hidden")) {
            $(".LeftNavigationHeader").removeClass("Selected");
            $(".LeftNavigationMenuList").slideUp("slow");
            
            $(this).next().slideDown("slow");
            $(this).addClass("Selected"); 
            return false;
        }
    });
    $(".LeftNavigationHeader").each(function() {
        if ($(this).attr("Selected") == 'true') {
            $(this).addClass("Selected");
            $(this).next().show();
        }
    });
});

/**********************************************
Sub Page - Right Anchor Navigation
***********************************************/
$(document).ready(function() {
    $(".GroupNavigationWrapper").find("A").click(function() {
        $(".GroupNavigationWrapper").find("A").removeClass("Selected");
        $(this).addClass("Selected");
    });
});

/**********************************************
UpSell Slider
***********************************************/
setUpSellSlider = function() {
    $('DIV.UpSellSlider').each(function() {

        $(this).find('UL.UpSellWrapper:visible').each(function() {
            var _wrapperWidth = 0;
            $(this).find('LI.UpSell').each(function() {
                _wrapperWidth += $(this).width() + 30;
            });

            $(this).width(_wrapperWidth);

            //Enable the Right Button
            if ($(this).parent().find('.UpSellWrapper').width() > 877 &&
                parseFloat($(this).parent().find('.UpSellWrapper').css("left").replace("px", "")) >= 0 ) {
                var _srcRight = $(this).parent().parent().find('A.RightSliderButton IMG').attr("src");
                _srcRight = _srcRight.replace("disabled", "enabled_off");
                $(this).parent().parent().find('A.RightSliderButton IMG').attr("src", _srcRight);
            }

        });

        $(this).find('A.LeftSliderButton').unbind("click").click(function() {
            slideLeft($(this));

        });
        $(this).find('A.RightSliderButton').unbind("click").click(function() {
            slideRight($(this));
        });

        slideLeft = function(obj) {
            var p = $(obj).closest('.UpSellSlider DIV.TabContent:visible');
            var w = p.find('.UpSellWrapper:visible');
            if (w.is(':animated')) {
                //Do Nothing. Wait until Animation is done
            } else {
                var wOffset = w.css("left");
                wOffset.replace('px', '');
                wOffset = parseInt(wOffset)
                if (wOffset < 20) {
                    wOffset += 857;
                    w.animate({ "left": wOffset + "px" }, function() {
                        //Enable the right slider button
                        var _srcRight = p.find('A.RightSliderButton IMG').attr("src");
                        _srcRight = _srcRight.replace("disabled", "enabled_off");
                        p.find('A.RightSliderButton IMG').attr("src", _srcRight);

                        var _srcLeft = p.find('A.LeftSliderButton IMG').attr("src");
                        if ((wOffset) >= 20) {
                            _srcLeft = _srcLeft.replace("_off", "").replace("_on", "").replace("_down", "").replace("enabled", "disabled");
                            p.find('A.LeftSliderButton IMG').attr("src", _srcLeft);
                        }
                    });
                }
            }
        }

        slideRight = function(obj) {
            var p = $(obj).closest('.UpSellSlider DIV.TabContent:visible');
            var w = p.find('.UpSellWrapper:visible');
            if (w.is(':animated')) {
                //Do Nothing. Wait until Animation is done
            } else {
                var wOffset = w.css("left");
                var pWidth = w.width();
                wOffset.replace('px', '');
                wOffset = parseInt(wOffset);
                pWidth = parseInt(pWidth);
                if (pWidth > 877 && ((wOffset * -1) < (pWidth - 877))) {
                    wOffset -= 857;
                    w.animate({ "left": wOffset + "px" }, function() {
                        var _srcLeft = p.find('A.LeftSliderButton IMG').attr("src");
                        _srcLeft = _srcLeft.replace("disabled", "enabled_off");
                        p.find('A.LeftSliderButton IMG').attr("src", _srcLeft);

                        var _srcRight = p.find('A.RightSliderButton IMG').attr("src");
                        if ((wOffset * -1 + 925) > (pWidth)) {
                            _srcRight = _srcRight.replace("_off", "").replace("_on", "").replace("_down", "").replace("enabled", "disabled");
                            p.find('A.RightSliderButton IMG').attr("src", _srcRight);
                        }
                    });
                }
            }
        }
    });
}


/**********************************************
Add To Cart
***********************************************/
function addItemToCart (skuid, qty) {
    var arr = new Array();
    var o = new Object();
    o.DOMObjectReferenceID = "";
    o.SKUID = skuid;
    o.Quantity = qty;
    arr.push(o);

    return AddBasketItems(null, arr);
}

function AddBasketItems(obj, itemList) {
   //Here is an Example. Make sure your control has an id so we can use it 
   //after the items are added to the basket. 
   //onclick='return AddItemToCart(this, {'DOMObjectReferenceID': this.id, "SKUID": 1280, "QuantityRequested": 1 });'
   //or
   //var arr = new Array(); 
   //var o = new Object(); 
   //o.DOMObjectReferenceID = "DOMid"; 
   //o.SKUID = "1234";
   //o.QuantityRequested = "1";
   //arr.push(o);

   //Create a Temporary Button when adding
   //items to the basket.
   var adding = $(obj).clone();
   adding.attr("ID", $(obj).attr("ID") + "_adding");
   adding.unbind('click', AddBasketItems).click(function() {
       return false; 
   }); //Disable Click
   if (adding.attr("tagName") == "A") {
       adding.find("IMG").attr("src", THEMEIMAGEPATH + "btn_103_add_to_cart_disabled.gif");
   } else if (adding.attr("tagName") == "INPUT") {
       adding.attr("src", THEMEIMAGEPATH + "btn_103_add_to_cart_disabled.gif");
    }
   $(obj).hide();
   $(obj).after(adding);

   try {
       BasketWebService.AddBasketItems(itemList, function(items) {
       if (items == null) {
               //if there was an error when adding the items to the basket, 
               //attempt to add items through the add-to-cart.aspx link method
                var addToCartLink = "add-to-cart.aspx?mode=javascript-error";
               for (var i = 0; i < itemList.length; i++) {
                   addToCartLink += "&itemid=" + itemList[i].SKUID + ":" + itemList[i].QuantityRequested;
               }
               window.location = addToCartLink;
           }

           var errorMessage = "";
           for (var i = 0; i < items.length; i++) {
               if (parseFloat(items[i].QuantityRequested) > parseFloat(items[i].QuantityAdded)) {
                   errorMessage += 'Sorry not enough stock was available for Item: ' + items[i].SKU + '. \r\n You asked for ' + items[i].QuantityRequested + ' but we only added ' + items[i].QuantityAdded + ' item(s) to the basket for you.\r\n\r\n';
               }
           }
           //Show the object and remove the temp object
           adding.remove(); //Remove the Temporary Button
           $(obj).show();

           if (errorMessage == '')
               displayItemAddedMessage();
           else {
               alert(errorMessage);
               //TODO: Open a clean Modal Window with a good layout. 
               //openModal($(".SM_FO_UMAP_WRAPPER").attr("ID"));
           }

           //Update the QuickView
           updateQuickBasket()
       }, function(result) {
           //if there was an error when adding the items to the basket, 
           //attempt to add items through the add-to-cart.aspx link method
           var addToCartLink = "add-to-cart.aspx?mode=javascript-error";
           for (var i = 0; i < itemList.length; i++) {
               addToCartLink += "&itemid=" + itemList[i].SKUID + ":" + itemList[i].QuantityRequested;
           }
           window.location = addToCartLink;
       });
   }
   catch (e) {
       //handle error
       alert(GENERICERROR); 
   }
   return false; 
}

//Updates the QuickBasket on the top of the page.
function updateQuickBasket() {
    $(".QB_QuickViewGrid").find(".ProgressWindow").show();
    try {
        BasketWebService.GetBasket(function(basket) {
            var bWrap = $(".QB_QuickViewGrid");
            var iList = bWrap.find("DIV.QB_QuickViewGridItem");
            var iNumber = 0;
            var iListCount = iList.length;

            if (basket.BasketItemList.length > 0) {
                $(".QB_EnabledCart").show();
                $(".QB_DisabledCart").hide();
                $(".QB_EmptyCart").hide();
            } else {
                $(".QB_EnabledCart").hide();
                $(".QB_DisabledCart").show();
                $(".QB_EmptyCart").show();
            }

            for (var i = 0; i < basket.BasketItemList.length; i++) {

                //Clone the Template or the last record if there are
                //no more available DOM objects. 
                if (i >= iListCount) {
                    var clone = bWrap.find("DIV.QB_QuickViewGridItem:last").clone(false);
                    iList.push(clone);
                    bWrap.append(clone);
                }

                var cItem = $(iList[iNumber]);
                var pName = basket.BasketItemList[i].ProductFullName + " (" + basket.BasketItemList[i].SKU + " )";
                cItem.find(".QB_Quantity").html(basket.BasketItemList[i].Quantity);
                cItem.find(".QB_Item").html("<a href='" + basket.BasketItemList[i].SKUSEOURL + ".aspx' title='" + pName + "' >" + pName + "</a>");
                cItem.find(".QB_CustomerPrice").html(formatCurrency(parseFloat(basket.BasketItemList[i].CustomerPriceExtended)));
                cItem.show();

                iNumber++;
            }

            //Hide the rest of the records until we are ready to show them again
            if (iNumber < iListCount) {
                for (var i = iNumber; i < iListCount; i++) {
                    var cItem = $(iList[i]);
                    cItem.hide();
                    iNumber++;
                }
            }

            $(".BasketSubTotal").html(basket.BasketSubTotalFormatted);
            $(".BasketItemCount").html(basket.BasketItemCount);

        }, function(error) {
            //alert(GENERICERROR); //TODO: figure out a better way to handle this. 
        });
    } catch (e) {
        //alert(GENERICERROR); //TODO: figure out a better way to handle this.
    }

    $(".QB_QuickViewGrid").find(".ProgressWindow").hide();
}

/**********************************************
HELPER FUNCTIONS
**********************************************/
function displayItemAddedMessage() {
    var msgHtml = $(document.createElement("DIV"));
    msgHtml.attr("id", "DisplayItemAddedMessage");
    msgHtml.addClass("ItemAddedWindow");
    msgHtml.html("Item(s) Added to Cart");
    $("BODY").append(msgHtml);

    msgHtml.css('top', ($(this).scrollTop() + 200) + "px");
    $(window).scroll(function() {
        msgHtml.css('top', ($(this).scrollTop() + 200) + "px");
    });

    msgHtml.fadeIn(200)
           .animate({ opacity: 1.0 }, 1000)
           .fadeOut(1000, function() {
               msgHtml.remove();
           });
}

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
    num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}
