/*
--------------------------------------------------

Regis - Franchise
application.js

Joe Morrow [joe.morrow@acquitygroup.com]
7/09/2008

Copyright © 2008 Acquity Group LLC

--------------------------------------------------
*/
$(document).ready(function() {

    // setup for IE6-specific treatments
    if ((!$.browser.msie) || (($.browser.version + 0) > 6)) {

        // loads the custom scrollbars (but not for IE6)
        $("#contentWrapper.resulted #rightContainer, #contentWrapper #productDetailContainer #productDetailDescrip, #cartTable #cartBodyScroller, #invoiceTable #invoiceBodyScroller, #resourceBodyScroller").jScrollPane({
            scrollbarWidth: 5,
            dragMinHeight: 26,
            dragMaxHeight: 26,
            wheelSpeed: 10
        });

        // set up the salon selector
        if ($("#salonSelectorScroller .conceptContainer").size() > 3) {
            $("#salonSelectorScroller").jScrollPane({
                wheelSpeed: 10,
                showArrows: true,
                animateTo: true
            });
            $('#contentWrapper.salonSelector .jScrollPaneContainer .jScrollArrowUp').empty().unbind().click(function() {
                $('#salonSelectorScroller')[0].scrollBy(-125);	// This is minus the height of one row (hard-coded, yes)
                return false;
                }
            ).appendTo("#storeController");
            $('#contentWrapper.salonSelector .jScrollPaneContainer .jScrollArrowDown').empty().unbind().click(function() {
                $('#salonSelectorScroller')[0].scrollBy(125);	// This is the height of one row (hard-coded, yes)
                return false;
                }
            ).appendTo("#storeController");
        } else
            $("#storeControllerHelp").hide();

        // Carousel (lite) scrollers for Store Selector section
        $("#salonSelectorScroller .conceptContainer").each(function() {
            if ($("li.conceptStore", $(this)).size() > 7) {
                var thisID = "#" + $(this).attr("id");
                $(thisID + " .visibleArea").jCarouselLite({
                    btnNext: thisID + " .rightController",
                    btnPrev: thisID + " .leftController",
                    visible: 7,
                    mouseWheel: false,
                    speed: 250,
                    circular: false
                });
            } else {
                $(".conceptController", $(this)).css("visibility", "hidden");
            }
        });

    } else {

/* Developer Note 6/18/2008:
1.  The top-level navigation menus for IE6 are now handled in /styles/ie6.css, so the Javascript code here has been removed.
*/
        // png fix (for IE6)
        $("[@src$=png], #storeInfo, #featuredThisWeek, #shoppingBag, #needHelp, .leftController, .rightController, #searchResultsController, #contentContainerHeader,#searchResultsController, div.modalStoreInfo div.left, div.modalArrowStoreInfo div.left").pngfix();

        // set up the salon selector's max width (IE6)
        /* This seems to cause more problems then good.
             if ($("#salonSelectorScroller").size() > 0) {
            var conceptWidth = 0;
            $("#salonSelectorScroller div.conceptContainer").each(function() {
                conceptWidth = Math.max($("li.conceptStore", $(this)).size(), conceptWidth);
            });

            $("#salonSelectorScroller .conceptContainer").width(conceptWidth * 100 + 226);
            $("#salonSelectorScroller .visibleArea").width(conceptWidth * 100);
        }*/

        // bottom/horizontal scrollbar for salon selector
        $('div#salonSelectorScroller div.visibleArea').each(function(){
            var conceptContainer = $(this).parent().parent('div.conceptContainer');
            var liWidth = $($(this).children('ul').children('li')[1]).width() + parseInt($($(this).children('ul').children('li')[1]).css('margin-right'));

            var listWidth = $(this).children('ul').children('li').length * liWidth;

            if (listWidth > $(this).width()) {
                $(this).css('width', listWidth + 'px');
                conceptContainer.css('width', listWidth + 226 + 'px');
            }
        })
    }

    // load custom select fields
    //$("select.filterDropDown").selectbox();
    //$("#paymentTypes select").selectbox();
    //$("#invoiceSearchContainer select").selectbox();
    //$("#conceptSelect").selectbox();
    //$("#paymentMethodContainer select").selectbox();
    $("#salonSelect").hide();

    // Image preload
    $.preloadImages("/media/REG001/images/static/franchise/nav/my-account-bckgrnd.gif",
        "/media/REG001/images/static/franchise/nav/order-history-bckgrnd.gif",
        "/media/REG001/images/static/franchise/nav/quick-order-bckgrnd.gif",
        "/media/REG001/images/static/franchise/nav/resources-bckgrnd.gif",
        "/media/REG001/images/static/franchise/nav/salon-selector-bckgrnd.gif",
        "/media/REG001/images/static/franchise/nav/shop-bckgrnd.gif",
        "/media/REG001/images/static/franchise/notify-modal-bckgrnd.png",
        "/media/REG001/images/static/franchise/notify-modal-bckgrnd-inner.gif",
        "/media/REG001/images/static/franchise/icons/modal-close.gif",
        "/media/REG001/images/static/franchise/store-info-header-modal.png",
        "/media/REG001/images/static/franchise/store-info-modal-inner.gif",
        "/media/REG001/images/static/franchise/store-info-modal.png",
        "/media/REG001/images/static/franchise/backbar-modal-bckgrnd.png",
        "/media/REG001/images/static/franchise/backbar-modal-inner.gif",
        "/media/REG001/images/static/franchise/language-modal-inner.gif",
        "/media/REG001/images/static/franchise/language-modal-bckgrnd.png",
        "/media/REG001/images/static/franchise/store-selector-modal.png");

    // Carousel (lite) scrollers for Featured This Week section
    $("#featuredThisWeek #itemContainer #visibleArea").jCarouselLite({
        btnNext: "#featuredThisWeek #itemContainer .rightController",
        btnPrev: "#featuredThisWeek #itemContainer .leftController",
        visible: 3,
        mouseWheel: true,
        speed: 250,
        circular: false
    });

    // Carousel (lite) scrollers for upsell section
    $("#upSellContainer #upSellVisibleArea").jCarouselLite({
        btnNext: "#upSellContainer .rightController",
        btnPrev: "#upSellContainer .leftController",
        vertical: true,
        visible: 4,
        mouseWheel: true,
        speed: 250,
        circular: false
    });

    // modals
    var timeoutID;

    var sleep = function(obj) {
        obj.w.show();
        var fader = ($.browser.msie) ? function() {obj.w.css("background-color", "#fff").fadeOut(500, function() {obj.w.jqmHide();});} : function() {obj.w.fadeOut(500, function() {obj.w.jqmHide();});};
        timeoutID = setTimeout(fader, 1700);
    };

    $("div.modalBackBar").jqm({
        ajax: '@href',
        trigger: ".openBackBarModal",
        modal: true,
        overlay: 0,
        toTop: true,
        nocache: true,
        onLoad: function(newObj) {
               // if session has timed out
            if ($(newObj.w).find('#loginContainer').html() != null) {
                window.location='/franchise/store/login.jsp';
                return;
            }
            newObj.w.pngfix();
        },
        onHide: function(newObj) {
            if ($(newObj.w).find('#thanksContainer').html() != null) {
                window.location='/franchise/store/checkout/cart.jsp';
                return;
            } else {
                newObj.o.remove();
                newObj.w.hide();
            }
        }
    });

    $("div.modalContainerNotify").jqm({
        ajax: "/franchise/store/modal/notify.jsp",
        overlay: 0,
        onShow: sleep,
        nocache: true
    });

    $("div.modalLanguage").jqm({
        ajax: "modals/language-modal.html",
        trigger: ".openLanguageModal",
        modal: true,
        overlay: 0,
        toTop: true,
        onLoad: function(newObj) {
            newObj.w.pngfix();
        }
    });

    $("div.modalStoreInfo").jqm({
        modal: true,
        overlay: 0,
        trigger: ".openStoreInfoModal",
        toTop: true,
        closeClass: "jqmClose"
    });

     $("div.backBarModalContainer #backBarOrderBttn").livequery("click", function() {
        var options = {
            /*target:'#ajaxContainer_backbar',*/
            success: function(responseText) {
                /* error condition */
                if ($(responseText).find('#ajaxContainer_backbar').html() != null) {
                    $('#ajaxContainer_backbar').html($(responseText).find('#ajaxContainer_backbar').html());
                    $("div#errorContainer").jqm({modal: true, overlay: 50, toTop: true, closeClass: "jqmErrorClose"});
                    $("div#errorContainer").jqmShow();
                } else if ($(responseText).find('#thanksModal').html() != null) {
                     /* we need to say thanks and update backbar main component */
                     $('#ajaxContainer_backbar').html($(responseText).find('#thanksModal').html());
                     $('#backBarOrder').html($(responseText).find('#backbarComponentUpdate').html());
                } else {
                    // exception not caught
                    $('#ajaxContainer_backbar').html(responseText);
                }
            }
        };
        $('#backBarOrderForm').ajaxSubmit(options);
        return false;
    });

    var defaultImg = $("#productPreviews #mainPreviewImage img").attr("src");
    $("#multiPreviewImages a").click(function() {
        var newImgSrc = $(this).attr("href");
        $(this).unbind("mouseout");
        $("#productPreviews #mainPreviewImage img").attr("src", newImgSrc);
        return false;
    });


    $("#multiPreviewImages a").mouseover(function() {
        var newImgSrc = $(this).attr("href");
        $("#productPreviews #mainPreviewImage img").attr("src", newImgSrc);
        $(this).mouseout(function() {
            $("#productPreviews #mainPreviewImage img").attr("src", defaultImg);
        });
    });

     $("#visibleArea li, #upSellVisibleArea li, #cartBody td.quantity").each(function() {
        if ($(this).hasClass("quantity"))		// For #cartBody
            var currentItem = "#" + $(this).parent().attr("id") + " td.quantity a";
        else									// For #upSellVisibleArea
            var currentItem = "#" + $(this).attr("id") + " a.buyNow";
        $("div.modalContainerBuyQty", $(this)).jqm({
            ajax: '@href',
            trigger: currentItem,
            modal: true,
            overlay: 0,
            toTop: true,
            onShow: function(newObj) {
                var currOffset = $(currentItem).offset();
                var topPos = currOffset.top - 50;
                var leftPos = currOffset.left - 30;
                newObj.w.css("top", topPos + "px");
                newObj.w.css("left", leftPos + "px");
                newObj.w.show();
            },
            onLoad: function(newObj) {
                // if session has timed out
                if ($(newObj.w).find('#loginContainer').html() != null) {
                    window.location='/franchise/store/login.jsp';
                    return;
                }
                //newObj.w.add("img", newObj.w).pngfix();
            }
        });
        return $(this);
    });

    $("#invoiceBody td.salonID, #invoiceBody td.paySalonID, #resourceBody td.orderSalonID, #resourceBody td.userSalonID").each(function() {
        if ($(this).hasClass("orderSalonID"))
            var currentItem = "#" + $(this).parent().attr("id") + " td.orderSalonID a";
        else if ($(this).hasClass("userSalonID"))
            var currentItem = "#" + $(this).parent().attr("id") + " td.userSalonID a";
        else if ($(this).hasClass("salonID"))
            var currentItem = "#" + $(this).parent().attr("id") + " td.salonID a";
        else if ($(this).hasClass("paySalonID"))
            var currentItem = "#" + $(this).parent().attr("id") + " td.paySalonID a";

        $("div.modalArrowStoreInfo", $(this)).jqm({
            trigger: currentItem,
            modal: true,
            overlay: 0,
            toTop: true,
            onShow: function(newObj) {
                var currOffset = $(currentItem).offset();
                var topPos = currOffset.top - 107;
                var leftPos = currOffset.left + 19;
                newObj.w.css("top", topPos + "px");
                newObj.w.css("left", leftPos + "px");
                newObj.w.show();
            },
            onLoad: function(newObj) {
                //instead of using ajax, specify here what content to use - which div to display
                $(newObj.w).replaceWith($("div#modalArrowStoreInfo_" + $(currentItem).attr("id")));
                //newObj.w.add("img", newObj.w).pngfix();
            }
        });
        return $(this);
    });

    // updating quantity on cart page
    $("#id_modalContainerCartBuyQty #updateQtyBttn").livequery("click", function() {
        var visibleModal = $(this).parents("div.modalContainerBuyQty");
        var fader = function() {
            visibleModal.css("background-color", ($.browser.msie) ? "#fff" : "transparent").fadeOut("slow",
            function() {
                visibleModal.jqmHide();
            });
        };
        var reload = function(){
            window.location='/franchise/store/checkout/cart.jsp';
        };
        var options = {
            data: {update_line_quantity: "submitType"},
            success: function(responseText) {
                if (responseText.indexOf('errorContainer') != -1) {
                    //replace the form with the one that came back - it contains the markers for fields with errors
                    $("#ajaxContainer_id").replaceWith($(responseText).find("#ajaxContainer_id"));
                    $("div#errorContainer").jqm({modal: true, overlay: 50, toTop: true, closeClass: "jqmErrorClose"});
                    $("div#errorContainer").jqmShow();
                } else if (responseText.indexOf('notifyModalContainer') != -1) {
                    //update the ajax container with the response html - the notification content
                    $("#ajaxContainer_id").html(responseText);
                    setTimeout(fader, 1700);
                    setTimeout(reload,1800);
                } else {
                    // error page
                    //alert('yet some othar case - probably exception');
                }
            }
        };
        $('#checkout_cart_id').ajaxSubmit(options);
        return false;
    });
    // updating quantity on cart page enter key
    $("#id_modalContainerCartBuyQty #buyNowQty").livequery("keypress", function(e) {
        var keyCode = e.charCode || e.keyCode;
        if (keyCode == 13) {
            var visibleModal = $(this).parents("div.modalContainerBuyQty");
            var fader = function() {
                visibleModal.css("background-color", ($.browser.msie) ? "#fff" : "transparent").fadeOut("slow",
                function() {
                    visibleModal.jqmHide();
                });
            };
            var reload = function(){
                window.location='/franchise/store/checkout/cart.jsp';
            };
            var options = {
                data: {update_line_quantity: "submitType"},
                success: function(responseText) {
                    if (responseText.indexOf('errorContainer') != -1) {
                        //replace the form with the one that came back - it contains the markers for fields with errors
                        $("#ajaxContainer_id").replaceWith($(responseText).find("#ajaxContainer_id"));
                        $("div#errorContainer").jqm({modal: true, overlay: 50, toTop: true, closeClass: "jqmErrorClose"});
                        $("div#errorContainer").jqmShow();
                    } else if (responseText.indexOf('notifyModalContainer') != -1) {
                        //update the ajax container with the response html - the notification content
                        $("#ajaxContainer_id").html(responseText);
                        setTimeout(fader, 1700);
                        setTimeout(reload,1800);
                    } else {
                        // error page
                        //alert('yet some othar case - probably exception');
                    }
                }
            };
            $('#checkout_cart_id').ajaxSubmit(options);
            return false;
        }
    });

    // add to cart from shopping cart cross sells
    $("#id_modalContainerCartBuyQty #buyNowCartCrossSellBttn").livequery("click", function() {
        var visibleModal = $(this).parents("div.modalContainerBuyQty");
        var fader = function() {
            visibleModal.css("background-color", ($.browser.msie) ? "#fff" : "transparent").fadeOut("slow",
            function() {
                visibleModal.jqmHide();
            });
        };
        var reload = function(){
            window.location='/franchise/store/checkout/cart.jsp';
        };
        var options = {
            data: {add_to_cart: "submitType"},
            success: function(responseText) {
                if (responseText.indexOf('errorContainer') != -1) {
                    //replace the form with the one that came back - it contains the markers for fields with errors
                    $("#ajaxContainer_id").replaceWith($(responseText).find("#ajaxContainer_id"));
                    $("div#errorContainer").jqm({modal: true, overlay: 50, toTop: true, closeClass: "jqmErrorClose"});
                    $("div#errorContainer").jqmShow();
                } else if (responseText.indexOf('notifyModalContainer') != -1) {
                    //update the ajax container with the response html - the notification content
                    $("#ajaxContainer_id").html(responseText);
                    setTimeout(fader, 1700);
                    setTimeout(reload,1800);
                } else {
                    // error page
                    //alert('yet some othar case - probably exception');
                }
            }
        };
        $('#checkout_cart_id').ajaxSubmit(options);
        return false;
    });

    // add to cart from shopping cart cross sells enter key
    $("#id_modalContainerCartBuyQty #buyNowQty").livequery("keypress", function(e) {
        var keyCode = e.charCode || e.keyCode;
        if (keyCode == 13) {
            var visibleModal = $(this).parents("div.modalContainerBuyQty");
            var fader = function() {
                visibleModal.css("background-color", ($.browser.msie) ? "#fff" : "transparent").fadeOut("slow",
                function() {
                    visibleModal.jqmHide();
                });
            };
            var reload = function(){
                window.location='/franchise/store/checkout/cart.jsp';
            };
            var options = {
                data: {add_to_cart: "submitType"},
                success: function(responseText) {
                    if (responseText.indexOf('errorContainer') != -1) {
                        //replace the form with the one that came back - it contains the markers for fields with errors
                        $("#ajaxContainer_id").replaceWith($(responseText).find("#ajaxContainer_id"));
                        $("div#errorContainer").jqm({modal: true, overlay: 50, toTop: true, closeClass: "jqmErrorClose"});
                        $("div#errorContainer").jqmShow();
                    } else if (responseText.indexOf('notifyModalContainer') != -1) {
                        //update the ajax container with the response html - the notification content
                        $("#ajaxContainer_id").html(responseText);
                        setTimeout(fader, 1700);
                        setTimeout(reload,1800);
                    } else {
                        // error page
                        //alert('yet some othar case - probably exception');
                    }
                }
            };
            $('#checkout_cart_id').ajaxSubmit(options);
            return false;
        }
    });

    // featured items add to cart, product cross sells add to cart
    $("div.buyQtyModalContainer form#checkout_cart_id #buyNowQtyBttn").livequery("click", function() {
        var visibleModal = $(this).parents("div.modalContainerBuyQty");
        var fader = function() {
            visibleModal.css("background-color", ($.browser.msie) ? "#fff" : "transparent").fadeOut("slow",
            function() {
                visibleModal.jqmHide();
            });
        };
        var options = {
            data: {add_to_cart: "submitType"},
            success: function(responseText) {
                if (responseText.indexOf('errorContainer') != -1) {
                    //replace the form with the one that came back - it contains the markers for fields with errors
                    $("#ajaxContainer_id").replaceWith($(responseText).find("#ajaxContainer_id"));
                    $("div#errorContainer").jqm({modal: true, overlay: 50, toTop: true, closeClass: "jqmErrorClose"});
                    $("div#errorContainer").jqmShow();
                } else if (responseText.indexOf('outer') != -1) {
                    //update the ajax container with the response html - the notification content
                    $("#shoppingBag").replaceWith($(responseText).find("#shoppingBag"));
                    $("#productPromoContainer").replaceWith($(responseText).find("#productPromoContainer"));
                    $("form#checkout_cart_id").replaceWith($(responseText).find("#ajaxContainer_modal div.notifyModalContainer"));
                    setTimeout(fader, 1700);
                } else {
                    // error page
                    //alert('yet some othar case - probably exception');
                }
            }
        };
        $('#checkout_cart_id').ajaxSubmit(options);
        return false;
    });

     // featured items add to cart, product cross sells add to cart enter key
    $("div.buyQtyModalContainer form#checkout_cart_id #buyNowQty").livequery("keypress", function(e) {
        var keyCode = e.charCode || e.keyCode;
        if (keyCode == 13) {
            var visibleModal = $(this).parents("div.modalContainerBuyQty");
            var fader = function() {
                visibleModal.css("background-color", ($.browser.msie) ? "#fff" : "transparent").fadeOut("slow",
                function() {
                    visibleModal.jqmHide();
                });
            };
            var options = {
                data: {add_to_cart: "submitType"},
                success: function(responseText) {
                    if (responseText.indexOf('errorContainer') != -1) {
                        //replace the form with the one that came back - it contains the markers for fields with errors
                        $("#ajaxContainer_id").replaceWith($(responseText).find("#ajaxContainer_id"));
                        $("div#errorContainer").jqm({modal: true, overlay: 50, toTop: true, closeClass: "jqmErrorClose"});
                        $("div#errorContainer").jqmShow();
                    } else if (responseText.indexOf('outer') != -1) {
                        //update the ajax container with the response html - the notification content
                        $("#shoppingBag").replaceWith($(responseText).find("#shoppingBag"));
                        $("#productPromoContainer").replaceWith($(responseText).find("#productPromoContainer"));
                        $("form#checkout_cart_id").replaceWith($(responseText).find("#ajaxContainer_modal div.notifyModalContainer"));
                        setTimeout(fader, 1700);
                    } else {
                        // error page
                        //alert('yet some othar case - probably exception');
                    }
                }
            };
            $('#checkout_cart_id').ajaxSubmit(options);
            return false;
        }
    });
    // product listing,q product details, and quick order
    $("div.productContainer a.buyNow, div.productContainer a.reserve, form#quickOrderForm #add, #productDetailQty #details_add").livequery("click", function() {
        if ($(this).hasClass("openNotifyModal")) {
            var form = $(this).parent().parent();
        } else {
            var form = $(this).parent();
        }
        var options = {
            //target:updateDivs,
            data: {add_to_cart: "submitType"},
            success: function(responseText) {
               // error case
               // CANNOT USE JQUERY ON responseText -> IE WILL GIVE secruity popup
               // work around for ie problem
               if (responseText.indexOf("errorContainer") > -1) {
                   // only append if not already added to body
                   pos = responseText.indexOf("<div id=\"errorParent\">");
                   responseText = responseText.substring(pos);
                   pos = responseText.indexOf("<div class=\"bottom\"></div>");
                   responseText = responseText.substring(0,pos+62);
                   if ($("#errorContainer").html() == null) {
                        $("body").append(responseText);
                   } else {
                       $("#errorContainer").replaceWith(responseText);
                   }
                   $("div#errorContainer").jqm({modal: true, overlay: 50, toTop: true, closeClass: "jqmErrorClose"});
                   $("div#errorContainer").jqmShow();
                   $("div#errorContainer a.jqmErrorClose").focus();
               } else {
                   $("#shoppingBag").replaceWith($(responseText).find("#shoppingBag"));
                   $("#productPromoContainer").replaceWith($(responseText).find("#productPromoContainer"));

                   if (timeoutID != null) {
                        clearTimeout(timeoutID);
                   }
                   $("div.modalContainerNotify").jqmHide();
                   setTimeout(function(){$("div.modalContainerNotify").jqmShow();}, 500);
                }
            }
        };
        form.ajaxSubmit(options);
        return false;
    });
   // enter submit on product listing,q product details, and quick order
   $("div.productContainer .quantityInput, #productDetailQty #productQty, #sidebarContainer form#quickOrderForm #quickItem").bind("keypress",function(e) {
       var keyCode = e.charCode || e.keyCode;
       if (keyCode == 13 || (keyCode == 9 && $(this).attr("id") == "quickItem")) {
           if ($(this).attr("id") == "productQty") {
               var form = $(this).parent().parent();
           } else {
               var form = $(this).parent();
           }
           var options = {
               //target:updateDivs,
               data: {add_to_cart: "submitType"},
               success: function(responseText) {
                   // error case
                   // CANNOT USE JQUERY ON responseText -> IE WILL GIVE secruity popup
                   // work around for ie problem
                   if (responseText.indexOf("errorContainer") > -1) {
                       // only append if not already added to body
                       pos = responseText.indexOf("<div id=\"errorParent\">");
                       responseText = responseText.substring(pos);
                       pos = responseText.indexOf("<div class=\"bottom\"></div>");
                       responseText = responseText.substring(0,pos+62);
                       if ($("#errorContainer").html() == null) {
                            $("body").append(responseText);
                       } else {
                           $("#errorContainer").replaceWith(responseText);
                       }
                       $("div#errorContainer").jqm({modal: true, overlay: 50, toTop: true, closeClass: "jqmErrorClose"});
                       $("div#errorContainer").jqmShow();
                       $("div#errorContainer a.jqmErrorClose").focus();
                   } else {
                       $("#shoppingBag").replaceWith($(responseText).find("#shoppingBag"));
                       $("#productPromoContainer").replaceWith($(responseText).find("#productPromoContainer"));

                       if (timeoutID != null) {
                            clearTimeout(timeoutID);
                       }
                       $("div.modalContainerNotify").jqmHide();
                       setTimeout(function(){$("div.modalContainerNotify").jqmShow();}, 500);
                   }
               }
           };
           form.ajaxSubmit(options);
           return false;
       }

   });
   $("form#quickOrderForm #quickQty").bind("keypress", function(e){
       var keyCode = e.charCode || e.keyCode;
       if (keyCode == 13 || keyCode == 9) {
               $(this).parent().children("#quickItem").val('');
               $(this).parent().children("#quickItem").focus();
               return false;
       }
   });

   var ajaxManager1 = $.manageAjax({manageType: 'sync', maxReq: 0});
   // Submit the quick order page form on Enter keypress
   $("#leftContent form#quickOrderForm #quickItem").bind("keypress",function(e) {
        var keyCode = e.charCode || e.keyCode;
        if (keyCode == 13 || keyCode == 9) { //enter or tab key pressed
            //only submit the form if error modal is not being displayed
            if ($("div#errorContainer").length > 0 && $("div#errorContainer").css("display") == "block") {
                //close the error modal
                $("div#errorContainer").jqmHide();
            } else {
                var reload = function(){
                    window.location='/franchise/store/checkout/quick_order.jsp';
                }
                var dataFields = $("form#quickOrderForm").formToArray();
                dataFields.push({name: 'add_item', value: 'submitType'});
                var options = {
                    //data: {add_item: "submitType"},
                    data: dataFields,
                    success: function(responseText) {
                        // error case
                       // CANNOT USE JQUERY ON responseText -> IE WILL GIVE secruity popup DONT KNOW WHY
                       // work around for ie 6.0 problem
                       if (responseText.indexOf("errorContainer") > -1) {
                           // only append if not already added to body
                           pos = responseText.indexOf("<div id=\"errorParent\">");
                           responseText = responseText.substring(pos);
                           pos = responseText.indexOf("<div class=\"bottom\"></div>");
                           responseText = responseText.substring(0,pos+62);

                           if ($("#errorContainer").html() == null) {
                                $("body").append(responseText);

                           } else {
                               // replace if overlay does not exist
                               if ($(".jqmOverlay").html() == null) {
                                  $("#errorContainer").replaceWith(responseText);
                               } else {
                                   // if overlay exists append
                                   pos = responseText.indexOf("<div class=\"content\">");
                                   var contentHtml = responseText.substring(pos);
                                   pos = contentHtml.indexOf("</div>");
                                   var content = contentHtml.substring(21,pos);
                                   $("#errorContainer #errorPopUp .content").append("<br\>"+content);
                               }
                           }
                           $("div#errorContainer").jqm({modal: true, overlay: 50, toTop: true, closeClass: "jqmErrorClose"});
                           $("div#errorContainer").jqmShow();
                           $("div#errorContainer a.jqmErrorClose").focus();

                        } else {
                            // empty cart
                            if ($("#cartTable").html() == null) {
                                $("#emptyCart").remove();
                                $("#leftContent").append($(responseText).find("#fullCart"));
                            } else {
                                $("#fullCart").replaceWith($(responseText).find("#fullCart"));
                            }
                            $("#rightContainer").replaceWith($(responseText).find("#rightContainer"));
                            reloadJSCart();
                        }
                    },
                    type: "POST",
                    url: $("form#quickOrderForm").attr("action")
                };
                $("#quickItem").val('');
                $("#quickQty").val('');
                $("#quickQty").focus();
                ajaxManager1.add(options);
            }
            return false;
        }
    });

    $("form#invoiceSearchForm").keypress(function(obj) {
        var keyCode = obj.charCode || obj.keyCode;
        if (keyCode == 13) { //enter key pressed
            $("form#invoiceSearchForm input#invoiceSearchSubmit").click();
        }
    });

    $("form#schedPmtSearchForm").keypress(function(obj) {
        var keyCode = obj.charCode || obj.keyCode;
        if (keyCode == 13) { //enter key pressed
            $("form#schedPmtSearchForm input#schedPmtSearchSubmit").click();
        }
    });

    $("div#paymentMethodContainerTop fieldset").keypress(function(obj) {
        var keyCode = obj.charCode || obj.keyCode;
        if (keyCode == 13) { //enter key pressed
            $("input#paymentMethodSubmit").click();
        }
    });

    // Store Selector hovers
    if ($("div.conceptContainer div.visibleArea li.conceptStore a").size() > 0) {

        $("body").append('<div class="modalSelectedStore"></div>');

        $("div.conceptContainer div.visibleArea li.conceptStore a").mouseover(function() {
            $("div.modalSelectedStore").jqmHide();
            $(this).click();

            var currModal = $(this).parent().find("div.selectStoreModalWrapper").html();
            $("div.modalSelectedStore").empty();
            $("div.modalSelectedStore").prepend(currModal);
        });

        $("div.modalSelectedStore").jqm({
            trigger: "div.conceptContainer div.visibleArea li.conceptStore a",
            overlay: 0,
            toTop:true,
            onShow: function(newObj) {
                var currOffset = $(newObj.t).offset();
                var topPos = currOffset.top;
                var leftPos = currOffset.left - 47;
                newObj.w.css("top", topPos + "px");
                newObj.w.css("left", leftPos + "px");
                $(newObj.t).parent().addClass("selected");
                newObj.w.show();
                newObj.w.pngfix();
            },
            onHide: function(newObj) {
                $(newObj.t).parent().removeClass("selected");
                newObj.w.hide();
            }
        });

        $("div.modalSelectedStore").bind("mouseleave", function() {
            $(this).jqmHide();
        });

    }

    //Top Nav Menu Pop Up Modal
    $("body").append('<div class="modalMenuPopUp"></div>');

    var menuMod = $("div#navSystem ul#mainLevel li#navShop").find("div#topNavMenuPopUpWrapper").html();
    $("div.modalMenuPopUp").empty();
    $("div.modalMenuPopUp").prepend(menuMod);

    $("div.modalMenuPopUp").jqm({
        trigger: "div#navSystem ul#mainLevel > li > a.openMenuPopUpModal",
        modal: true,
        overlay: 0,
        toTop:true,
        onShow: function(newObj) {
            var currOffset = $(newObj.t).offset();
            var leftPos = currOffset.left - 47;
            newObj.w.css("left", leftPos + "px");
            newObj.w.show();
            newObj.w.pngfix();
        },
        onHide: function(newObj) {
            $("#navSystem #mainLevel > .selected").removeClass("selected");
            $("#navSystem #mainLevel > .default").addClass("selected");
            //hide the overlay and modal
            newObj.o.hide();
            newObj.w.hide();
        }
    });


    // Invoice table checkbox initial states
    $('#invoiceBody .invoiceCheck input:checked').each(function() {
        $(this).parent().parent().addClass('selected');
    });

    // Invoice table check all
    $('#invoiceHeader .invoiceCheck input').click(function() {
        if ($(this).attr('checked')) {
            $(this).parents('#invoiceTable').find('#invoiceBody .invoiceCheck input').attr('checked', 'checked').parent().parent().each(function() {
                $(this).addClass('selected');
            });
        } else {
            $(this).parents('#invoiceTable').find('#invoiceBody .invoiceCheck input').removeAttr('checked').parent().parent().each(function() {
                $(this).removeClass('selected');
            });
        }
    });

    // Invoice table highlight toggle
    $('#invoiceBody .invoiceCheck input').click(function() {
        var thisRow = $(this).parent().parent();
        if ($(this).attr('checked')) {
                thisRow.addClass('selected');
        } else {
                thisRow.removeClass('selected');
                $('#invoiceHeader .invoiceCheck input').removeAttr('checked');
        }
    });

    // Clear Invoice Payment Amounts
    $("#invoicePaymentForm #bottomContent #clearAllAmounts").click(function() {
        $("#invoiceBody input").each(function() {
            $(this).attr("value", "");
        });
    });

    // Proper sizes for the Custom select boxes
    $("#invoiceSearchContainer #invoiceSearchForm div.select div.selectbox-wrapper, #invoiceSearchContainer #invoiceSearchForm div.invoiceSearchShow_container.div.selectbox-wrapper").css("width", "108px");
    $("#savedPayOpts_container.selectbox-wrapper").css("width", "195px");
    $("#newCredCardType_container.selectbox-wrapper").css("width", "135px");
    $("#newCredCardExpMonth_container.selectbox-wrapper").css("width", "123px");
    $("#newCredCardExpYear_container.selectbox-wrapper").css("width", "59px");
    $("#invoiceSearchFromMonth_container.selectbox-wrapper, #invoiceSearchToMonth_container.selectbox-wrapper").css("width", "49px");
    $("#invoiceSearchFromYear_container.selectbox-wrapper, #invoiceSearchToYear_container.selectbox-wrapper").css("width", "51px");


    // Toplevel Navigation Menu Hovers
    $("#navSystem #mainLevel > .selected").addClass("default");
    $("#navSystem #mainLevel > li > a").mouseover(function() {
        $("#navSystem #mainLevel > .selected").removeClass("selected");
        $(this).parent().addClass("selected");
        return false;
    });
    $("#navSystem").bind("mouseleave", function() {
        if ($("div.modalMenuPopUp").css("display") == "none") {
            $("#navSystem #mainLevel > .selected").removeClass("selected");
            $("#navSystem #mainLevel > .default").addClass("selected");
        }
        return false;
    });


    //Error Pop Up Modal
    //if the error div exists, display it
    $("div#errorContainer").jqm({
        modal: true,
        overlay: 50,
        toTop: true,
        closeClass: 'jqmErrorClose'
    });
    $("div#errorContainer").jqmShow();


    $("div#errorContainer").livequery("keypress", function(e) {
        var keyCode = e.charCode || e.keyCode;
        if (keyCode == 13) { //enter key pressed
            $(this).jqmHide();
            //move focus back to the quick order qty field
            $('form#quickOrderForm input#quickQty').focus();
        }
    });

    //set focus to the qty field in the quick order component
    $('form#quickOrderForm input#quickQty').focus();

});

// Image Preloader
jQuery.preloadImages = function() {
    for (var i=0; i<arguments.length; i++) {
        jQuery("<img>").attr("src", arguments[i]);
    }
}
function submitForm(formId, inputButtonName) {
    theForm = document.getElementById(formId);
    theForm.elements[inputButtonName].click();
}
var formValid = true;
function checkIfFormValid(targetBtn) {
    if (formValid == true) {
        formValid = false;
        return true;
    } else {
        targetBtn.disabled = true;
        return false;
    }
}
function disableCreditCardElements() {
    cForm = document.getElementById('openInvoicesForm');
    cForm.elements['IVC_CREDIT_CARD<>cardBrand_cd'].disabled = true;
    cForm.elements['IVC_CREDIT_CARD<>cardNum'].disabled = true;
    cForm.elements['IVC_CREDIT_CARD<>cardNum'].value = '';
    cForm.elements['IVC_CREDIT_CARD<>cardholderName'].disabled = true;
    cForm.elements['IVC_CREDIT_CARD<>cardholderName'].value = '';
    cForm.elements['IVC_CREDIT_CARD<>cardVerifyNum'].disabled = true;
    cForm.elements['IVC_CREDIT_CARD<>cardVerifyNum'].value = '';
    cForm.elements['IVC_CREDIT_CARD<>cardMonth_cd'].disabled = true;
    cForm.elements['IVC_CREDIT_CARD<>cardMonth_cd'].value = '';
    cForm.elements['IVC_CREDIT_CARD<>cardYear_cd'].disabled = true;
    cForm.elements['IVC_CREDIT_CARD<>cardYear_cd'].value = '';
}
function enableCreditCardElements() {
    cForm = document.getElementById('openInvoicesForm');
    cForm.elements['IVC_CREDIT_CARD<>cardBrand_cd'].disabled = false;
    cForm.elements['IVC_CREDIT_CARD<>cardNum'].disabled = false;
    cForm.elements['IVC_CREDIT_CARD<>cardholderName'].disabled = false;
    cForm.elements['IVC_CREDIT_CARD<>cardholderName'].value = 'Name on Card*';
    cForm.elements['IVC_CREDIT_CARD<>cardVerifyNum'].disabled = false;
    cForm.elements['IVC_CREDIT_CARD<>cardVerifyNum'].value = 'CVN Number*';
    cForm.elements['IVC_CREDIT_CARD<>cardMonth_cd'].disabled = false;
    cForm.elements['IVC_CREDIT_CARD<>cardMonth_cd'].value = '';
    cForm.elements['IVC_CREDIT_CARD<>cardYear_cd'].disabled = false;
    cForm.elements['IVC_CREDIT_CARD<>cardYear_cd'].value = '';
}

function selectLink(target) {
    location.href = $(target).children('option:selected').val();
}

function submitBrandSearch(brand) {
    $("form#brandSearchForm input#keyword").val(brand);
    $("form#brandSearchForm input#submitButton").click();
}
function submit_forgot_password() {
    var loginForm = document.getElementById('loginForm');
    user = loginForm.elements['LOGIN<>userid'].value;
    passwordForm = document.getElementById('forgot_password');
    passwordForm.elements['FORGOT_PASSWORD<>email'].value = user;
    passwordForm.submit();
}

function popupWindow(lnk, h, w) {
    var topOffset = (screen.height - h) / 2;
    var leftOffset = (screen.width - w) / 2;
    settings='width='+w+',height='+h+',top='+topOffset+',left='+leftOffset;
    name='_blank';
    var win = window.open(lnk,name,settings);
}

function newWindow(lnk) {
    var win = window.open(lnk, "fullscreen");
}

function selectSavedPayment(target) {
    if (target.selectedIndex == 0) {
        $("input#savedPayOpt").removeAttr('checked');
    } else {
        $("input#savedPayOpt").attr('checked', 'checked');
    }
}
function selectNewCC() {
    $("input#newCredCard").attr('checked', 'checked');
}

function reformatDate(x){
    var y=document.getElementById(x).value;
    y = y.replace(/\./g, "/");
    y = y.replace(/-/g, "/");

    //Change 05062009 to 05/06/2009
    if( y.length == 8 && y.indexOf("/") == -1 ){
        y = y.substring(0,2) + "/" + y.substring(2,4) + "/" + y.substring(4,8);
    }
    //Change 05/06/09 to 05/06/CC09
    if( y.length == 8 && y.indexOf("/") > 1 ){
        y = y.substring(0,6) + "20" + y.substring(6,8);
    }
    //Change 050609 to 05/06/CC09
    if( y.length == 6 ){
        y = y.substring(0,2) + "/" + y.substring(2,4) + "/20" + y.substring(4,6);
    }

    document.getElementById(x).value=y;
}

function reloadJSCart() {

    if ((!$.browser.msie) || (($.browser.version + 0) > 6)) {
        // load scroll bar for cart
        $("#cartTable #cartBodyScroller").jScrollPane({
            scrollbarWidth: 5,
            dragMinHeight: 26,
            dragMaxHeight: 26,
            wheelSpeed: 10
        });
        //cross sell scroller
        // Carousel (lite) scrollers for upsell section
        $("#upSellContainer #upSellVisibleArea").jCarouselLite({
            btnNext: "#upSellContainer .rightController",
            btnPrev: "#upSellContainer .leftController",
            vertical: true,
            visible: 4,
            mouseWheel: true,
            speed: 250,
            circular: false
        });
    }

    $("#visibleArea li, #upSellVisibleArea li, #cartBody td.quantity").each(function() {
        if ($(this).hasClass("quantity"))		// For #cartBody
            var currentItem = "#" + $(this).parent().attr("id") + " td.quantity a";
        else									// For #upSellVisibleArea
            var currentItem = "#" + $(this).attr("id") + " a.buyNow";
        $("div.modalContainerBuyQty", $(this)).jqm({
            ajax: '@href',
            trigger: currentItem,
            modal: true,
            overlay: 0,
            toTop: true,
            onShow: function(newObj) {
                var currOffset = $(currentItem).offset();
                var topPos = currOffset.top - 50;
                var leftPos = currOffset.left - 30;
                newObj.w.css("top", topPos + "px");
                newObj.w.css("left", leftPos + "px");
                newObj.w.show();
            },
            onLoad: function(newObj) {
                // if session has timed out
                if ($(newObj.w).find('#loginContainer').html() != null) {
                    window.location='/franchise/store/login.jsp';
                    return;
                }
                //newObj.w.add("img", newObj.w).pngfix();
            }
        });
        return $(this);
    });
}
