(function($) {
    var site = window.site = {
        data: {
        // js data
    },
    func: {
        // commonly used site specific functions
        setupHeaderNavigation: function() {
            /* top nav hover */
            var menuTimer;
            var navItemSecondaryIndex;
            $("#siteHdr #nav > li").each(function(item, i) {
                $(this).hover(function() {
                    if (menuTimer != "undefined") {
                        clearTimeout(menuTimer);
                        lib.layer.remove("#tierThreeLayer");
                    }
                    $("#nav > li").removeClass("navHighlight1");
                    $(this).addClass("navHighlight1");
                    $("li:eq(0)", this).addClass("first");

                    /* Add the menu to body, and setup hover */
                    var highestnavitem = this;
                    var wPos = lib.screen.position();
                    var wSize = lib.screen.size();
                    var menuLayerSelector = "#hdrNavigationLayer";
                    liPositionX = lib.utils.getPosition(this)[0][0] + (1);
                    liPositionY = lib.utils.getPosition(this)[0][1] + (26); // navbar position plus height of bar

                    if ($("ul", this).html() != null) {
                        var ulHTML = "<ul class='tiertwo'>" + $("ul", this).html() + "</ul>";
                        lib.layer.create(menuLayerSelector, {
                            defaultContent: ulHTML,
                            xPos: liPositionX,
                            yPos: liPositionY
                        });
                    }

                    $("#hdrNavigationLayer li").hover(function() {
                        if (menuTimer != "undefined")
                        { clearTimeout(menuTimer); }

                        $("#hdrNavigationLayer li").removeClass("navHighlight2");
                        $(this).addClass("navHighlight2");
                        navItemSecondaryIndex = $("#hdrNavigationLayer li").index(this);
                        if ($("ul", this).html() != null) {

                            // third tier positioning and creation
                            var difference = lib.utils.getPosition("#hdrNavigationLayer")[0][1] - lib.utils.getPosition("#hdrNavigationLayer ul")[0][1];
                            var liTier2PositionX = lib.utils.getPosition(this)[0][0] + ($(this).width()) + 31; // the hardcoded number is the padding on the lists in px
                            var liTier2PositionY = lib.utils.getPosition(this)[0][1] + difference;
                            var ulThirdTierHTML = "<ul class='tierthree'>" + $("ul", this).html() + "</ul>";

                            lib.layer.create("#tierThreeLayer", {
                                defaultContent: ulThirdTierHTML,
                                xPos: liTier2PositionX,
                                yPos: liTier2PositionY
                            });

                            //handlers for third tier
                            $("#tierThreeLayer").hover(
                                function() { clearTimeout(menuTimer); },
                                function() {
                                    menuTimer = setTimeout(function() {
                                        clearTimeout(menuTimer);
                                        lib.layer.remove("#hdrNavigationLayer");
                                        lib.layer.remove("#tierThreeLayer");
                                    }, 500);
                                }
                            );

                            $("#tierThreeLayer li").each(function(i, item) {
                                // remove top border for first nav item
                                if (navItemSecondaryIndex == 0 && i == 0) { $(item).addClass("removeBorder"); }
                                $(this).hover(function() {
                                    $("#tierThreeLayer li").removeClass("navHighlight3");
                                    $(this).addClass("navHighlight3");
                                }, function() {
                                    $("#tierThreeLayer li").removeClass("navHighlight3");
                                });
                            });
                        }
                        else {
                            lib.layer.remove("#tierThreeLayer");
                        }

                    }, function() {
                        clearTimeout(menuTimer);
                        menuTimer = setTimeout(function() {
                            $("#navBar li").removeClass("navHighlight1");
                            $("#navBar li").removeClass("navHighlight2");
                            lib.layer.remove("#tierThreeLayer");
                            lib.layer.remove("#hdrNavigationLayer");
                            $("#navBar li").removeClass("navHighlight3");
                        }, 500);
                    });

                }, function() {
                    clearTimeout(menuTimer);
                    menuTimer = setTimeout(function() {
                        $("#siteHdr #nav > li").removeClass("navHighlight1");
                        $("#siteHdr #nav > li").removeClass("navHighlight2");
                        lib.layer.remove("#hdrNavigationLayer");
                        //lib.layer.remove("#tierThreeLayer");
                    }, 500);
                });
            });
        },

        inPagePanelDisplay: function(selector) {
            // be able to call function without parameter
            if (selector === undefined) { selector = false; }
            else {
                $(selector).show();
                $(selector + " .js-layerClose").click(function(e) {
                    e.preventDefault();
                    overlay.removeOverlay();
                    $(selector).hide();
                    $(selector).removeClass("lib__keepcentered");

                    // remove iframe for this selector
                    lib.layer.ie6Fix(selector, "r");
                });
                var overlay = new lib.obj.pageOverlay({ selector: "#pageOverlay" });
                $("#pageOverlay").click(function() {
                    overlay.removeOverlay();
                    $(selector).hide();
                });

                lib.layer.center(selector);
                $(selector).addClass("lib__keepcentered");

            }
            // function adds handle to link for setting 
            // appropriate layers on page visible
            $(".js-inPagePanelDisplay").click(function(e) {
                var selector;
                // dont fire href
                e.preventDefault();

                // grab href which is also selector for layer and display				

                var selectorHref = $(this).attr("href");
                // if a get needs to be made to load another document into layer
                // it can be specified in href of link which validates the condition below
                // example: <a href="../member/anotherDoc.aspx#yourLayer" ...>				
                if (selectorHref.split("#")[0] != "") {
                    selector = selectorHref.split("#")[1];
                    $("#" + selector).load(selectorHref.split("#")[0], function() {
                        // move layer header who's layout is dependent on PopUpPage.Master.cs but is causing rendering issues
                        /* because layers use same control as popups page header is always present, 
                        and in wrong place for layers, and doesnt allow for clean placement of close btn, 
                        this is meant to remedy that */
                        var lHeader = $("#" + selector + " .layerHeader").get();
                        $(lHeader).remove();
                        $("#" + selector + " .layerContent").prepend(lHeader);

                        // set on click to close
                        $("#" + selector + " .js-layerClose").click(function(e) {
                            e.preventDefault(); overlay.removeOverlay();
                            $("#" + selector).hide();

                            // remove centering
                            $(selector).removeClass("lib__keepcentered");

                            // remove iframe for this selector
                            lib.layer.ie6Fix(selector, "r");
                        });
                    });

                    $("#" + selector).show();
                    var overlay = new lib.obj.pageOverlay({ selector: "#pageOverlay" });
                    $("#pageOverlay").click(function() {
                        overlay.removeOverlay();
                        $("#" + selector).hide();

                    });

                    //center layer
                    lib.layer.center("#" + selector);
                    $("#" + selector).addClass("lib__keepcentered");
                }
                else { // specify selector as value of href for example <a href="#selectorForLayerToShow" ...>                    
                    selector = $(this).attr("href");

                    // move layer header who's layout is dependent on PopUpPage.Master.cs but is causing rendering issues
                    /* because layers use same control as popups page header is always present, 
                    and in wrong place for layers, and doesnt allow for clean placement of close btn, 
                    this is meant to remedy that */
                    var lHeader = $("#" + selector + " .layerHeader").get();
                    $(lHeader).remove();
                    $("#" + selector + " .layerContent").prepend(lHeader);

                    $(selector).show();
                    $(selector + " .js-layerClose").click(function(e) {
                        e.preventDefault();
                        $(selector).hide();
                        
                        
                        if ($(id("personalizedRibbonPanel")).attr("id") != undefined) {                            
                            return false;
                        }
                        else {
                            overlay.removeOverlay();
                            // remove centering
                            $(selector).removeClass("lib__keepcentered");

                            // remove iframe for this selector
                            lib.layer.ie6Fix(selector, "r");
                        }
                    });
                    if ($(id("personalizedRibbonPanel")).attr("id") != undefined) {                        
                        return false;
                    }
                    else {
                        var overlay = new lib.obj.pageOverlay({ selector: "#pageOverlay" });
                        $("#pageOverlay").click(function() {
                            overlay.removeOverlay();
                            $(selector).hide();
                        });
                        lib.layer.center(selector);
                        $(selector).addClass("lib__keepcentered");
                    }
                }


            });
        },
        inPagePanelPersist: function(selector) {
            // be able to call function without parameter 
            if (selector === undefined) { selector = false; }
            $("input.persist").each(function() {
                if (($(this).val() == "true")) {

                    if ($(this).siblings("input:hidden").hasClass("persistLayerValue")) { // call function without parameter                       

                        var chosenSelector = $(this).next("input.persistLayerValue").val();
                        //if(selectorNotPassedIn == true && chosenSelector == null) { alert("you must specify a selector as a parameter or via a hidden field"); }		
                        var overlay = new lib.obj.pageOverlay({ selector: "#pageOverlay" });

                        $(chosenSelector).show();

                        // if content is being loaded externally, then reload it
                        if ($(this).siblings("input:hidden").hasClass("persistLayerContentReload")) {
                            $(chosenSelector).load($(this).siblings("input.persistLayerContentReload").val(), function() {

                                // move layer header who's layout is dependent on PopUpPage.Master.cs but is causing rendering issues
                                /* because layers use same control as popups page header is always present, 
                                and in wrong place for layers, and doesnt allow for clean placement of close btn, 
                                this is meant to remedy that */
                                var lHeader = $(chosenSelector + " .layerHeader").get();
                                $(lHeader).remove();
                                $(".layerContent").prepend(lHeader);
                            });

                        }
                        // set on click to close
                        $(chosenSelector + " .js-layerClose").click(function(e) {
                            e.preventDefault();
                            $(chosenSelector).hide();
                            overlay.removeOverlay();

                            // stop centering
                            $(chosenSelector).removeClass("lib__keepcentered");

                            // remove iframe for this selector
                            lib.layer.ie6Fix(chosenSelector, "r");
                        });
                        lib.layer.center(chosenSelector);
                        $(chosenSelector).addClass("lib__keepcentered");

                    }
                    else { // call function by passing in selector
                        var overlay = new lib.obj.pageOverlay({ selector: "#pageOverlay" });

                        $(selector).show();
                        $(selector + " .js-layerClose").click(function(e) {
                            e.preventDefault();
                            $(selector).hide();
                            $("#pageOverlay").removeOverlay();

                            // stop centering
                            $(selector).removeClass("lib__keepcentered");

                            // remove iframe for this selector
                            lib.layer.ie6Fix(selector, "r");
                        });
                        lib.layer.center(selector);
                        $(selector).addClass("lib__keepcentered");
                    }
                }
            });
        },
        inPagePanelDismiss: function() {
            if (($("input.dismiss").get() != undefined)) {
                var selector = $("input.dismiss").val();
                $("#pageOverlay").remove();
                $(selector).hide();
            }
        },
        setUpPanelCalls: function() {
            $(".js-openLayer").click(function(e) {
                e.preventDefault();

                var layerUrl = (this.href == "undefined") ? "layer_template.html" : this.href;
                var layerSize = (this.name == "undefined") ? "defaultSize" : this.name;
                var layerClass = (this.className.split(" ")[1] == "undefined" ? "defaultClass" : this.className.split(" ")[1] + "__commonPageLayer")
                var layerId = (this.id == "undefined") ? "defaultId" : this.id + "Layer";
                var selector = "#" + layerId;

                lib.layer.create(selector, {
                    keepCentered: true,
                    url: layerUrl,
                    callback: function() {

                        //$(selector).addClass(layerSize);
                        $(selector).addClass(layerClass);

                        // move layer header who's layout is dependent on PopUpPage.Master.cs but is causing rendering issues
                        /* because layers use same control as popups page header is always present, 
                        and in wrong place for layers, and doesnt allow for clean placement of close btn, 
                        this is meant to remedy that */
                        var lHeader = $(selector + " .layerHeader").get();
                        $(lHeader).remove();
                        $(selector + " .layerContent").prepend(lHeader);

                        $(".js-layerClose").click(function(e) {
                            e.preventDefault();
                            lib.layer.remove(selector); // remove iframe for this selector
                            lib.layer.ie6Fix(selector, "r");
                        });
                    }
                });

            }); // end layer handler


            $(".js-openLayerOverlay").click(function(e) {
                e.preventDefault();
                // Get URL and id from anchor
                var layerUrl = (this.href == "undefined") ? "layer_template.html" : this.href;
                var layerSize = (this.name == "undefined") ? "defaultSize" : this.name;
                var layerClass = (this.className.split(" ")[1] == "undefined" ? "defaultClass" : this.className.split(" ")[1] + "__commonPageLayer")
                var layerId = (this.id == "undefined") ? "defaultId" : this.id + "Layer";
                var selector = "#" + layerId;
                lib.layer.create(selector, {
                    keepCentered: true,
                    url: layerUrl,
                    callback: function() {

                        //$(selector).addClass(layerSize);
                        $(selector).addClass(layerClass);

                        // move layer header who's layout is dependent on PopUpPage.Master.cs but is causing rendering issues
                        /* because layers use same control as popups page header is always present, 
                        and in wrong place for layers, and doesnt allow for clean placement of close btn, 
                        this is meant to remedy that */
                        var lHeader = $(selector + " .layerHeader").get();
                        $(lHeader).remove();
                        $(selector + " .layerContent").prepend(lHeader);

                        $(".js-layerClose").click(function(e) {

                            e.preventDefault();
                            lib.layer.remove(selector);
                            overlay.removeOverlay();

                            // stop centering
                            $(selector).removeClass("lib__keepcentered");

                            // remove iframe for this selector
                            lib.layer.ie6Fix(selector, "r");
                        });

                        // handler to open new overlay content from existing overlay
                        $(".js-reloadLayerOverlay").click(function(e) {
                            e.preventDefault();
                            lib.layer.remove(selector);

                            // Get URL and id from anchor
                            var reloadLayerUrl = (this.href == "undefined") ? "layer_template.html" : this.href;
                            var reloadLayerClass = (this.className.split(" ")[1] == "undefined" ? "defaultClass" : this.className.split(" ")[1] + "__commonPageLayer")
                            var reloadLayerId = (this.id == "undefined") ? "defaultId" : this.id + "Layer";
                            var reloadSelector = "#" + reloadLayerId;

                            lib.layer.create(reloadSelector, {
                                keepCentered: true,
                                callback: function() {
                                    $(reloadSelector).addClass(reloadLayerClass);

                                    // move layer header who's layout is dependent on PopUpPage.Master.cs but is causing rendering issues
                                    /* because layers use same control as popups page header is always present, 
                                    and in wrong place for layers, and doesnt allow for clean placement of close btn, 
                                    this is meant to remedy that */
                                    var lHeader = $(reloadSelector + " .layerHeader").get();
                                    $(lHeader).remove();
                                    $(reloadSelector + " .layerContent").prepend(lHeader);

                                    $(".js-layerClose").click(function(e) {
                                        e.preventDefault();
                                        lib.layer.remove(reloadSelector);
                                        overlay.removeOverlay();

                                        // stop centering
                                        $(selector).removeClass("lib__keepcentered");

                                        // remove iframe for this selector
                                        lib.layer.ie6Fix(reloadSelector, "r");
                                    });

                                },
                                url: reloadLayerUrl
                            });

                        }); // end layer & overlay handler


                    }

                });

                var overlay = new lib.obj.pageOverlay({ selector: "#pageOverlay" });

                //$("#pageOverlay").addClass("ie6png");
                $("#pageOverlay").click(function() {
                    overlay.removeOverlay();
                    lib.layer.remove(selector);
                });

            }); // end layer & overlay handler

            // handler to open new overlay content from existing overlay
            $(".js-reloadLayerOverlay").click(function(e) {
                e.preventDefault();
                // Get URL and id from anchor
                var layerUrl = (this.href == "undefined") ? "layer_template.html" : this.href;
                var layerClass = (this.className.split(" ")[1] == "undefined" ? "defaultClass" : this.className.split(" ")[1] + "__commonPageLayer")
                var layerId = (this.id == "undefined") ? "defaultId" : this.id + "Layer";
                var selector = "#" + layerId;

                lib.layer.create(selector, {
                    keepCentered: true,
                    callback: function() {
                        $(selector).addClass(layerClass);

                        // move layer header who's layout is dependent on PopUpPage.Master.cs but is causing rendering issues
                        /* because layers use same control as popups page header is always present, 
                        and in wrong place for layers, and doesnt allow for clean placement of close btn, 
                        this is meant to remedy that */
                        var lHeader = $(selector + " .layerHeader").get();
                        $(lHeader).remove();
                        $(selector + " .layerContent").prepend(lHeader);

                        $(".js-layerClose").click(function(e) { e.preventDefault(); lib.layer.remove(selector); overlay.removeOverlay(); });

                    },
                    url: layerUrl
                });

            }); // end layer & overlay handler


            $(".js-openInNewWindow").click(function(e) {
                e.preventDefault();
                // Get the URL and the ID from the <a> tag
                var linkLayerURL = $(this).attr("href");
                var windowParameters = ($(this).attr("name") == "") ? "scrollbars,width=600,height=500" : $(this).attr("name");
                window.open(linkLayerURL, "popup", windowParameters);

            }); // end pop up handler

            $(".popupWindowContainer .js-layerClose").click(function(e) { e.preventDefault(); window.close(); }); // close handler for popup
        },
        preUpdateAddressJson: function() {
            $(".multiShip_UpdateThisAddressId").click(function(e) {
                // woah there overzealous href dont execute Json just yet
                e.preventDefault();
                var overlay = new lib.obj.pageOverlay({ selector: "#pageOverlay" });

                /*$("#pageOverlay").click(function() {
                overlay.removeOverlay();					
                $("#divAddUpdatePanel").hide();
                });
                */

                // make layer visible first
                $("#pageOverlay").click(function() {
                    $(this).removeOverlay();
                    $(selector).hide();
                });
                $("#divAddUpdatePanel").show();
                lib.layer.center("#divAddUpdatePanel");
                $("#divAddUpdatePanel").addClass("lib__keepcentered");
                $(".js-layerClose").click(function(e) { e.preventDefault(); $("#divAddUpdatePanel").hide(); overlay.removeOverlay(); });


                // ok lets figure out where you want to go                                
                var aid = $(this).parent().find(".ddlShippingAddressesClassId").val();
                var url = $(this).attr("href") + "&aid=" + aid;

                // $(".hidEditAddressId").val("0");
                //As this Value should Update to all drop down so clear all the hidden drop down ID
                $(".hidDropdownId").val("");

                try {
                    $.ajax({
                        type: "GET",
                        url: url,
                        timeout: 30000,
                        cache: false,
                        data: "",
                        success: function(data) {
                            var address = eval('(' + data + ')');

                            if (address != null) {
                                $(".hidEditAddressId").val(address.addressId);

                                $(".adFirstName").val(address.firstName);
                                $(".adLastName").val(address.lastName);
                                $(".adCompanyName").val(address.company);
                                $(".adAddress1").val(address.address1);
                                $(".adAddress2").val(address.address2);
                                $(".adCity").val(address.city);

                                $(".ddlStatesId").val(address.state);

                                $(".abAPOAddress > input").removeAttr("checked");
                                if (address.state == "AE" || address.state == "AP" || address.state == "AA")
                                    $(".abAPOAddress > input").attr("checked", "true");

                                $(".adZipCode").val(address.zip);
                                $(".adPhoneNumber").val(address.dayPhone);

                            }
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                            alert("Failed");
                        }
                    });
                }
                catch (e) {
                    alert(e);
                }
                finally {

                }

                return false;
            });


        },
        setUpIntFooterTargets: function() {
            $("#siteFooter select").change(function() {
                switch (this.selectedIndex) {
                    case 1:
                        location.href = "http://www.godiva.be"; // Europe
                        break;
                    case 2:
                        location.href = "http://www.godiva.co.jp"; // Japan
                        break;
                    case 3:
                        location.href = "http://www.godiva.hk"; // Hong Kong
                        break;
                    default:
                        return;
                }
            });
        },
        setUpProductTabs: function() {
            tabSet = new lib.obj.contentCollection({
                selectorContent: "#productTabs .tabContent .tab",
                selectorActivator: "#productTabs .tabHeader a",
                defaultIndex: 0
            });


            $("#productTabs .tabHeader a").click(function(e) {
                // remove previous tab and trigger display of images on left
                $("#productTabs .tabHeader li").each(function() {
                    var currentClass = $(this).attr("class");
                    var currentClassStripped = currentClass.split(" ")[0];
                    if (currentClass.indexOf("_selected") != -1) {
                        $(this).removeClass(currentClassStripped + "_selected");
                    }
                })

                var itemClass = $(this).parent().attr("class");
                var itemClassStripped = itemClass.split(" ")[0];
                var itemClassSelected = itemClassStripped + "_selected";
                $(this).parent().addClass(itemClassSelected);


                $(".productImg").hide();
                if (itemClassSelected == "tabdescription_selected") {
                    $(".default").show();
                }
                if (itemClassSelected == "tabpackaging_selected") {
                    $(".packaging").show();
                }
                if (itemClassSelected == "tabWhatsInside_selected") {
                    $(".inside").show();
                }
                if (itemClassSelected == "tabShipping_selected") {
                    $(".default").show();
                }

            });
        },
        setUpSideBarNav: function() {
            // only show top cats, hide all nested UL elements
            $("#leftNav ul li ul").hide();
            $("#leftNav ul li a.selected ~ ul").show();
            $("#leftNav li a").each(function() {
                if ($(this).prev().hasClass("handle")) { $(this).css({ padding: "0" }); }
            });

            $("#leftNav ul .js-expandMenu").each(function() {
                $(this).click(function(e) {
                    e.preventDefault();
                    var currentHandle = this;
                    if ($("~ ul", this).is(":visible")) {
                        // hide all siblings that are UL elements
                        $("~ ul", this).hide();
                        $("~ ul > ul", this).hide();
                        $("#leftNav ul li a.handleExpand").each(function() {
                            $(currentHandle).removeClass("handleExpand");
                            $(currentHandle).addClass("handle");
                        });
                    }
                    else {
                        // show all siblings that are UL elements
                        $("~ ul", this).show();
                        $("~ ul > ul", this).show();
                        $("#leftNav ul li a.handle").each(function() {
                            $(currentHandle).addClass("handleExpand");
                            $(currentHandle).removeClass("handle");
                        });
                    }
                });
            });

        },
        launchPostEmailSignUp: function() {

            $(".js-formLayer").hover(function(e) {
                e.preventDefault();

                /*** EMAIL & QUICKSHOP LAYER ***/
                //$(this).addClass("selected");
                $("#catalogEmail").addClass("selected");
                $("#quickShopEmailForm").show();

                //get position for layer
                liPositionX = lib.utils.getPosition(this)[0][0] - 94;
                liPositionY = lib.utils.getPosition(this)[0][1] - 48;

                //position layer
                $("#quickShopEmailForm").css({ top: liPositionY, left: liPositionX });

                //add handler for clearing text fields
                site.func.clearTextFields(".submit #inputSignUpHeader", "#inputSignUpHeader");
                $(".js-signUpClose").click(function(event) {
                    event.preventDefault();
                    $(this).parent().parent().parent().hide();
                    $("#catalogEmail").removeClass("selected");
                    return false;
                });
                // Close on Click Outside
                //$(document).bind('mousedown', { nodeID: "#quickShopEmailForm" }, closeLayerOnClickOutside);
            });
            
            $("#quickShopEmailForm").hover(function(){
                $("#quickShopEmailForm").show();
            }, function(){
                $("#quickShopEmailForm").hide();
                $("#catalogEmail").removeClass("selected");
            })

            //handler which controls post for footer and header
            $(".js-inputSubmit").click(function(e) {
                e.preventDefault();
                var parentForm = this.parentNode;

                while ($(parentForm).hasClass("form") == false) { parentForm = parentForm.parentNode; }
                var formBtnId = $("#" + parentForm.id + " .text").attr("id");
                // start functions
                handleSignUp();

                //Footer Control Code - START
                function handleSignUp() {
                    //var supForm = document.getElementById("footerSubcribe");
                    var email = parentForm[formBtnId].value;
                    var signUpMsg = "Sign up for Godiva Emails &amp; News:"; //	 Declared in the Navigation control

                    // only submit if the current email passes basic check
                    if (cleanString(email) != "" && email != signUpMsg) { parentForm.submit(); }
                    else { return false; }
                    return true;
                }

                function clearEmail() {
                    //var supForm = document.getElementById("footerSubcribe");                    
                    var emailField = parentForm[formBtnId];
                    var signUpMsg = "Sign up for Godiva Emails &amp; News:";
                    if (emailField.value == signUpMsg)
                        emailField.value = "";
                }

                function resetEmail() {
                    //var supForm = document.getElementById("footerSubcribe");
                    var emailField = parentForm[formBtnId];
                    var cleanEmail = cleanString(emailField.value);

                    // alert("Input: " + emailField.value + "\nClean: " + cleanEmail)

                    var signUpMsg = "Sign up for Godiva Emails &amp; News:";

                    if (cleanEmail == "")
                        emailField.value = signUpMsg;
                }

                function cleanString(input) {
                    var output = "";
                    if (input.length > 0) {
                        for (var i = 0; i < input.length; i++)
                            if (input.charAt(i) != " ")
                            output += input.charAt(i);
                    }
                    return output;
                }
                function isValidEmail(str) {
                    var at = "@"
                    var dot = "."
                    var lat = str.indexOf(at)
                    var lstr = str.length
                    var ldot = str.indexOf(dot)

                    if (str.indexOf(at) == -1) {
                        return false
                    }
                    if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
                        return false
                    }
                    if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
                        return false
                    }
                    if (str.indexOf(at, (lat + 1)) != -1) {
                        return false
                    }
                    if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
                        return false
                    }
                    if (str.indexOf(dot, (lat + 2)) == -1) {
                        return false
                    }
                    if (str.indexOf(" ") != -1) {
                        return false
                    }
                    return true
                }
                //Footer Control Code - END
            });
        },
        switchShippingInfo: function() {
            $(".js-showShipMore").click(function(e) {
                $(".labelMore").hide();
                var parentEntry = this.parentNode;
                while ($(parentEntry).hasClass("entry") == false) { parentEntry = parentEntry.parentNode; }
                var thisShippingInfoObj = $(parentEntry).children(".labelMore");
                //alert(thisShippingInfoObj);
                $(thisShippingInfoObj).show();
            });
        },
        postSearch: function() {
            $(".search .inputBtn").click(function(e) {
                var searchFormElement = $("#searchForm").get(0);
                searchFormElement.submit();
            });
            $("#inputGlobalSearch").click(function(e) {
                if (!$(this).hasClass("activeSearch")) {
                    $(this).addClass("activeSearch")
                }
            });
        },
        clearTextFields: function(selectorHandle, textFieldSelector) {
            $(selectorHandle).click(function() {
                //$(textFieldSelector).addClass("defaultCleared");
                $(textFieldSelector).val("");
                $(textFieldSelector).css({ color: "#000" });
            });
        },
        fillAddressBookValues: function() {
            $(".js-abSendToForm").click(function() {

                $(this).parent().find("p").each(function() {

                    var currentAddLabel = $(this).attr("class");
                    var currentAddText = $(this).text();
					var currentAddTextStripped = currentAddText.replace(/^\s*|\s*$/g,'');

                    if (currentAddLabel == "ddlStatesId") {
                        $("select.ddlStatesId").val(""); // set the selected to nothing

                        $("select.ddlStatesId option").each(function() {
                            if ($(this).val() == currentAddText) {
                                $("select.ddlStatesId").val($(this).val());
                                return;
                            }
                        });
                    }
                    else
                        $("input." + currentAddLabel).val(currentAddTextStripped);
                });
            });
        },
        toggleStateVsProvinceInAddressControl: function() {

            setDisplayForInternational();

            $(".ddlCountriesId").change(function() {
                setDisplayForInternational();
            });

            function setDisplayForInternational() {
                if ($(".ddlCountriesId").val() == null || $(".ddlCountriesId").val() == undefined || $(".ddlCountriesId").val() == "US") {
                    $(".ddlStatesId").show();
                    $(".txtProvinceId").hide();
                    if ($(".txtProvinceId").val("")) {
                        $(".txtProvinceId").val("Enter a state");
                    }
                }
                else {
                    $(".ddlStatesId").hide();
                    $(".txtProvinceId").show();
                    if ($(".txtProvinceId").val("Enter a state")) {
                        $(".txtProvinceId").val("");
                    }
                    $(".ddlStatesId option").each(function() {
                        $(this).removeAttr("selected");
                    })

                }
            }
        },
        printing: function() {
            $("#printLink").click(function(e) {
                e.preventDefault();
                var printUrl = location.href;
                printUrl += (location.href.match(/\?/g)) ? "&media=print" : "?media=print";

                window.open(printUrl, "PrintGodiva");
            });

            if (location.href.match(/media=print/g)) {
                window.print();
                $("a").css({ "cursor": "default" });
                $("input").click(function(e) {
                    e.preventDefault();
                });
                $("a").click(function(e) {
                    e.preventDefault();
                });
                $(".finalShipping").each(function() {
                    $(this).before("Final shipping");
                    $(this).remove();
                })
            }

        },
        personalizeRibbon: function() {
            $(".ribbonMessage_chars").click(function(e) {
                if ($(this).val() == "enter text") {
                    $(this).val("");
                    $(this).removeClass("defaultInputText");
                }
            });
            $(".ribbonMessage_chars").bind("keyup", function(e) {
                changePreviewState("enable");
                return (countPersonalRibbonMessage($(this),$(this).val(), e.which, $(id("txtCustomMessage")).attr("maxlength")));
            });
            $(".ribbonMessage_chars").bind("keypress", function(e) {
                var key = e.which;
                // allow delete and backspace always
                if (key == 8 || key == 0) return true;

                var previousRemaining = $("#ribMessage_remaining").text();
                if (previousRemaining <= 0) {
                    return false;
                }
                // if letters typed are valid and letters typed are @ max return
                if (String.fromCharCode(key).match(/[A-Za-z]/g) != null && previousRemaining == 0) {
                    return false;
                }
            });

            $(".ribbonFontsSelect").click(function(e) {
                changePreviewState("enable");
            });

            $(".ribbonQuantity").change(function() {
                updatedPerRibbonTotal();
            })
            // Limit entry to only numbers
            $(".onlyNumbers").bind("keypress", function(e) {
                var key = e.which;
                // $("#debug").text(key);
                if (key == 8) return true; // Backspace
                if (key == 0) return true; // Backspace
                if (key == 46) return true; // Backspace
                if (key < 48 || key > 57) return false;
                return true;
            });
            $(".swatchSelector li").click(function() {
                $(this).parent().children().removeClass("current");
                var currentName = $(this).parent().parent().children("input").attr("value");
                var selectName = $(this).children("img").attr("alt");
                var displayText = $(this).children("img").attr("displaytext");

                if (currentName == selectName) {
                    $(this).parent().parent().children("input").attr("value", "");
                    if ($(this).parent().parent().children("input").attr("id") == $(id("txtRibbonColor")).attr("id")) {
                        $(id("ribbonColorText")).text("");
                    }
                    else if ($(this).parent().parent().children("input").attr("id") == $(id("txtFontColor")).attr("id")) {
                        $(id("fontColorText")).text("");
                    }
                } else {
                    $(this).addClass("current");
                    $(this).parent().parent().children("input").attr("value", selectName);

                    //GS: hide validation message once the item is selected
                    if ($(this).parent().parent().children("input").attr("id") == $(id("txtRibbonColor")).attr("id")) {
                        $(id("vldRibbonColor")).hide();
                        $(id("vldRibbonColorPreview")).hide();
                        $(id("ribbonColorText")).text(displayText);
                    }
                    else if ($(this).parent().parent().children("input").attr("id") == $(id("txtFontColor")).attr("id")) {
                        $(id("vldFontColor")).hide();
                        $(id("vldFontColorPreview")).hide();
                        $(id("fontColorText")).text(displayText);
                    }
                }
                updatedPerRibbonTotal();
                changePreviewState("enable");
            });
            $("#prFaqToggle").click(function(e) {
                e.preventDefault();
                if ($("#perRibbonFAQBody").is(':hidden')) {
                    $("#perRibbonFAQs").attr("class", "faqVisible");
                    $("#perRibbonFAQBody").slideDown(500);
                } else {
                    $("#perRibbonFAQs").attr("class", "faqHidden");
                    $("#perRibbonFAQBody").slideUp(300);
                }
            });

            $(id("showPersonlizedRibbons")).click(function(e) {

                e.preventDefault();

                //site.func.inPagePanelDisplay(".personalizedRibbonPanel");
                var overlay = new lib.obj.pageOverlay({ selector: "#pageOverlay" });

                // make layer visible first
                $("#pageOverlay").click(function() {
                    $("#pageOverlay").remove();
                    $(id("personalizedRibbonPanel")).hide();
                });
                $(id("personalizedRibbonPanel")).css("top", document.documentElement.scrollTop + 100);
                $(id("personalizedRibbonPanel")).show();

                // resolve stack order issues in IE6
                $(id("aspnetForm")).append(id("personalizedRibbonPanel")); //This is creating problem by preventing Add To Shopping Bag button click

                $(".js-layerClose").click(function(e) { e.preventDefault(); $(id("personalizedRibbonPanel")).hide(); overlay.removeOverlay(); });

            });

            //print customized item
            $("#printRibbon").click(function(e) {
                e.preventDefault();
                var url = $("#previewImage").attr("src");

                if (url == "writeTextOnRibbon.aspx")
                    alert('No customized item available to preview.');
                else
                    window.open(url, "printPersonalizedRibbon");
            });
            /* disabling zoom
            //these next few lines are to replace existing zoom, client wanted something with more flare
            $("#previewImage").bind("mouseover", function() {

                var url = $(".js-ribbonZoom").attr("href");
            if (url == "writeTextOnRibbon.aspx") {
            //$(".js-ribbonZoom").removeAttr("href");
            return;
            }
            else
            site.func.enableZoom();
            });

            //zoom customized item
            $("#zoomLink").click(function(e) {
            e.preventDefault();
            var url = $("#previewImage").attr("src");

                if (url == "writeTextOnRibbon.aspx")
            alert('No customized item available to preview.');
            else
            window.open(url, "zoomPersonalizedRibbon");
            });
            */
            //GS: hide validation message once the checked is selected
            $(id("chkProof")).click(function(e) {
                $(id("proofNotification")).hide();
            });

            /* GS: shouldn't we call it on pressing Cancel link? */
            $(".fontColor").val("");
            $(".ribbonColor").val("");
            $(".ribbonCharm").val("");
            $(".ribbonQuantity").val("");
            $(".ribbonMessage_chars").val("enter text");
            $(".ribbonMessage_chars").addClass("defaultInputText");
            $(id("chkProof")).removeAttr('checked');
            $("#" + id("ddlFonts").attr("id") + " option:first-child").attr("selected", "selected");
        },
        populateMultiShipmentAddressControl: function() {

            $(".ddlShippingAddressesClassId").each(function() {
                if ($(this).val() == "" || $(this).val() == "0") {
                    $(this).parent().find(".multiShip_UpdateThisAddressId").hide();
                }
            });

            $(".ddlShippingAddressesClassId").change(function() {
                if ($(this).val() != "" && $(this).val() != "0")
                    $(this).parent().find(".multiShip_UpdateThisAddressId").show();
                else
                    $(this).parent().find(".multiShip_UpdateThisAddressId").hide();
            });
            $(".multiShip_ShipToNewAddress").click(function() {
                
                
                /*if ($(this).val() == "" || $(this).val() == "0")
                $(this).parent().find(".multiShip_UpdateThisAddressId").hide();
                */
                // clear input for address
                $(".adFirstName").val("");
                $(".adLastName").val("");
                $(".adCompanyName").val("");
                $(".adAddress1").val("");
                $(".adAddress2").val("");
                $(".adCity").val("");
                $(".ddlStatesId").val("");
                $(".adZipCode").val("");
                $(".adPhoneNumber").val("");
                $(".abAPOAddress").removeAttr("checked");

                $(".hidEditAddressId").val("0");
                //$(".hidEditAddressId").val($(this).parent().find(".ddlShippingAddressesClassId option").length);
                
                //Assign the dropdwon client ID, so that server can assign the new Value to drop down
                $(".hidDropdownId").val($(this).parent().find(".ddlShippingAddressesClassId").attr("id"));

                return false;
            });
        },
        enableCalendar: function() {
            if ($(".js-datePicker").get() != "") {
                var calendarSetUp = function(thisInput) {
                    // add class to formEntry of current table to target correct alternate value in hidden field
                    $(".formEntry").removeClass("___currentEntryForCalendar");
                    var parentFormEntry = thisInput.parentNode;
                    while ($(parentFormEntry).hasClass("formEntry") == false) { parentFormEntry = parentFormEntry.parentNode; }
                    $(parentFormEntry).addClass("___currentEntryForCalendar");

                    //selector
                    var selector = "#calendarLayer";

                    // onclick show calendar layer
                    $(selector).show();

                    // set on click to close
                    $(selector + " .js-layerClose").click(function(e) { e.preventDefault(); overlay.removeOverlay(); $(selector).removeClass("lib__keepcentered"); $(selector).hide(); lib.layer.ie6Fix(selector, "r"); });
                    var overlay = new lib.obj.pageOverlay({ selector: "#pageOverlay" });
                    $("#pageOverlay").click(function() {
                        overlay.removeOverlay();
                        $(selector).hide();
                    });

                    //center layer
                    lib.layer.center(selector);
                    $(selector).addClass("lib__keepcentered");
                    //alert("before date object " + $(".___currentEntryForCalendar .datePickerValue").val());
                    // store current value from hidden field
                    // it starts at null, but then is updated by the calendar value itself
                    // when in edit mode, the value is provided by back end via the hidden field
                    //alert($(".___currentEntryForCalendar .datePickerValue").val()=="null");
                    if ($(".___currentEntryForCalendar .datePickerValue").val() == "null") {

                        var dateNonFormat = new Date();
                        var month = dateNonFormat.getMonth() + 1;
                        var day = dateNonFormat.getDate();
                        var year = dateNonFormat.getFullYear();
                        // month/day/year						
                        var date = month + "/" + day + "/" + year;
                    }
                    else {
                        var date = $(".___currentEntryForCalendar .datePickerValue").val();
                    }

                    //var date = "09/15/2009";

                    //var date = $(".___currentEntryForCalendar .datePickerValue").val();
                    var arrDate = date.split("/");
                    var m = arrDate[0];
                    var d = arrDate[1];
                    var y = arrDate[2];

                    //alert("year, month, date:"+y+m+d);                    

                    // add calendar obj, giving it an onSelect event and a default date
                    // the default date is whatever the hidden value in input field
                    // the min date is how far back a user can select from within calendar in days
                    $("#calendarLayer .js-datePicker").datepicker(
						{
						    onSelect: function(dateText, inst) { $("#calendarLayer .textPickerValue").html(dateText); },
						    defaultDate: new Date(y, m - 1, d),
						    minDate: 1
						}
					);
                    // get alternate field, this tells the date picker to post its 
                    // current value into the hidden input field					
                    var altField = $("#calendarLayer .js-datePicker").datepicker('option', 'altField');

                    /* if the checkbox is checked apply the date from hidden field 
                    to all available pickers, note: thats date pickers not nose pickers*/
                    if ($(".useAbove input").is(':checked')) {
                        //alert("checked");
                        //set alternate field
                        $("#calendarLayer .js-datePicker").datepicker('option', 'altField', '.datePickerValue');
                        // set node with date text
                        $("#calendarLayer .js-datePicker").datepicker('setDate', new Date(y, m - 1, d));
                        $("#calendarLayer .textPickerValue").html($(".datePickerValue").val());
                    }
                    else {
                        //alert("not checked"+ y + m + d);
                        //just update this pickers object and fields
                        $("#calendarLayer .js-datePicker").datepicker('option', 'altField', '.___currentEntryForCalendar .datePickerValue');
                        // set node with date text
                        $("#calendarLayer .js-datePicker").datepicker('setDate', new Date(y, m - 1, d));
                        $("#calendarLayer .textPickerValue").html($(".___currentEntryForCalendar .datePickerValue").val());
                    }
                };

                // make calendar work for radio click
                $("table.shippingArriveAndMethod .shipByDate input:radio").bind("click", function() {
                    var thisInput = this;
                    calendarSetUp(thisInput);
                });

                // make calendar work for icon click
                $("table.shippingArriveAndMethod .js-setValuesForDateInHiddenFieldThenShowLayer").bind("click", function() {
                    var thisInput = this;
                    calendarSetUp(thisInput);

                    //if date obj is created for icon click then go right ahead and select the radio too
                    $(".___currentEntryForCalendar .shipByDate input:radio").attr("checked", "checked");

                });
            }
        },
        shippingMethodDisplayOptions: function() {
            var initial = true;
            var arriveByChecked = false;
            var shipMethChecked = false;
            var oddArriveByChecked = false;
            var oddShipMethChecked = false;
            var shippingTable;
            var initTableObj = {
                type: null,
                date: null,
                identifier: null,
                method: null
            };
            var otherTableObj = {
                type: null,
                date: null,
                identifier: null,
                method: null
            };


            //loop through each table, for each table check the values of each radio, and store in object. 
            //ex: asap, 8/16/09, 34, 6, 1, rdbMethodStandard.

            $(".shippingArriveAndMethod input:radio").bind("click", function(e) {

                // start a loop of each table
                $(".shippingArriveAndMethod").each(function(i, item) {
                    //alert($("#table_"+i));
                    var checkedValAmount = $("#table_" + i + " input:checked").length;
                    // take clicked value of THIS tables inputs, if both columns not clicked, dont compare.
                    //alert();
                    if (checkedValAmount > 1) {
                        $("#table_" + i + " input:checked").each(function(i, item) {
                            //alert("#table_" + i);
                            var parent = $(this).parents("div").attr("class");
                            var checkedVal = $(this).val();
                            //var stringCompare = document.getElementById('stringCompare');
                            $("#stringCompare").hide();
                            //alert(checkedVal);
                            // check div to see if current values match if they dont continue, otherwise meesgae user
                            if ($("#stringCompare span").text() == checkedVal) {
                                //alert("same");
                            }
                            else {
                                // store new values of table in div
                                //stringCompare.innerHTML = stringCompare.innerHTML + checkedVal;
                                //alert("i"+i);
                                if (i == 1) {
                                    var compareDiv = document.createElement("div");
                                    compareDiv.className = "stringCompare";
                                    $(compareDiv).append(".formFieldSet1Content");
                                }
                            }



                        });
                    }
                    //$("#stringCompare").html() = "<div>" + $("#stringCompare").html() + "</div>";

                });

                //site.func.collectSMGRadioValues(this, arriveByHidden, shipMethHidden);                       
            });
        },
        collectSMGRadioValues: function(input, hiddenInput1, hiddenInput2) {
            //alert(input+","+hiddenInput1+","+hiddenInput2);		
            var parentTable = input.parentNode;
            while ($(parentTable).hasClass("shippingArriveAndMethod") == false) { parentTable = parentTable.parentNode; }
            if (site.func.shippingMethodDisplayOptions.initial == true || $(parentTable).hasClass("__initialTable")) {

                // make the first table selected always the comparable table
                if (site.func.shippingMethodDisplayOptions.initial == true) { $(parentTable).addClass("__initialTable"); }
                // this is the relevant table whos selected values are being grabbed
                $(parentTable).addClass("__currentTable");

                $(".__initialTable .addGiftMessage").show();
                $(".__initialTable .addGreeting").show();
                $(hiddenInput1, ".__initialTable").each(function(i, el) {
                    //get checked type , date, identifier
                    /*initTableObj.type = $(this).attr('name') == "type" ? $(this).val() : null; 
                    initTableObj.date = $(this).attr('name') == "date" ? $(this).val() : null;
                    initTableObj.identifier = $(this).attr('name') == "identifier" ? $(this).val() : null;
                    */
                    if ($(this).attr('name') == "type") { site.func.shippingMethodDisplayOptions.initTableObj.type = $(this).val(); }
                    if ($(this).attr('name') == "date") { site.func.shippingMethodDisplayOptions.initTableObj.date = $(this).val(); }
                    if ($(this).attr('name') == "identifier") { site.func.shippingMethodDisplayOptions.initTableObj.identifier = $(this).val(); }

                    // alert our obj
                    //debug("initials ob: " + initTableObj.type, initTableObj.date, initTableObj.identifier, initTableObj.method);
                    //if(otherTableObj!=undefined){alert("otherTableMatch: " + "type=" + otherTableObj.type + "date=" + otherTableObj.date + "identifier=" + otherTableObj.identifier + initTableObj.method);}	

                });
                $(hiddenInput2, ".__initialTable").each(function(i, el) {
                    //initTableObj.method = $(this).attr('name') == "method" ? $(this).val() : null;				 
                    if ($(this).attr('name') == "method") { site.func.shippingMethodDisplayOptions.initTableObj.method = $(this).val(); }
                    //debug("initials ob: " + initTableObj.type, initTableObj.date, initTableObj.identifier, initTableObj.method);
                    // alert our obj
                    //alert("initsobjMeth: " + initTableObj.method);
                });
                site.func.shippingMethodDisplayOptions.initial = false;
            }
            else {
                // make sure current table is NOT initial table here
                // make the first table selected always the comparable table
                if ($(parentTable).hasClass("__initialTable")) { $(parentTable).removeClass("__initialTable"); }

                $(parentTable).addClass("__currentTable");
                $(hiddenInput1, ".__currentTable").each(function(i, el) {
                    //get checked type , date, identifier				     
                    /*otherTableObj.type = $(this).attr('name') == "type" ? $(this).val() : null;
                    otherTableObj.date = $(this).attr('name') == "date" ? $(this).val() : null;
                    otherTableObj.identifier = $(this).attr('name') == "identifier" ? $(this).val() : null;
                    */

                    if ($(this).attr('name') == "type") { site.func.shippingMethodDisplayOptions.otherTableObj.type = $(this).val(); }
                    if ($(this).attr('name') == "date") { site.func.shippingMethodDisplayOptions.otherTableObj.date = $(this).val(); }
                    if ($(this).attr('name') == "identifier") { site.func.shippingMethodDisplayOptions.otherTableObj.identifier = $(this).val(); }

                    //debugOther("otherTableObj: " + otherTableObj.type, otherTableObj.date, otherTableObj.identifier, otherTableObj.method);
                });
                $(hiddenInput2, ".__currentTable").each(function(i, el) {

                    if ($(this).attr('name') == "method") { site.func.shippingMethodDisplayOptions.otherTableObj.method = $(this).val(); }
                    //debugOther("otherTableObj: " + otherTableObj.type, otherTableObj.date, otherTableObj.identifier, otherTableObj.method);
                });

            }

            // parse through each ship table and check if each obj is defined, 
            // if they are compare the obj values to the initial table	
            $(".shippingArriveAndMethod").each(function() {
                // at this point either the values for the initial table have been set
                // or the values for both initial and current tables have been set

                // lets collect the checked values and their children, for each table and store them, 
                // then compare them with the "current table" while left and right are checked

                shippingTable = this;
                $("input:checked", this).each(function(i, checkedEl) {

                    if ($(checkedEl).parents(".arriveByEntry").get(0) != undefined) { site.func.shippingMethodDisplayOptions.oddArriveByChecked = true; }
                    if ($(checkedEl).parents(".shippingMethEntry").get(0) != undefined) { site.func.shippingMethodDisplayOptions.oddShipMethChecked = true; }

                    //alert(oddArriveByChecked +","+ oddShipMethChecked);								
                    if (site.func.shippingMethodDisplayOptions.oddArriveByChecked == true && site.func.shippingMethodDisplayOptions.oddShipMethChecked == true) {
                        $($(this).siblings("input:hidden")).each(function(i, hiddenEl) {
                            site.func.shippingMethodDisplayOptions.oddArriveByChecked = false;
                            site.func.shippingMethodDisplayOptions.oddShipMethChecked = false;
                            if ($(shippingTable).hasClass('__currentTable') || $(shippingTable).hasClass('__initialTable')) { return; }
                            else {

                                if ($(this).attr('name') == "type") { site.func.shippingMethodDisplayOptions.tempObj.type = $(this).val(); }
                                if ($(this).attr('name') == "date") { site.func.shippingMethodDisplayOptions.tempObj.date = $(this).val(); }
                                if ($(this).attr('name') == "identifier") { site.func.shippingMethodDisplayOptions.tempObj.identifier = $(this).val(); }
                                if ($(this).attr('name') == "method") { site.func.shippingMethodDisplayOptions.tempObj.method = $(this).val(); }

                            }
                        });
                    }
                    //alert(this);
                    //if((this)==($("input:checked",".__currentTable").siblings("input:hidden").attr("name"))) { alert("fuvery much"); }
                    //alert($("input:checked",".__currentTable").siblings("input:hidden")[i]);
                    //if((attr) ==  

                    //$($("input:checked",".__currentTable").siblings("input:hidden")).each
                    //if($(this).siblings("input:hidden").attr("name") == ($("input:checked",".__currentTable").siblings("input:hidden").attr("name"))) { alert("I could kiss u"); }							

                    if (site.func.shippingMethodDisplayOptions.otherTableObj != undefined && site.func.shippingMethodDisplayOptions.initTableObj != undefined) {

                        var oddTypeMatch = (site.func.shippingMethodDisplayOptions.tempObj.type == site.func.shippingMethodDisplayOptions.otherTableObj.type && tempObj.type != null) ? true : false;
                        var oddDateMatch = (site.func.shippingMethodDisplayOptions.tempObj.date == site.func.shippingMethodDisplayOptions.otherTableObj.date && tempObj.date != null) ? true : false;
                        var oddIdentifierMatch = (site.func.shippingMethodDisplayOptions.tempObj.identifier == site.func.shippingMethodDisplayOptions.otherTableObj.identifier && tempObj.identifier != null) ? true : false;
                        var oddMethodMatch = (site.func.shippingMethodDisplayOptions.tempObj.method == otherTableObj.method && site.func.shippingMethodDisplayOptions.tempObj.method != null) ? true : false;

                        var typeMatch = (site.func.shippingMethodDisplayOptions.initTableObj.type == site.func.shippingMethodDisplayOptions.otherTableObj.type) ? true : false;
                        var dateMatch = (site.func.shippingMethodDisplayOptions.initTableObj.date == site.func.shippingMethodDisplayOptions.otherTableObj.date) ? true : false;
                        var identifierMatch = (site.func.shippingMethodDisplayOptions.initTableObj.identifier == site.func.shippingMethodDisplayOptions.otherTableObj.identifier) ? true : false;
                        var methodMatch = (site.func.shippingMethodDisplayOptions.initTableObj.method == site.func.shippingMethodDisplayOptions.otherTableObj.method) ? true : false;
                        //alert("method" + initTableObj.method + "" + otherTableObj.method);
                        if ((typeMatch == true) && (dateMatch == true) && (identifierMatch == true) && (methodMatch == true) && (shipMethChecked == true) && (arriveByChecked == true)) {
                            $(".__currentTable .addGiftMessage").hide();
                            $(".__currentTable .addGreeting").hide();
                            $(".__currentTable .personalizedMax").show();
                            alert(site.func.shippingMethodDisplayOptions.arriveByChecked + "," + site.func.shippingMethodDisplayOptions.shipMethChecked);
                            alert("yes match: " + "typematch=" + typeMatch + "datematch=" + dateMatch + "identifymatch=" + identifierMatch + "methMatch=" + methodMatch);
                        }
                        else if ((oddTypeMatch == true) && (oddDateMatch == true) && (oddIdentifierMatch == true) && (oddMethodMatch == true) && (shipMethChecked == true) && (arriveByChecked == true)) {
                            $(".__currentTable .addGiftMessage").hide();
                            $(".__currentTable .addGreeting").hide();
                            $(".__currentTable .personalizedMax").show();
                            alert(site.func.shippingMethodDisplayOptions.oddArriveByChecked + "," + site.func.shippingMethodDisplayOptions.oddShipMethChecked);
                            alert("odd type match");
                            //debugOdd("otherTableOdd: " + tempObj.type, tempObj.date, tempObj.identifier, tempObj.method);
                        }
                        else {
                            //$(".shippingArriveAndMethod .addGiftMessage").hide();
                            //$(".shippingArriveAndMethod .addGreeting").hide();
                            $(".shippingArriveAndMethod .addGiftMessage").show();
                            $(".shippingArriveAndMethod .addGreeting").show();
                            $(".shippingArriveAndMethod .personalizedMax").hide();
                            alert(site.func.shippingMethodDisplayOptions.arriveByChecked + "," + site.func.shippingMethodDisplayOptions.shipMethChecked);
                            alert("no match: " + "typematch=" + typeMatch + "datematch=" + dateMatch + "identifymatch=" + identifierMatch + "methMatch=" + methodMatch);
                        }

                    }
                });
            });
            $(".__currentTable").removeClass("__currentTable");
        },
        detectLeavingSurvey: function() {			
			// global variable
			this.clickedUrl = null;
			
            $("#survey a").click(function(e) {
                e.preventDefault();
				
				// get current url
				this.clickedUrl = this.href;				
                //var layerUrl = popupUrl;
                //var layerClass = (this.className.split(" ")[1] == "undefined" ? "defaultClass" : this.className.split(" ")[1] + "__commonPageLayer")
                //var layerId = popupId + "Layer";
                //var selector = "#" + layerId;
                
				site.func.inPagePanelDisplay("#modal_surveyexit");
				
				// unbind events to certain links
				$("#quickShopEmailForm a").unbind('click');
				//$("#survey .closeWin").unbind('click');
				//$("#survey .complete").unbind('click');
				//$("#survey .exit").unbind('click');
				var thisUrl = this.clickedUrl;
				$(".exit").click(function(e) { 
					e.preventDefault();					
					location.href = thisUrl; 					
					//return false;
				});
				$("#survey .complete").click(function() {
					$("#modal_surveyexit").hide();
					$("#modal_surveyexit-iframe").remove();
					$("#pageOverlay").remove();
					$("#pageOverlay-iframe").remove();
				});																								                			
				
            });
        },
        enableZoom: function() {
            // add configs
            var options = {
                zoomWidth: 200,
                zoomHeight: 200,
                title: false,
                xOffset: 10,
                yOffset: 0,
                position: "right",
                hideEffect: 'fadeout',
                fadeoutSpeed: 'slow',
                lens: false
            };

            $(".js-ribbonZoom").jqzoom(options);
        },
        fixBoxedPngInIE6: function() {
            if (jQuery.browser.msie && $.browser.version == "6.0") {
                $(".boxedSectionHeader").each(function() {
                    if ($(this).parents(".shippingSection").get(0) != undefined) { return false; }
                    var headerText = $(this).children(".wrapper").children("h2").text();
                    var boxWidth = $(this).width() - 14;
                    $(this).addClass("boxedStylePrimary");
                    $(this).addClass("boxedSectionHeaderIE6");
                    $(this).children(".wrapper").children("h2").remove();
                    $(this).children(".wrapper").append("<h3>" + headerText + "</h3>");
                    $(this).children(".wrapper").addClass("boxedStylePrimaryHdr");
                    $(this).children(".wrapper").addClass("ie6png");
                    $(this).children(".wrapper").css("width", boxWidth + "px");
                    $(this).children(".wrapper").before('<div class="boxedStylePrimaryHdrLft ie6png"></div>');
                    $(this).children(".wrapper").after('<div class="boxedStylePrimaryHdrRt ie6png"></div>');
                    $(this).removeClass("boxedSectionHeader");
                });
                $(".boxedSectionBody").each(function() {
                    if ($(this).parents(".shippingSection").get(0) != undefined) { return false; }
                    $(this).addClass("ie6png");
                    var boxWidth = $(this).width();
                    $(".boxedSectionBody").css("width", boxWidth + "px"); ;
                });
            }
        },
        useAboveShippingMethod: function() {
            //Get the Base ID for  Shiiping ID
            var i = 0;
            var ctrl;

            //Get the Last Index of '_'
            i = shippingId.lastIndexOf('_');
            var prefixShipID = shippingId.substring(0, i);
            var suffixShipID = shippingId.substring(i + 1);

            i = rbArriveById.lastIndexOf('_');
            var prefixArriveBy = rbArriveById.substring(0, i);
            var suffixArriveBy = rbArriveById.substring(i + 1);

            ctrl = document.getElementById(prefixArriveBy + "_chbUseShipmentForAllOtherRecipients")
            if (ctrl == null || ctrl.checked == false)
                return;

            //Get the Select ArrivaBy date
            i = 0;
            var selectedArriveBy = -1;
            var countArriveBy = 0;
            while (true) {
                var rb = document.getElementById(rbArriveById + "_" + i.toString());
                //Exit oncel looped though all the radio buttons;
                if (rb == null)
                    break;

                if (rb.checked)
                    selectedArriveBy = i;

                countArriveBy++;
                i++;
            }


            var selectedShipping = defaultShipping;
            var countShipping = 0;

            var shipping = '';
            //Check Standard Shipping
            shipping = prefixShipID + "_rdbMethodStandard";
            ctrl = document.getElementById(shipping);
            if (ctrl != null && ctrl.checked)
                selectedShipping = "rdbMethodStandard"

            shipping = prefixShipID + "_rdbMethod2ndDay";
            ctrl = document.getElementById(shipping);
            if (ctrl != null && ctrl.checked)
                selectedShipping = "rdbMethod2ndDay"

            shipping = prefixShipID + "_rdbMethodOverNight";
            ctrl = document.getElementById(shipping);
            if (ctrl != null && ctrl.checked)
                selectedShipping = "rdbMethodOverNight"

            shipping = prefixShipID + "_rdbMethodOverNightSaturday";
            ctrl = document.getElementById(shipping);
            if (ctrl != null && ctrl.checked)
                selectedShipping = "rdbMethodOverNightSaturday"


            //alert(selectedShipping);

            //Apply Arrive By date other Items
            if (selectedArriveBy > -1) {
                //Remove Last 2 chars which are the numeric;
                prefixArriveBy = prefixArriveBy.substring(0, prefixArriveBy.length - 2);

                //Loop through all the Items
                for (i = 1; i < itemCount; i++) {
                    var mid = "0" + i.toString();
                    if (i > 9)
                        mid = i.toString();
                    mid = mid + "_";

                    ctrl = document.getElementById(prefixArriveBy + mid + suffixArriveBy + "_" + selectedArriveBy.toString());
                    if (ctrl != null)
                        ctrl.checked = true;
                }
            }

            if (selectedShipping.length > 0) {
                //Remove Last 2 chars which are the numeric;
                prefixShipID = prefixShipID.substring(0, prefixShipID.length - 2);

                //Loop through all the Items
                for (i = 1; i < itemCount; i++) {
                    var mid = "0" + i.toString();
                    if (i > 9)
                        mid = i.toString();
                    mid = mid + "_";

                    ctrl = document.getElementById(prefixShipID + mid + selectedShipping);
                    if (ctrl != null)
                        ctrl.checked = true;
                }
            }

            return;
            while (true) {
                var rb = document.getElementById(prefixShipID + i);
                //Exit oncel looped though all the radio buttons;
                if (rb == null)
                    break;

                if (rb.checked)
                    selectedArriveBy = i;

                countArriveBy++;
                i++;
            }

        },
        truncateLongHeaders: function(selector) {
            var settings = $.extend({
                length: 62,
                postfix: "..."
            }, settings);
            lib.utils.strTruncate(selector, settings);
        },
        clearGiftMessageFields: function() {
            $(".js-clearGiftFields").bind("click", function() {
                $(".layerContent input").filter(".text").val("");
                $(".characterCountBlock div").html("140 characters left	");
            });
        },
        addConfirmationMessage: function() {
            $(".js-addConfirmationMessage").bind("click", function() {
                var layerId = $(this).parents(".commonLayer").attr("id");
                var layerIdArray = layerId.split("_");

                //show confirmation layer
                $("#giftMessageNotification_" + layerIdArray[1] + " .informationNotification p").show();
                $("#giftMessageNotification_" + layerIdArray[1]).fadeIn(1000).fadeOut(3000);

                //hide personalization link
                $("#table_" + layerIdArray[1] + " .messaging .addGreeting").hide();
                $("#table_" + layerIdArray[1] + " .addGiftMessage").html("Edit Gift Message");
                $("#table_" + layerIdArray[1] + " .messaging p:eq(0)").hide();


                var checkbox = this;
                $(".giftMessageLayer").each(function(i, item) {
                    var layerId = $(checkbox).parents(".commonLayer").attr("id");
                    var layerIdArray = layerId.split("_");
                    //alert(layerId);
                    if ($("input:checkbox").is(":checked")
                    && (($("#divGiftMessageContainer_" + layerIdArray[1] + " #" + id("txtGiftMessageLine1").attr("id")).val() !== "")
                    || ($("#divGiftMessageContainer_" + layerIdArray[1] + " #" + id("txtGiftMessageLine2").attr("id")).val() !== "")
                    || ($("#divGiftMessageContainer_" + layerIdArray[1] + " #" + id("txtGiftMessageLine3").attr("id")).val() !== "")
                    || ($("#divGiftMessageContainer_" + layerIdArray[1] + " #" + id("txtGiftMessageLine4").attr("id")).val() !== "")
                    )) {

                        var fields = {
                            one: $("#divGiftMessageContainer_" + layerIdArray[1] + " #" + id("txtGiftMessageLine1").attr("id")).val(),
                            two: $("#divGiftMessageContainer_" + layerIdArray[1] + " #" + id("txtGiftMessageLine2").attr("id")).val(),
                            three: $("#divGiftMessageContainer_" + layerIdArray[1] + " #" + id("txtGiftMessageLine3").attr("id")).val(),
                            four: $("#divGiftMessageContainer_" + layerIdArray[1] + " #" + id("txtGiftMessageLine4").attr("id")).val()
                        }
                        //alert(typeof fields.one);
                        $("#" + id("txtGiftMessageLine1").get()[i].id).val(fields.one);
                        $("#" + id("txtGiftMessageLine2").get()[i].id).val(fields.two);
                        $("#" + id("txtGiftMessageLine3").get()[i].id).val(fields.three);
                        $("#" + id("txtGiftMessageLine4").get()[i].id).val(fields.four);
                        $("#table_" + i + " .messaging .addGreeting").hide();
                        $("#table_" + i + " .addGiftMessage").html("Edit Gift Message");
                        $("#table_" + i + " .messaging p:eq(0)").hide();

                    }
                });
            });
            $(id("ApplyAboveToAll")).change(function() {
                var checkbox = this;
                $(".giftMessageLayer").each(function(i, item) {
                    var layerId = $(checkbox).parents(".commonLayer").attr("id");
                    var layerIdArray = layerId.split("_");
                    //alert(layerId);
                    if ($("input:checkbox").is(":checked")
                    && (($("#divGiftMessageContainer_" + layerIdArray[1] + " #" + id("txtGiftMessageLine1").attr("id")).val() !== "")
                    || ($("#divGiftMessageContainer_" + layerIdArray[1] + " #" + id("txtGiftMessageLine2").attr("id")).val() !== "")
                    || ($("#divGiftMessageContainer_" + layerIdArray[1] + " #" + id("txtGiftMessageLine3").attr("id")).val() !== "")
                    || ($("#divGiftMessageContainer_" + layerIdArray[1] + " #" + id("txtGiftMessageLine4").attr("id")).val() !== "")
                    )) {

                        var fields = {
                            one: $("#divGiftMessageContainer_" + layerIdArray[1] + " #" + id("txtGiftMessageLine1").attr("id")).val(),
                            two: $("#divGiftMessageContainer_" + layerIdArray[1] + " #" + id("txtGiftMessageLine2").attr("id")).val(),
                            three: $("#divGiftMessageContainer_" + layerIdArray[1] + " #" + id("txtGiftMessageLine3").attr("id")).val(),
                            four: $("#divGiftMessageContainer_" + layerIdArray[1] + " #" + id("txtGiftMessageLine4").attr("id")).val()
                        }
                        //alert(typeof fields.one);
                        $("#" + id("txtGiftMessageLine1").get()[i].id).val(fields.one);
                        $("#" + id("txtGiftMessageLine2").get()[i].id).val(fields.two);
                        $("#" + id("txtGiftMessageLine3").get()[i].id).val(fields.three);
                        $("#" + id("txtGiftMessageLine4").get()[i].id).val(fields.four);
                        $("#table_" + i + " .addGiftMessage").html("Edit Gift Message");
                        $("#table_" + i + " .messaging p:eq(0)").hide();

                    }
                });
            });
        },
        detectMessageGreetingOptions: function() {
            $(".messaging p").hide();
            if (($(".messaging .addGreeting").is(":visible")) && ($(id("divPersonalizedCardLink")).is(":visible"))) {
                $(".messaging p").show();
            }
        },
		actionAddedToCart : function(){
			//make cart icon glow
			//#siteUtil #siteToolsRight ul #items
			//$("#siteUtil #siteToolsRight ul #items").removeClass('default');
			$("#siteUtil #siteToolsRight ul #items").removeClass('full');
			$("#siteUtil #siteToolsRight ul #items").removeClass('flagGlow');
			
			// make cart added
			$("#siteUtil #siteToolsRight ul #items").addClass('added');			
			
			//$("#siteUtil #siteToolsRight ul #items .cartIconDisplay").css({opacity:0});			
			//$("#siteUtil #siteToolsRight ul #items .cartIconDisplay").animate({opacity:1}, 0);
			
			//wait few seconds then, stop glow and show full
			var changeGlowingIcon = setTimeout(site.func.actionItemsInCart, 3000);			
		},
		actionItemsInCart : function(){
			//$("#siteUtil #siteToolsRight ul #items").removeClass('default');
			$("#siteUtil #siteToolsRight ul #items").removeClass('added');
			
			// make cart full
			$("#siteUtil #siteToolsRight ul #items").addClass('full');
			
			//$("#siteUtil #siteToolsRight ul #items .cartIconDisplay").css({opacity:0});	
			//$("#siteUtil #siteToolsRight ul .cartIconDisplay").animate({opacity:1}, 0);
			clearTimeout(site.func.actionAddedToCart.changeGlowingIcon);
			// make cart icon show full 
		},
		actionEmptyCart : function() {
			// make cart icon show empty
			$("#siteUtil #siteToolsRight ul #items").removeClass('full');
			$("#siteUtil #siteToolsRight ul #items").removeClass('added');
			
			// make cart empty
			$("#siteUtil #siteToolsRight ul #items").addClass('default');
			
			//$("#siteUtil #siteToolsRight ul #items .cartIconDisplay").css({opacity:0});	
			//$("#siteUtil #siteToolsRight ul .cartIconDisplay").animate({opacity:1}, 0);
		}, 
		legacyTrufflesHover: function() {
		    // handle hover state for /landing/legacytruffles.aspx page
		    var hoverTimer;
            $("#legacyTrufflesBottom ul li").each(function() {
                var truffle = "#" + this.id;
                //define position
                liPositionX = lib.utils.getPosition(this)[0][0] - (10);
                liPositionY = lib.utils.getPosition(this)[0][1] + (50);
                //set position
                $(truffle + " .desc").css({ top: liPositionY, left: liPositionX });
                $(this).hover(function() {
                    if (hoverTimer != "undefined") {
                        clearTimeout(hoverTimer);
                        $("#legacyTrufflesBottom ul li .desc").hide();
                    }
                    $(truffle + " .desc").show();
                }, function() {
                    clearTimeout(hoverTimer);
                    hoverTimer = setTimeout(function() {
                        $("#legacyTrufflesBottom ul li .desc").hide();
                    }, 500);
                });
            });
        },
        addFocusToErrorField : function() {
            if(Page_IsValid == false)
                {                    
                    try
                    {
                        var maxCount = Page_Validators.length;
                        
                        for(var count = 0; count < maxCount;count++)
                        {
                            var ctrlValidator = Page_Validators[count];
                            
                            if(ctrlValidator.isvalid == false)
                            {                                
                                document.getElementById(ctrlValidator.controltovalidate).focus();
                                site.func.scrollToElement(document.getElementById(ctrlValidator.controltovalidate));
                                //$(window).css("scrolltop":0);
                                break;
                            }
                        }
                    }
                    catch(err)
                    {
                        //If User has entered first name & last name And missed the City 
                        //still it focuses the first name, the actual error may not be int visible scope

                        //$(id("txtFirstName")).focus();
                        if ( $(".adFirstName") != undefined && $(".adFirstName") != null && $(".adFirstName").get() != "" )
                         $(".adFirstName").focus();
                    }
                }
            return Page_IsValid;
        },
        scrollToElement : function(theElement) {
            var selectedPosX = 0;
              var selectedPosY = 0;
                          
              while(theElement != null){
                selectedPosX += theElement.offsetLeft;
                selectedPosY += theElement.offsetTop;
                theElement = theElement.offsetParent;
              }                                    		      
             window.scrollTo(selectedPosX,selectedPosY);
        },
		showRewardsLayer : function() {
			$(".js-showRewardsLayer").hover(function(){								
				//show layer
				$("#rewardsClubLayer").show();				
				//position layer here				
                linkPositionX = lib.utils.getPosition(this)[0][0];
                linkPositionY = lib.utils.getPosition(this)[0][1] + 15;

                //position layer
                $("#rewardsClubLayer").css({ top: linkPositionY, left: linkPositionX });
				
				$("#rewardsClubLayer .js-layerClose").click(function(event) {
                    event.preventDefault();
                    $("#rewardsClubLayer").hide();                    
                });
				
			});
			$("#rewardsClubLayer").hover(function(){
				$("#rewardsClubLayer").show();
			}, function(){
				$("#rewardsClubLayer").hide();
			});
		}
    },
    obj: {
        // site specfic objects
        pagination: function(settings) {
            if (arguments.length > 0)
            { this.init(settings); }
        }
    }
};





})($);


//instantiate objects
site.obj.pagination.prototype.init = function(settings) {
    if (settings == null)
    { settings = { pageTotal: null, currentPage: null, selectorForward: null, selectorBackward: null, resultsContainerNode: null }; }

    this.pageTotal = (settings.pageTotal == null) ? ".pageTotal" : settings.pageTotal;
    this.currentPage = (settings.currentPage == null) ? ".currentPage" : settings.currentPage;
    this.selectorForward = (settings.selectorForward == null) ? ".js-paginateForward" : settings.selectorForward;
    this.selectorBackward = (settings.selectorBackward == null) ? ".js-paginateBackward" : settings.selectorBackward;
    this.resultsContainerNode = (settings.resultsContainerNode == null) ? null : settings.resultsContainerNode;
    var currentItem = 0;
    var initial = true;

    var resultsCount = $(this.resultsContainerNode).each(function(i, items) {
        $(this).hide();        
    });
	
	// toggle display of pagination
	if(currentItem <= 0){
		$(this.selectorBackward).hide();
	}	
	if(currentItem == resultsCount.length){
		$(this.selectorForward).hide();
	}
	
    $(this.resultsContainerNode + ":eq(0)").show();
    $(this.pageTotal).html(resultsCount.length);

    var thisObj = this;
    $(this.selectorForward).click(function(e) {
        e.preventDefault();
        moveForward();
    });

    $(this.selectorBackward).click(function(e) {
        e.preventDefault();
        moveBackward();
    });

    function moveBackward() {
		// toggle display of pagination
		
        if (currentItem > 0) {
			$(thisObj.selectorForward).show();
            currentItem = currentItem - 1;            
            $(thisObj.resultsContainerNode).hide();
            $(thisObj.resultsContainerNode + ":eq(" + currentItem + ")").show();
            $(thisObj.currentPage).html(currentItem + 1);
			if (currentItem == 0) { $(thisObj.selectorBackward).hide(); }
        }
        else {			
            return;
        }
    }

    function moveForward() {
		
		//alert(currentItem + "after condition");
		if (currentItem >= resultsCount.length-1) { return; }
		else {
			$(thisObj.selectorBackward).show();
			currentItem = currentItem + 1;
			$(thisObj.resultsContainerNode).hide();
			$(thisObj.resultsContainerNode + ":eq(" + currentItem + ")").show();                
			$(thisObj.currentPage).html(currentItem+1);
			if (currentItem >= resultsCount.length-1) { $(thisObj.selectorForward).hide(); }			
		}
       
    }

};
var closeLayerOnClickOutside = function(element) {
	var nodeId = element.data.nodeID;
	var element = $(element.target)[0];
	var observe = $(nodeId)[0];

	while (true) {
		if (element == observe) {
			return true;
		} else if (element == document) {
			$(document).unbind('mousedown', closeLayerOnClickOutside);
			$(nodeId).hide();
			if (nodeId == "#quickShopEmailForm") {
				$("#catalogEmail").removeClass("selected");
			}
			return true;
		} else {
			element = $(element).parent()[0];
		}
	}
	return true;
};
// on body load
$(function() {
	// global variable
	//var clickedUrl;
    //Site on load.
    site.func.setupHeaderNavigation();
    site.func.setUpPanelCalls();
    site.func.setUpIntFooterTargets();
    site.func.setUpProductTabs();
    //site.func.clickableGlobalHdr();
    site.func.setUpSideBarNav();
    site.func.launchPostEmailSignUp();
	site.func.showRewardsLayer();
    site.func.postSearch();
    site.func.clearTextFields(".submit #inputSignUpSubmit", "#inputSignUpSubmit");
    site.func.printing();
    site.func.personalizeRibbon();
    site.func.fixBoxedPngInIE6();

    // site.func.switchShippingInfo
    site.func.switchShippingInfo();

    //instantiate any pagination obj    
    if ($(".pagingContent").get() != "") {
        new site.obj.pagination({
            pageTotal: ".pageTotal",
            currentPage: ".currentPage",
            selectorForward: ".js-paginateForward",
            selectorBackward: ".js-paginateBackward",
            resultsContainerNode: ".pagingResults"
        });
    }

    // take values from address book and fill form fields
    site.func.fillAddressBookValues();

    //site.func.clearTextFields(".search .input", "#inputGlobalSearch"); // global search
    //Run the Form Setup
    //lib.func.formSetup();

    site.func.toggleStateVsProvinceInAddressControl();
    site.func.populateMultiShipmentAddressControl();
    site.func.preUpdateAddressJson();
    site.func.inPagePanelDisplay();
    site.func.enableCalendar();
    if ($(".shippingGiftingContent").get() != "") {
        site.func.truncateLongHeaders(".formFieldSet1Hdr h3 span");
    }
    if ($(".giftingContent").get() != "") {
        site.func.clearGiftMessageFields();
        site.func.addConfirmationMessage();
        site.func.detectMessageGreetingOptions();
    }
	if ($("#survey").get() != ""){
		site.func.detectLeavingSurvey();
	}
	if ($("#legacyTrufflesBottom").get() != ""){
	    site.func.legacyTrufflesHover();
	}
	
	// onload if class exists make shopping bag icon glow:
	if($("#siteToolsRight #items").hasClass("flagGlow")) {
	    // make full
	    site.func.actionAddedToCart();
	    
	    // wait 1 second make added (glow)
	    //setTimeOut(actionAddedToCart, 1000);
	    	   
	}
	
});

function checkQuantity(ctrlID,crtlErrorID)
{
    checkQuantity(ctrlID,crtlErrorID,1);
}
function checkQuantity(ctrlID,crtlErrorID,minQuntity)
{
    var check= false;
    var text = document.getElementById(ctrlID).value;
    if($.trim(text).length > 0)
        check = isNumeric(document.getElementById(ctrlID).value);
    
    if(check)
    {
        var quntity = 0;
        quntity = parseInt(document.getElementById(ctrlID).value);
        if(quntity < minQuntity)
        check = false;
    }
    
        
    if(check == false)
        document.getElementById(crtlErrorID).setAttribute("style","Display:block");
    
    return check;
}

function isNumeric(sText)
{
	return IsNumeric1(sText,"0123456789");
}
function isDecimal(sText)
{
	return IsNumeric1(sText,"0123456789.-");
}

function IsNumeric1(sText,ValidChars)
{
   //var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
   for (i = 0; i < sText.length && IsNumber == true; i++) 
   { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
      {
			IsNumber = false;
      }
   }
   return IsNumber;
}
function countPersonalRibbonMessage(obj,message, key, maxlength) {
	var remaining = countRemainingCharacters(message, maxlength);
	
	if (remaining < 0) {
    	//$(".ribbonMessage_chars").val($(".ribbonMessage_chars").val().slice(0, -1));
    	obj.val(obj.val().slice(0, -1));
		$("#ribMessage_remaining").text("0");
		//remaining = countRemainingCharacters($(".ribbonMessage_chars").val(), maxlength);
		remaining = countRemainingCharacters(obj.val(), maxlength);
	}
	$("#ribMessage_remaining").text(remaining);

	// allow delete and backspace always
	if (key == 8 || key == 0) return true;
	// Block adding Characters if over limit
	return ((remaining > 0) ? true : false);
}
function countRemainingCharacters(message, maxlength) {
	var allCharacters = message.split("");
	var remaining = maxlength;
	for (var i = 0; i < allCharacters.length; i++) {
		if (allCharacters[i].match(/[A-Z]/g)) {
			remaining -= 2;
		} else {
			remaining--;
		}
	}
	return (remaining);
}
function updatedPerRibbonTotal() {
	var quantity = $(".ribbonQuantity").val();
	var productCost = $(id("txtProductCost")).val();

    if (!productCost) 
	    return;
	
	if (!quantity) 
	    return;
	
	if(isNaN(quantity))
	    quantity = 0;

	if(isNaN(productCost))
	    productCost = 0;

	var cost = Number($("#ribbonCost").text());
	var charm = ($(".ribbonCharm").val() == "" || $(".ribbonCharm").val() == undefined) ? 0 : parseFloat($(id("lblPricePerCharm")).text());
	var totalCost = quantity * (cost + charm);
	$("#ribbonTotalCost").text("$" + totalCost.toFixed(2));
	$("#ProductTotalCost").text("$" + ((productCost * quantity) + totalCost).toFixed(2));
}

function validateEmailPattern(source, arguments)
{
    if(source.controltovalidate.indexOf('txtEmail') > -1)
    {
        //alert("Natalie: Refactor isValidEmail() function ");
        if(arguments.Value.length == 0)
        {
            source.errormessage = "Please enter your email address."
            arguments.IsValid = false;
            return false;
        }
        else if (! isValidEmail(arguments.Value))
        {
            source.errormessage = "Please enter a valid email address."
            arguments.IsValid = false;
            return false;            
        }    
        return true;
    }
    
    return true;
    
}

//FUNCTION IS REPEATED, NATALIE has to REFACTOR THIS transferring onus to Nat coz Wes is not there :)
function isValidEmail(str) {
    var at = "@"
    var dot = "."
    var lat = str.indexOf(at)
    var lstr = str.length
    var ldot = str.indexOf(dot)

    if (str.indexOf(at) == -1) {
        return false
    }
    if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
        return false
    }
    if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
        return false
    }
    if (str.indexOf(at, (lat + 1)) != -1) {
        return false
    }
    if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
        return false
    }
    if (str.indexOf(dot, (lat + 2)) == -1) {
        return false
    }
    if (str.indexOf(" ") != -1) {
        return false
    }
    return true
}

function loginValidationPatternCheck(source, arguments)
{
    if(source.controltovalidate == $(id("txtLoyaltyNumber")).attr("id"))
    {
        /*
            1.	Sum up all the odd digits.
            2.	Sum up all the even digits.
            3.	Multiply the result from #1 by 3.
            4.	Add the result of #2 and #3.
            5.	Take the result of #4 modulo 10.
            6.	Subtract the result of #5 from 10.
            7.	Take the result of #6 modulo 10.
  
        */

        var loyaltyNumber = '';
        loyaltyNumber = $.trim(arguments.Value);
        
        if(isNumeric(loyaltyNumber) == false)
        {
            arguments.IsValid = false;
            return false;
        }
        if(loyaltyNumber.length != 14)
        {
            arguments.IsValid = false;
            return false;
        }
        
        //var i = 0;
        var sumOdd = 0;
        var sumEven = 0;
        var checkDigit = 0;
        
        for(i=0;i<loyaltyNumber.length;i++)
        {
            var digit = 0 ;
            digit = parseInt(loyaltyNumber.substr(i,1));
            if(digit % 2 == 0)
                sumEven += digit;
            else
                sumOdd += digit;
          
        }
        try { 
            checkDigit = (10 - (((sumOdd * 3) + sumEven) % 10)) % 10;
            return true; 
        }
        catch (err)
        {
            arguments.IsValid = false;
            return false;
        }
        
    }
}

function id(controlName)
{
	return $("[id$='" + controlName + "']");
}