/*
 * common.js
 * Common javascript to be run on every page of the Lowes.com web site.
 * 
 * Copyright Lowes, Inc.
 *
 */

var lowes=window.lowes || {};
lowes.common={
    init:function(){
        lowes.common._setupDZB();
        lowes.common._setupMyStoreInfo();
        lowes.common._setupMyStoreChangeStore();
        lowes.common._setupMyAccount();
        lowes.common._setupLeftNav();
        lowes.common._setupPrettyButtons();
        lowes.common._fixIE();
        lowes.common._fixIE6();
        lowes.common._setupSearchTipsModal();
        lowes.common._setupForgotPasswordModalHide();
        lowes.common._setupAutoTab();
        lowes.common._setupStoreChooser();
		lowes.common._replaceContexHelpWithFloatingPane();
        lowes.common._setupContextHelp();
        lowes.common._setupHoverTips();
        lowes.common._setupEmailFriend();
        lowes.common.sizeIframe();
        lowes.common._setupMiniCart();
    },
    createFloatPanel: function(href,title,prodId,addClass,isIframe){
        // make sure vars have values/set defaults for width/height
        prodId = prodId || "";
        addClass = addClass || "";
        width = 627;
        height = 300;
        // more height/width stuff
        if(addClass == "quickview-modal") {
            width=800;
            height=400;
        } else if((addClass == "demo-modal") || (addClass == "large-image-modal")) {
            height=600;
        }

        
        // if there's another floating pane, get rid of it 
        if(fpActive) {
            fpActive.destroy();
        }
        
        // set up args for floatingPane
        var fpArgs = {
            title:title,
            dockable: false,
            maxable: false,
            closable: true,
            resizable: false,
            duration:0,
            preventCache:true,
            _startZ:1000
        };
        
        // create a domNode for the floating pane
        var node = document.createElement('div');
        dojo.body().appendChild(node);
        
        // if we need an iframe, set it up
        if(isIframe){
            height = 600;
            //node.innerHTML = "<iframe src=\""+href+"\" frameborder=\"0\" width=\""+587+"\" height=\""+(height-80)+"\" />";
			// changed by RA on 8/18/09
			// iframe issues with IE6
			// this function (createFloatPanel) called on two JSP pages only (cachedGiftCardItemDisplay.JSP & cachedItemDisplay.JSP)
			node.innerHTML = '<div style="height:'+(height-80)+'; width:587px;"><img class="largerImageView" src="'+href+'" /></div>';
        } else {// if not, set the href of the floatingPane
            fpArgs.href = href;
        } 
        
        // create the floating pane
        var fp = new dojox.layout.FloatingPane(fpArgs,node);
        
        //get the dimensions of the current viewport
        var viewport = dijit.getViewport();
		
		//if floatingPane is being created for the shipping link, then ALWAYS position the popup 160px from the top.
		function positionTop(){
			var top;
			if(addClass == "shipping-link" || addClass == "help-link"){
				top = 160;
			}else{
				top = ((viewport.h/2) + viewport.t) - (height/2);
			}
			return top;
		}
        
        // use them to determine the position the floatingPane (not actually positioned until onLoad)
        var position_l = ((viewport.w/2) + viewport.l) - (width/2);
        var position_t = positionTop();

        // floatingPane is resized after it loads
        fp.isResized=false;
        var actualHeight = null;

        // attached to onload of FP if we're loading via AHAH, called directly if we've got an iframe.
        var fpOnLoad = function(e){
            // methods to set up content of floating panel
            if(addClass == "quickview-modal") {
                lowes.catalog._postQuickviewLoad(prodId, fp.domNode);
            } else if((addClass == "demo-modal") || (addClass == "large-image-modal") || (addClass == "demo-modal") || (addClass == "large-image-modal")) {
                lowes.catalog._postDemoLoad(prodId, fp.domNode);
            }

            
            if (dojo.isIE && dojo.isIE<7) { // fix dropdown bleedthru in IE6
                fp.domNode.appendChild(document.createElement('iframe'));
            }
            if(addClass == "quickview-modal") {
                //if the Floating Panel is a QV pop up, e.target.blur() is not used to allow to enter a value into the "Enter zip code" text field.
                setTimeout(function(){
                    // not really sure what's going on here. 
                    fp.connect(fp.domNode,'onclick',function(e){
                        e.stopPropagation();
                        return false;
                    });
                    // this makes the floating pane disappear when you click outside of it.
                    
                    fp.connect(dojo.doc,'onclick',function(e){
                        this.hide();
                    });
                },100); // timeout to workaround a race condition in IE
            }else{
                setTimeout(function(){
                    // not really sure what's going on here. 
                    fp.connect(fp.domNode,'onclick',function(e){
                        e.target.blur();
                        e.stopPropagation();
                        return false;
                    });
                    // this makes the floating pane disappear when you click outside of it.
                    
                    fp.connect(dojo.doc,'onclick',function(e){
                        this.hide();
                    });
                },100); // timeout to workaround a race condition in IE
            }
            
            // get the height of the new domNode
            actualHeight=dojo.marginBox(fp.domNode).h;
            if(!fp.isResized){
                fp.resize({ w:width, h:actualHeight, t:position_t, l:position_l });
                fp.domNode.style.visibility='visible';
                fp.isResized = true;
            }
        };
        
        if(isIframe){
            fpOnLoad();
        } else {
            fp.connect(fp,'onLoad',fpOnLoad);
        }
        
        // hide until resized to avoid jumpiness for user
        if(actualHeight==null){
            fp.domNode.style.visibility='hidden';
        }
        
        // get rid of the panel once it's closed. 
        if (addClass == "quickview-modal"){ 
			//need to destroy first the dijit.Dialog for the dojo link if this does exist. 
			dojo.connect(fp,'hide',function() { 
				var qv = fp.getDescendants(); 
				qv.forEach(function(el){ 
					if (el.id.indexOf("qv_find_product") > -1){ 
						el.destroy(); 
						} 
					}); 
				fp.destroy(); 
                        });         
                }else{ 
                        dojo.connect(fp,'hide',function() { 
                                fp.destroy(); 
                        }); 
                }  

        fp.startup();
        dojo.addClass(fp.domNode, addClass);
        
        if (actualHeight != null && !fp.isResized) {
            // Size and place this Floating Pane
            fp.resize({
                w: width,
                h: height,
                t: position_t,
                l: position_l
            });
            fp.domNode.style.visibility='visible';
            fp.isResized = true;
        }
        fpActive = fp;
        return false;
    },
    setupDojo:function(){
        dojo.require("dijit.Dialog");
        dojo.require("dijit.form.ComboBox");
        dojo.require("dijit.layout.ContentPane");
        dojo.require("dijit.layout.TabContainer");
        dojo.require("dijit.form.ComboBox");
        dojo.require("dojox.layout.FloatingPane");
        dojo.require("dijit.Tooltip");
        dojo.require("dojo.parser");    // scan page for widgets and instantiate them
        dojo.require("dijit.form.Button"); 
        //dojo.require("dojo.fx");
    },
    _setupDZB:function(){
        var $dzb = dojo.byId('dzb');
        var $openDZB = dojo.byId('find-store');
        var $myStore = dojo.byId('my-store');
        var $dzbBar = dojo.byId('dzb-bar');
        // If they've chosen a store, the DZB will not
        // be on the page, so go ahead and return
        if(!$dzb) return;
        
        // Check cookie value
        var _dzbState = readCookie('dzb_state');
        // Hook up open link
        dojo.connect($openDZB, 'onclick',function(ev){
            ev.preventDefault();
            dojo.style($dzb,'top','25px');
            if($myStore) dojo.addClass($myStore, 'hidden');
            if($dzbBar) dojo.style($dzbBar, 'display', 'block');
            // They've opened the DZB, so set the cookie appropriately
            createCookie('dzb_state','shown', 0);
            
        });
        // Hook up close link
        dojo.connect(dojo.query('a.close', $dzb)[0], 'onclick',function(){
            dojo.style($dzb,'top','-45px');
            if($myStore) dojo.removeClass($myStore, 'hidden');
            if($dzbBar) dojo.style($dzbBar, 'display', 'none');
            // They've closed the DZB, so set the cookie appropriately
            createCookie('dzb_state','closed', 0);
        });
        // If they've seen the animation, but stil haven't 
        // chosen a store, just show the DZB
        if(_dzbState == 'shown') {
            dojo.style($dzb,'top','25px');
            if($dzbBar) dojo.style($dzbBar, 'display', 'block');
            if($myStore) dojo.addClass($myStore, 'hidden');
            return;
        }
        // IF they've closed the DZB, move it off the screen
        if(_dzbState == 'closed') {
            dojo.style($dzb,'top','-45px');
            if($dzbBar) dojo.style($dzbBar, 'display', 'none');
            if($myStore) dojo.removeClass($myStore, 'hidden');
            return;
        }
        // If they haven't seen the animation and haven't 
        // chosen a store animate the DZB
        if(!_dzbState) {
            if($myStore) dojo.addClass($myStore, 'hidden');
            dojo.animateProperty({
                node: 'dzb',
                duration: 2000, 
                properties: {
                    top: { start: '-50', end: '25', unit:"px" }
                },
                onEnd: function(){
                    // Set the cookie to show that they've seen the animation.
                    // It will expire when the browser is closed.
                    createCookie('dzb_state','shown', 0);
                }            
            }).play();
        }
        // Cookie functions
        function createCookie(name,value,days) {
			var expires;
            if (days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000));
                expires = "; expires="+date.toGMTString();
            }
            else expires = "";
            document.cookie = name+"="+value+expires+"; path=/";
        }
        function readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for(var i=0;i < ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
            }
            return null;
        }
        function eraseCookie(name) {
            createCookie(name,"",-1);
        }
        
    }, 
    _setupMyStoreInfo:function(){

        var $currentStore = dojo.byId('current-store2');
        var currentStoreLinks = dojo.query(".current-store-link2");
        var $currentStoreInfo = dojo.byId('my-store-more-info2');
     
        if(!$currentStore || !$currentStoreInfo) return;
        dojo.body().appendChild($currentStoreInfo);
        dojo.style($currentStoreInfo, 'zIndex', '1000');
        currentStoreLinks.connect('onclick', function(ev, el){
            ev.preventDefault();
            
            var _currentState = dojo.style($currentStoreInfo, 'display');
            if (_currentState == 'none' ) {
                // The link we'll use to retrieve the store info will be in the href of the anchor tag
                // and will be after the # sign.  
                var href = ev.currentTarget.href;
                if ( href ) {
                    // We put the url after a # sign so it degrades gracefully if this method doesn't get called.
                    var url = href.split('#')[1];
               		
                    if ( url ) {
                        // The ul list goes into the first content node of my-store-more-info
                        var contentNode = dojo.query(".content2", $currentStoreInfo)[0];
                        
                        if ( contentNode ) {
                            // Make the ajax call to get the <ul> with the store information.  This call should
                            // be going to MastHeadStoreInfoView.
                             
                            dojo.xhrGet({
                                url : url,
                                handleAs : "text",
                                load : function(response, ioArgs) {
                                	
                                    if ( response ) {
                                        // Make sure the response we receieved was from the MastHeadStoreInfo page and not
                                        // something else like the GenericErrorPage.  
                                        if ( response.indexOf('TOKEN:MastHeadStoreInfo:') != -1) {
                                            contentNode.innerHTML = response;
                                            var storeName = dojo.query(".current-store2", $currentStoreInfo)[0];
										 	storeName.innerHTML = $currentStore.innerHTML;
                                        }
                                    }
                                },
                                error : function(response, ioArgs) {
                                    // Ignore errors.  The default <ul> list contains some information so just keep showing that.
                                }
                            });
                        }
                    }
                }
                dojo.style($currentStoreInfo, 'display', 'block');
				/*
                var pos = dojo._abs(ev.currentTarget, true);
                dojo.style($currentStoreInfo, "top",(pos.y + 10)+"px");
                dojo.style($currentStoreInfo, "left",pos.x+"px");*/
            } else {
                dojo.style($currentStoreInfo, 'display', 'none');
            }
        });    
        // Hook up close button
        var $close = dojo.query('a.close', $currentStoreInfo)[0];
        dojo.connect($close, 'onclick', function(ev){
            ev.preventDefault();
            dojo.style($currentStoreInfo, 'display', 'none');
        });
        // Click outside to close
        setTimeout(function(){
            dojo.connect($currentStoreInfo,'onclick',function(e){
                e.target.blur();
                e.stopPropagation();
                return false;
            });
            dojo.connect(dojo.doc,'onclick',function(e){
                if(!dojo.hasClass(e.target,"current-store-link2")) {
                    dojo.style($currentStoreInfo, 'display', 'none');
                }
            });
        },100); // timeout to workaround a race condition in IE
        // Hover outside to close
        hoverIntentTimer = false;
        dojo.connect($currentStoreInfo, 'onmouseout', function(){
            hoverIntentTimer = setTimeout(function(){
                dojo.style($currentStoreInfo, 'display', 'none');
            }, 3000);        
        });
        // Cancel mouseout timer
        dojo.connect($currentStoreInfo, 'onmouseover', function(){
            if (hoverIntentTimer) {
                clearTimeout(hoverIntentTimer);
            }
        });
    }, 
    _setupMyStoreChangeStore:function() {
        var $changeCurrentStore = dojo.byId('change-current-store');
        var $myStoreChangeStore = dojo.byId('my-store-change-store');
		
		if(!$changeCurrentStore || !$myStoreChangeStore) return;
        /*dojo.connect($changeCurrentStore, 'onclick', function(ev, el){
			populateStoreListInfo.populateStoreListInfoFunc();
			ev.preventDefault();
            // Adjust the location of the element
            var coords = dojo.marginBox(ev.target);
            //dojo.style($myStoreChangeStore, 'left', (coords.l-10) + 'px');
            var _currentState = dojo.style($myStoreChangeStore, 'display');
            if (_currentState == 'none' ) {
                dojo.style($myStoreChangeStore, 'display', 'block');
            } else {
                dojo.style($myStoreChangeStore, 'display', 'none');
            }
        });*/
		
        // Hook up close button
        var $close = dojo.query('a.close', $myStoreChangeStore)[0];
        dojo.connect($close, 'onclick', function(ev){
            ev.preventDefault();
            dojo.style($myStoreChangeStore, 'display', 'none');
        });
        // Click outside to close
       /* setTimeout(function(){
            dojo.connect($myStoreChangeStore,'onclick',function(e){
                e.target.blur();
                e.stopPropagation();
                return false;
            });
            dojo.connect(dojo.doc,'onclick',function(e){
                if(e.target != $changeCurrentStore) {
                    dojo.style($myStoreChangeStore, 'display', 'none');
                }
            });
        },100);*/ // timeout to workaround a race condition in IE
        // Hover outside to close
        hoverIntentTimer2 = false;
        dojo.connect($myStoreChangeStore, 'onmouseout', function(){
            hoverIntentTimer2 = setTimeout(function(){
                dojo.style($myStoreChangeStore, 'display', 'none');
            }, 3000);        
        });
        // Cancel mouseout timer
        dojo.connect($myStoreChangeStore, 'onmouseover', function(){
            if (hoverIntentTimer2) {
                clearTimeout(hoverIntentTimer2);
            }
        });
        
        // Go ahead and set up the show/hide functions
        var $moreInfoLinks = dojo.query('a.more-info', $myStoreChangeStore);
        $moreInfoLinks.forEach(function(el){
            dojo.connect(el, 'onclick', function(ev,el){
                ev.preventDefault();
                var $this = ev.target;
                // Get the parent
                var $parent = $this.parentNode;
                // Get the UL and determine it's state
                var $ul = dojo.query('ul:first', $parent)[0];
                var _state = dojo.hasClass($ul,'hidden');
                if(_state) {
                    if ( $ul ) {
                        // The link we'll use to retrieve the store info will be in the href of the anchor tag
                        // and will be after the # sign.  
                        var href = ev.currentTarget.href;
                        if ( href ) {
                            // We put the url after a # sign so it degrades gracefully if this method doesn't get called.
                            var url = href.split('#')[1];
                            if ( url ) {
                                // The ul list will replace the current ul list which is surrounded by a generic div
                                var contentNode = $ul.parentNode;
                                if ( contentNode ) {
                                    // Make the ajax call to get the <ul> with the store information.  This call should
                                    // be going to MastHeadStoreInfoView.
                                    dojo.xhrGet({
                                        url : url,
                                        handleAs : "text",
                                        load : function(response, ioArgs) {
                                
                                            if ( response ) {
                                                // Make sure the response we receieved was from the MastHeadStoreInfoView page and not
                                                // something else like the GenericErrorPage.  
                                                if ( response.indexOf('TOKEN:MastHeadStoreInfo:') != -1) {
                                                    contentNode.innerHTML = response;
                                                }
                                            }
                                        },
                                        error : function(response, ioArgs) {
                                        // Ignore errors.  The default <ul> list contains some information so just keep showing that.
                                        }
                                    });
                                }
                            }
                        }
                    }
                    dojo.removeClass($ul, 'hidden');
                    $this.innerHTML = 'Hide';
                } else {
                    dojo.addClass($ul, 'hidden');
                    $this.innerHTML = 'More Info';
                }
            });
        });
    },
    _setupMyAccount:function(){
        // ***** My Account Drop Down *****
        var myAccount = dojo.byId('my-account-control');
        if(!myAccount) return;
        var myAccountLink = dojo.query('a:first', myAccount)[0];
        var myAccountDropDown = dojo.query('ul',myAccount)[0];
        if(!myAccountDropDown) return;
        if(myAccountLink) dojo.connect(myAccountLink, 'onclick', myAccountLink, function(){
            var dropDownState = dojo.style(myAccountDropDown,'display');
            if(dropDownState == 'block') {
                dojo.style(myAccountDropDown, 'display', 'none');
            } else {
                dojo.style(myAccountDropDown, 'display', 'block');
            }
        });
        // Fix select box bleed through for IE6
        if (dojo.isIE && dojo.isIE<7) { 
            myAccountDropDown.appendChild(document.createElement('iframe'));
        }
        // Close My Account Drop Down when you click outside of it
        dojo.connect(dojo.doc, 'onclick', function(e){
            var myAccount = dojo.byId('my-account-control');
            var myAccountLink = dojo.query('a', myAccount)[0];
            var myAccountDropDown = dojo.query('ul',myAccount)[0];
            if( (e.target == myAccountLink) || (e.target == myAccountDropDown) ) return;
            if(myAccountDropDown){
                var dropDownState = dojo.style(myAccountDropDown,'display');
                if(dropDownState == 'block') {
                    dojo.style(myAccountDropDown, 'display', 'none');
                }
            } 
        });            
    },
    _setupLeftNav:function(){
        // ***** LEFT NAV ACCORDION EFFECT *****
        // Find all expanders and attach click event to add/remove 'open' class
        dojo.query('#expandable-nav li.expander').forEach(function(toggler){
            var $this = toggler;

            var $a = dojo.query('a',$this)[0];
            dojo.connect($a, 'onclick', $a, function(e){
                this.blur();
                dojo.toggleClass($this, 'open');
                e.preventDefault();
            });                
        });
        // Find all 'show-more' links and attach click event to show hidden elements
        dojo.query('#expandable-nav li.show-more').forEach(function(element){
            var $this = element;
            var $parent = $this.parentNode;
            var $a = dojo.query('a', $this)[0];
            var $hidden = dojo.query('li.hidden', $parent);
            dojo.connect($a, 'onclick', $a, function(e){
                this.blur();
                e.preventDefault();
                if($a.innerHTML != 'Less...') {
                    $a.innerHTML = 'Less...';
                    $hidden.forEach(function(element){
                        dojo.removeClass(element, 'hidden');
                        dojo.addClass(element,'show')
                    });
                } else {
                    $a.innerHTML = 'More...';
                    $hidden.forEach(function(element){
                        dojo.addClass(element, 'hidden');
                        dojo.removeClass(element,'show')
                    });
                }
            });
        });
    },
    _setupPrettyButtons:function(){
        /* 
            ***** PRETTY BUTTONS *****
            Find every input button with a class of js-submit, hide it, insert
            a link that is styled to look like a button (as defined in css/main.css) 
            and attach an onclick event to the inserted link that submits the form.
                Example of HTML element: 
                <input class="js-submit button-red" type="submit" value="Create Account"/> 
                 Note that 'button-red' is used to style the A tag that is inserted by the script.
                To create new button styles, just create the rules in css/main.css and use the new style
                in the input tag, ex: <input class="js-submit new-button-style"...
        */
        dojo.query("input.js-submit").forEach(
            function(inputElement) {
                var $submit = inputElement;
                if(!$submit) return;
                var $value = $submit.getAttribute('value');
                var $class = $submit.className;
                // Create new link with a click event that fires the original submit button
                var $link = dojo.doc.createElement("a");
                $link.setAttribute("href","javascript:void(0);");
                $link.className = $class;
                $link.innerHTML = "<span>" + $value + "</span>";
                dojo.place($link, $submit, 'before');
                dojo.style($submit, 'display', 'none');
                // Attach the event
                dojo.connect($link, 'onclick', $link, function(e){
                    dojo.stopEvent(e); // stop link from triggering usual event
                    $submit.form.submit(); // submit form
                });
               });    
    },
    _fixIE:function(){
        /*
            ***** FORM SUBMIT BY ENTER KEY FOR Internet Explorer
            IE does not allow the enter key to submit forms with hidden submit
            buttons, so we need to use this script to enable this feature.
            This allows the enter key to submit forms in IE
        */
        if (dojo.isIE) {
            dojo.query("input").forEach(
                function(inputElement) {
                    dojo.connect(inputElement, 'onkeydown', inputElement, function(e){
                        if(e.keyCode == 13) {
                            var $form = this.form;
                            var $submit = dojo.query("input[type='submit']", $form);
                            // If the submit key is not hidden, no need to do anything
                            if ($submit != null && $submit != ""){ 
                                if( dojo.style($submit[0], 'display') == 'block') return false;

                                // Submit the form
                                $form.submit();
                                return false;
                            }
                        }
                    });
            });
        }
    },
    _fixIE6:function(){
        if (dojo.isIE && dojo.isIE<7) {
            /*
             * Swap out the Service Desk image PNG with a GIF version for IE 6 and below
             */
            var $serviceDeskImage = document.getElementById('service-desk-image') ? document.getElementById('service-desk-image') : '';
            if ($serviceDeskImage != '') {
                $serviceDeskImage.src = '../images/service_desk.gif';
            }
            
            /* insert iframe in dropdown menus */
            dojo.query("#global-nav ul.subnav, #global-nav ul.subnav2, #cart-account ul.accountmenu").forEach(function(el){
                var ifr = document.createElement('iframe');
                el.appendChild(ifr);
            });
            /* insert empty div to fix CSS bug where bottom of page jumps on left nav hover */
            var bottomBlock = dojo.byId('page-bottom-block');
            if(bottomBlock){
                var node = document.createElement('div');
                dojo.place(node, bottomBlock, 'after');    
            }
        }

    },
    _setupSearchTipsModal:function(){
        dojo.query("a.search-tips").forEach(function(el){
            dojo.connect(el, 'onclick', el, function(e){
                e.preventDefault();
                lowes.common.createFloatPanel(el.href, el.title);
                return false;
            });
        });
    },
    _setupForgotPasswordModalHide:function(){
        dojo.query("#dialog_login div span.dijitDialogCloseIcon").forEach(function(el){
            dojo.connect(el, 'onclick', el, function(e){
                var passwordLayer = document.getElementById("forgot-password");
                if(!passwordLayer) return;
                e.preventDefault();
                dojo.style(passwordLayer, "display", "none")
                return false;
            });
        });
    },
    _setupAutoTab:function(){
        dojo.query("input.js-autotab").forEach(function(el){
            var maxLength = el.maxLength;
            if(!maxLength) return false;
            // Find next input field
            var f = el.form;
            var els = f.elements;
            for (var i=0, len=els.length; i<len; i++){
                if (el == els[i]){
                    // If the next field is not a text 
                    // input field, we don't tab to it.
                    if(els[i+1].type == 'text') {
                        var nextField = els[i+1];
                    } else {
                        return false;
                    }
                }
            }
            dojo.connect(el, 'onkeyup', el, function(e){
                if (el.value.length == maxLength) {
                 if (window.event.keyCode != 9 && window.event.keyCode != 16){
                    nextField.focus();
                   }
                } else {
                    return false;
                }
            });
        });
    }, 
	  _setupStoreChooser:function(){
        var lnk = dojo.byId('js-open-store-chooser');
        if (lnk){
            dojo.connect(lnk, 'onclick', function(){
                dojo.query('.store-chooser').forEach(function(el){
                    dojo.style(el, 'display','block');
                    // TODO: Add a function to manipulate user's cookie as that functionality is currently out of scope.
                });
            });
        }
        
        lnk = dojo.byId('js-close-store-chooser');
        if (lnk) {
            dojo.connect(lnk, 'onclick', function(){
                dojo.query('.store-chooser').forEach(function(el){
                    dojo.style(el, 'display', 'none');
                // TODO: Add a function to manipulate user's cookie as that functionality is currently out of scope.
                });
            });
        }
    },
    _setupMiniCart:function(){
        var minicart = new lowes.common.MiniCartCookie();
        if ( minicart && minicart.cart ) {
            var minicartNode = dojo.byId("mini-cart-display");
            if( minicartNode ) {
                  minicartNode.innerHTML = minicart.displayText();
            }
        }
    },
	_replaceContexHelpWithFloatingPane:function(){//added 8/6/2009 by JC - updated 9/1/09 by JC to fix defect 8197 
		/*if (dojo.query('.shipping-link')){
					//remove the contextHelp class from the link to prevent the _setupcontextHelp function from attaching an onclick event to it.
					dojo.query('.shipping-link').removeClass('contextHelp');
					//add a new onclick event to the link
					dojo.query('.shipping-link').forEach(function(node){
						dojo.connect(node, 'onclick', function(ev){ev.preventDefault();lowes.common.createFloatPanel(node.href,'Lowe\'s Shipping & Return Policies','','shipping-link',false); return false;})
					});
		}
		if (dojo.query('.help-link')){
					//remove the contextHelp class from the link to prevent the _setupcontextHelp function from attaching an onclick event to it.
					dojo.query('.help-link').removeClass('contextHelp');
					//add a new onclick event to the link
					dojo.query('.help-link').forEach(function(node){
						dojo.connect(node, 'onclick', function(ev){ev.preventDefault();lowes.common.createFloatPanel(node.href,'Lowe\'s Help','','help-link',false); return false;})
					});
		}*/
		if (dojo.query('.checkout-container fieldset ol form li label a.outdent')){
					//remove the contextHelp class from the link to prevent the _setupcontextHelp function from attaching an onclick event to it.
					dojo.query('.checkout-container fieldset ol form li label a.outdent').removeClass('contextHelp');
					//add a new onclick event to the link
					dojo.query('.checkout-container fieldset ol form li label a.outdent').forEach(function(node){
						dojo.connect(node, 'onclick', function(ev){ev.preventDefault();lowes.common.createFloatPanel('/wcsstore/B2BDirectStorefrontAssetStore/MContent/Structured/TopIconArea/w633.html','Security Code','','secCode-link',false); return false;})
					});
		}
	},
	_setupContextHelp:function(scopeId){
		/* add contextHelp to icons without on checkout page */
		dojo.query('tr.payment a.outdent').addClass('contextHelp');
		dojo.query('.contextHelp',scopeId).forEach(function(element, index){
			dojo.connect(element, 'onclick',function(ev){
				/* Run check to see if element has a class of clicked */
				if(!dojo.hasClass(element,'context_clicked')) {
				
					ev.preventDefault();
				
					/* Set a flag so we know the element has already been clicked */
					dojo.addClass(element,'context_clicked');
					
					ttdHref = element.href;
					ttdTitle = element.title;
					ttdRel = element.rel;
					var tooltip = document.createElement('div');
					var id = "";
					
					while (document.getElementById('contextHelp-' + index)){
						index++;
					}
									
					id = 'contextHelp-' + index;
					
					if (index > 0) {
						var idBefore = 'contextHelp-' + (index - 1);
						if(dojo.byId(idBefore)) dojo.byId(idBefore).parentNode.removeChild(dojo.byId(idBefore));
					}
					
					if(dojo.byId(id)) dojo.byId(id).parentNode.removeChild(dojo.byId(id));
					tooltip.id = id;
				   
					dojo.body().appendChild(tooltip);
					
					// fix dropdown bleedthru in IE6
					if (dojo.isIE && dojo.isIE < 7){
							
						var hideObject = true;
						var hiddenObject = new Array();
							
						switch(ttdRel){
							case 'W606':
								dojo.style(dojo.byId("scGenericshipModeId"), "visibility", "hidden");
								hiddenObject.push(dojo.byId("scGenericshipModeId"));
								break;
							case 'payPIN-help':
								dojo.style(dojo.byId("checkout-card-type"), "visibility", "hidden");
								hiddenObject.push(dojo.byId("checkout-card-type"));
								break;
							case 'secCode-help':
								dojo.style(dojo.byId("expiration-month"), "visibility", "hidden");
								hiddenObject.push(dojo.byId("expiration-month"));
								break;
							case 'rememberme-help':
								dojo.style(dojo.byId("challengeQuestion"), "visibility", "hidden");
								hiddenObject.push(dojo.byId("challengeQuestion"));
								break;
							default:
								hideObject = false;
						}
					}
                
					var ttd = new dijit.TooltipDialog({
						title:ttdTitle, 
						href:ttdHref
					}, tooltip);
                
					// Set up closing mechanisms
					ttd.connect(ttd,'onLoad',function(e){
						// Insert the close button
						var $button = document.createElement('button');
						$button.name='close';
						ttd.containerNode.appendChild($button);
						ttd.connect($button,'onclick',function(e){
							
							dojo.removeClass(element, 'context_clicked');
							
							e.target.blur();
							e.stopPropagation();
							ttd.destroy();
							dojo.style(tt_iframe,"display","none");
							//delete tt_iframe;
                        
							// fix dropdown bleedthru in IE6
							if (dojo.isIE && dojo.isIE < 7 && hideObject){
								for(i = 0; i < hiddenObject.length; i++){
									dojo.style(hiddenObject[i], "visibility", "visible");
								}
								hiddenObject = [];
							}
						});
						
						setTimeout(function(){
							ttd.connect(ttd.domNode,'onclick',function(e){
								e.stopPropagation();
								return false;
							});
							
							ttd.connect(dojo.doc,'onclick',function(e){
								dojo.removeClass(element, 'context_clicked');
								
								this.destroy();
							
								// fix dropdown bleedthru in IE6
								if (dojo.isIE && dojo.isIE < 7 && hideObject){
									for(i = 0; i < hiddenObject.length; i++){
										dojo.style(hiddenObject[i], "visibility", "visible");
									}
									hiddenObject = [];
								}
								if(this.id == currentIdIs){
									dojo.style(tt_iframe,'display','none');
								}
							});
							var closeButton = dojo.byId('ttdClose');
							ttd.connect(closeButton,'onclick',function(e){
								this.destroy();
								
								// fix dropdown bleedthru in IE6
								if (dojo.isIE && dojo.isIE < 7 && hideObject){
									for(i = 0; i < hiddenObject.length; i++){
										dojo.style(hiddenObject[i], "visibility", "visible");
									}
									hiddenObject = [];
								}
							});
						},100); // timeout to workaround a race condition in IE
					});
					
					// IF there is a div with an ID matching the rel attribute from this element,
					// we'll use that content for the tooltip dialog.
					if(element.rel) {
						var $tooltipContent = dojo.byId(element.rel);
						if($tooltipContent) {
							ttd.setContent('<div>'+$tooltipContent.innerHTML+'</div>');
						}
					}
                
					// Set up location of TooltipDialog based on where you click on the page.
					var _pageX = ev.pageX;
					var _pageY = ev.pageY;
					if(dojo.isIE) { // for IE
						var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body
						_pageX = ev.clientX + iebody.scrollLeft;
						_pageY = ev.clientY + iebody.scrollTop;
					}
					// This adusts for the location of TooltipDialog based on its size.
					var _adjustX = -227;
					var _adjustY = 9;
                
					// We know the tooltip Dialog is 277px wide, so make sure we aren't 
					// too close to the left edge.  If so, make this tooltip move off to 
					// the right of the element.
					if(_pageX < 277) { 
						ttd.domNode.className = 'dijitTooltipDialogTopLeft';
						_adjustX = -47;
					}
					dojo.style(ttd.domNode, "position", "absolute");
					dojo.style(ttd.domNode, "top", _pageY + _adjustY + "px");
					dojo.style(ttd.domNode, "left", _pageX + _adjustX + "px");
					dojo.style(ttd.domNode, "zIndex", 9999);
	
					ourTooltip = document.getElementById(tooltip.id);
                                
					if(window.tt_iframe === undefined){
						tt_iframe = document.createElement('iframe');
						tt_iframe = dojo.body().appendChild(tt_iframe);
						tt_iframe.id = 'tt_iframe';
					} else {
						dojo.style(tt_iframe,'display','block');
					}
					currentIdIs = tooltip.id;
					dojo.style(tt_iframe,'position','absolute');
					dojo.style(tt_iframe, "top", _pageY + _adjustY + "px");
					dojo.style(tt_iframe, "left", _pageX + _adjustX + "px");
					dojo.style(tt_iframe,'width',277+'px');
					dojo.style(tt_iframe,'zIndex',9998);
					dojo.style(tt_iframe,'border','none');
					document.getElementById(tt_iframe.id).setAttribute("frameborder","0");
					ourHeight=ttd.domNode.offsetHeight;
					dojo.style(tt_iframe,'height',ourHeight+'px');
						
					// Startup the TooltipDialog
					ttd.startup();
					return false;
				} else {
					ev.preventDefault();
				}
            });
        });
    }, 
    _setupHoverTips:function(scopeId){

		/* Run function on Product Compare page */
		if ( window.location.pathname.indexOf('LowesProductComparisionCmd') >= 0 ) {

			dojo.query('.hoverTip',scopeId).forEach(function(element, index){
	   			var ht;
	            dojo.connect(element, 'onmouseover',function(ev){
	                ev.preventDefault();
	                if(element.rel) {
	                    var tipAltTxt = element.rel;
	                } else {
	                    var tipAltTxt = element.alt;
	                }
                
	                var hoverTip = document.createElement('div');
	                var id = 'hoverTip' + index;
	                if(dojo.byId(id)) {
	                    dojo.byId(id).parentNode.removeChild(dojo.byId(id));
	                }        
	                hoverTip.id = id;        
	                dojo.body().appendChild(hoverTip);
	                ht = new dijit.TooltipDialog({
	                        title:tipAltTxt, 
	                        href:tipAltTxt
	                }, hoverTip);
	                ht.setContent('<div class="hovertip">'+tipAltTxt+'</div>');
                
	                // Set up location of TooltipDialog based on where you hover on the page.
	                var _pageX = ev.pageX - 150;
	                var _pageY = ev.pageY + 10;
	                //var _pageX = ev.pageX + 18;
	                //var _pageY = ev.pageY - 28;
	                if(dojo.isIE) { // for IE
	                    //var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body
	                    //_pageX = ev.clientX + iebody.scrollLeft;
	                    //_pageY = ev.clientY + iebody.scrollTop;
	                }
                
	                dojo.style(ht.domNode, "position", "absolute");
	                dojo.style(ht.domNode, "top", _pageY + "px");
	                dojo.style(ht.domNode, "left", _pageX + "px");
	                dojo.style(ht.domNode, "zIndex", 10000);
                
	                // Remove the alt attribute for IE
	                //if(element.alt) element.alt = '';

	                // Startup the TooltipDialog
	                ht.startup();
	                return false;
	            });
	            dojo.connect(element, 'onmouseout',function(ev){
	                ht.destroy();
	            });
	        });
		}	
    },
    _setupEmailFriend:function(url) {
        var $emailLink = document.getElementById("email-page");
        if(!$emailLink) return;
        //dojo.connect($emailLink, 'onclick', null, function(){popWin(url,"emailWin",600,880,100,100,"yes","yes")});
    },
    setupIframeContextHelp:function(iframeRef){
        dojo.withDoc(iframeRef, lowes.common._setupContextHelp());
    },
    setupUnderlay:function(id) {
        if(dojo.byId('dijit_DialogUnderlay_0')) {
            dojo.connect(dojo.byId('dijit_DialogUnderlay_0'),'onclick',function(e) {
                if(dijit.byId(id)) dijit.byId(id).hide();
                return false;
            });
        }
        //myUnderlay = dijit.byId(id);
        //if(myUnderlay) myUnderlay.style.top="25px";
    }, 
    sizeIframe:function(id) {
        if(!id) return;
        var $iframe = dojo.byId(id);
        if (!$iframe) return;
        var $innerDoc = ($iframe.contentDocument) ? $iframe.contentDocument : $iframe.contentWindow.document;
        var iframe_height = $innerDoc.body.scrollHeight + 20;
        var iframe_width = ($iframe.width) ? $iframe.width : $innerDoc.body.width;
        dojo.style($iframe,'height', iframe_height + 'px');
        dojo.style($iframe,'width', iframe_width + 'px');
        dojo.style($iframe,'overflow','hidden');
        dojo.connect($innerDoc,'onclick',function(){
            var $thisHeight = this.body.scrollHeight + 20;
            if($thisHeight != iframe_height) {
                dojo.style($iframe,'height', $thisHeight + 'px');
                return true;
            } 
        });
        return true;
    },
    initIframe:function(id) {
        // Set the ID of the iframe to resize
        iframe_id = id;        
        lastHash = '';
        function checkForMessages(){
            if(location.hash != lastHash){
                lastHash = location.hash;
                var params = lastHash.substring(1).split('&');
                for( var i = 0, l = params.length; i < l; ++i ) {
                  var parts = params[i].split( '=' );
                  switch( parts[0] ) {
                  case 'height':
                    h = parseInt( parts[1] );
                    break;
                  }
                }
                if( typeof( h ) == 'number' ) {
                  lowes.common.sizeIframeHeight(iframe_id,h);    
                }
            }
         }            
        iframe_interval = setInterval(checkForMessages, 200);
    },
    sizeIframeHeight:function(id,h) {
        var $iframe = dojo.byId(id);
        if(!$iframe)return false;
        dojo.style($iframe,'height', h + 'px');
        dojo.style($iframe,'overflow','hidden');
        return true;
    }, 
    stopIframe:function() {
        clearInterval(iframe_interval);
        iframe_id = null;
    },
    setupTopIconTooltip:function(activatorClassSelector, tooltipId) {

        //Variable to store the tooltip; we only want to create one
        //tooltip and attach it to multiple activators
        var tt = null;

        //Loop through all the nodes that should have the tooltip attached
        dojo.query(activatorClassSelector).forEach(function(n){

            //Get the node that contains the tooltip text
            var ttSnippetNode = dojo.byId(tooltipId);

            //If the text exists then continue creating the tooltip
            if (ttSnippetNode) {

                //Override the default onclick event of the activator and show the tooltip instead
                dojo.connect(n, "onclick", function(e){

                    //Only create the tooltip widget if it doesn't already exist
                    //By creating the toolip within the onclick we're only creating it if necessary
                    if (tt == null) {
                        tt = new dijit.TooltipDialog({}, ttSnippetNode);
                        tt.startup();

                        //Create a close button and add it to the tooltip
                        var b = document.createElement("button");
                        b.name="close";
                        tt.containerNode.appendChild(b);

                        //Add functionality to the button to close the toolip when clicked.
                        tt.connect(b, "onclick", function(e){
						dijit.popup.destroy(tt);
                        });
                    }

                    //Open the popup
                    //The orient is setup so it will try to match bottom right of the container with the top right of the tooltip.
                    dijit.popup.open({
                    popup: tt, around: n, orient: {BR:'TR', TR:'BR'} });
                });
            }
        });
    },
    LowesSelectedStore: function(inStoreIndex) {
        // Parses and stores data from a selected store cookie.
        
        // There can be X number of selectedStore cookies.
        // Indicates what selectedStoreX cookie to read.
        this.storeIndex = inStoreIndex;

        // Reads the cookie and sets the object values
        this.load = function() {

            // Set default values
            this.storeName = '';
            this.state     = '';
            this.storeNum  = '';
            this.zip       = '';
            this.distance  = '';
            this.remote    = '';
            this.ld        = '';
            this.address1  = '';
            this.city      = '';
            this.hours     = '';

            // Get the value of the selectedStoreX cookie. The cookie will be in a form like this: 
            //     "Lowe's Of Roeland Park## KS|2588|2|66205|no|N|4960 Roe Boulevard|Roeland Park|M-Sa 6:30-10## Su 8-7";
            var cookieValue = getCookie("selectedStore" + this.storeIndex);

            // Parse the values in the cookie
            if (cookieValue) {
                var valueArray = cookieValue.split('|');
                if (valueArray) {
                    if ( valueArray[0] ) {
                        var nameState = valueArray[0].split('## ');
                        if ( nameState[0] ) { this.storeName = nameState[0]; }
                        if ( nameState[1] ) { this.state = nameState[1]; }
                    }
                    if ( valueArray[1] ) { this.storeNum = valueArray[1]; }
                    if ( valueArray[2] ) { this.distance = valueArray[2]; }
                    if ( valueArray[3] ) { this.zip = valueArray[3]; }
                    if ( valueArray[4] ) { this.remote = valueArray[4]; }
                    if ( valueArray[5] ) { this.ld = valueArray[5]; }
                    if ( valueArray[6] ) { this.address1 = valueArray[6]; }
                    if ( valueArray[7] ) { this.city = valueArray[7].replace(/##/g, ','); }
                    if ( valueArray[8] ) { this.hours = valueArray[8].replace(/##/g, ','); }
                }
            }
        }
    },
    
    getCmExplorerAttributes: function() {
        // Creates the explorer attribute string of variables to pass to Coremetrics
        
        var attributes = '';
        var SEP = '-_-';
 
         // Get the user's select store information if it exists
        var selectedStore1 = new lowes.common.LowesSelectedStore(1);
        selectedStore1.load();

        if (selectedStore1) {
            if (selectedStore1.storeName) {
                attributes += selectedStore1.storeName;
            }
            attributes += SEP;

            if (selectedStore1.state) {
                attributes += selectedStore1.state;
            }
            attributes += SEP;

            if (selectedStore1.storeNum) {
                attributes += selectedStore1.storeNum;
            }
            attributes += SEP;
                
            if (selectedStore1.zip) {
                attributes += selectedStore1.zip;
            }
            attributes += SEP;

            if (selectedStore1.city) {
                attributes += selectedStore1.city;
            }
        }
        else {

            attributes = SEP + SEP + SEP + SEP;
        }
        return attributes;
    },
    getCmRelationship: function() {
    
        var cmRelationship = null;
        if ( window.location.search ) {
            var queryParams = dojo.queryToObject(window.location.search.slice(1));
            // we use slice(1) to strip the leading "?"
            // queryParams is now an object with a key for each GET parameter
            if ( queryParams ) {
                var paramValue = queryParams['cmRelshp'];
                if ( 'req' == paramValue ) {
                    cmRelationship = 'PRODUCT PAGE RECS';
                } else if ( 'rel' == paramValue ) {
                    cmRelationship = 'PDACCESS';
                } else if ( 'sim' == paramValue ) {
                    cmRelationship = 'PDIO1';
                }
            }
        }
        return cmRelationship;
    },
    MiniCartCookie: function() {

        this.quantity = "0";
        this.subTotal = "$0.00";
 
        this.cart = getCookie( "SHOPPINGCART" );
        if ( this.cart ) {
            var values = this.cart.split('|');
            if ( values && values.length == 2 ) {        
                if ( values[0] ) { this.quantity = values[0]; }
                if ( values[1] ) { this.subTotal = values[1]; }
            }    
        }
    
        this.displayText = function() {
            return this.subTotal + ' (' + this.quantity + ' items)';
        }
    }
}
var fpActive = null;
lowes.common.setupDojo(); // needs to be before onload
dojo.addOnLoad(lowes.common.init);

function styleLearnCreate(node) {
    var tabContents = document.getElementById(node);
    var tabCount = tabContents.childNodes.length;
    tabCount -= 1
    var lastTab = tabContents.childNodes[tabCount]
    lastTab.id += "styled-tab";
}

function popWin(url, winName, h, w, x, y, res, scr){ //must pass URL, others are optional
    var name = winName || "",
        ht = h || 600,
        wd = w || 600,
        posX = x || 25,
        posY = y || 25,
        resz = res || "no",
        scrl = scr || "no";

    window.open(url, name, "screenX=" + posX + ", screenY=" + posY + ", height=" + ht + ", width=" + wd + ", resizable=" + resz + ", scrollbars=" + scrl)
}

function show(id) {
    if (document.getElementById(id)) {
    document.getElementById(id).style.display = 'block';
    }
}

function hide(id) {
    if (document.getElementById(id)) {
    document.getElementById(id).style.display = 'none';
    }
}

function showHide(id) {
    if (x=document.getElementById(id)) {
    x.style.display = (x.style.display != 'block')? 'block' : 'none';
    }
}

// this function is called by page LowesIframeTransport.jsp 
// to resize the height of the IFRAME in the View 
// that displays a page from an External Service 
function resizeIframe(vHeight) {
    if (document.getElementById('externalServiceIframe')) {
        dojo.style('externalServiceIframe','height', vHeight + 'px');
    }
}

//** Get/Set Cookies START **//

// name and value are required
// days is optional; only required is setting permament cookie with expiration date
function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
//** Get/Set Cookies END **//

// function to "auto-tab" from one field to the next
// (e.g. useful for phone number fields)
var gen_field_length=0;
var field = null;
function autoTab(obj,event,len,next_field) {
    if (event == "down") {
        gen_field_length=obj.value.length;
        field = obj;
    }
    else if (event == "up") {
        if (obj.value.length != gen_field_length && field == obj) {
            gen_field_length=obj.value.length;
            if (gen_field_length == len) {
                next_field.focus();
            }
        }
    }
}

function addAmt(currTot,shpCost){
    var total = "";
    if(null != currTot && null != shpCost)
    {
        currTot=removeDollar(currTot);
        shpCost=removeDollar(shpCost);
        total=parseFloat(currTot)+parseFloat(shpCost);
        total = "$" + round(parseFloat(total),2);
        total = "$" + formatAmt(total);
    }else
    {
        total = "$"+formatAmt(currTot);
        total = "$" + formatAmt(total);
    }
    return total;
}


function formatAmt(amt){
   if(null != amt){
    if(amt.indexOf("$")!=-1){
        var dolIndx = amt.indexOf("$");
        amt = amt.substring(dolIndx+1,amt.length);
    }
    if(amt.indexOf(".")!=-1){
      if(amt.length>amt.indexOf(".")+3){
          amt = amt.substring(0,amt.indexOf(".")+3);
      }else if(amt.length==amt.indexOf(".")+3){
          amt = amt.substring(0,amt.length);
      }else{
          var lengthDiff = amt.indexOf(".") + 3 - amt.length;
        amt = amt.substring(0,amt.length);
        for (i=0;i<lengthDiff;i++){
            amt = amt + "0";
        }
      }
    }else{
        amt = amt + ".00";
    }
   }
    return amt;
}

function round(rval,rpal) {
    if(null != rval){
    var p = Math.pow(10,rpal);
    rval = rval*p;
    var tmp = Math.round(rval);
    return tmp/p;
 }

}

function removeDollar(str){
    if(null != str){
    if(str.indexOf("$")!=-1){
    var dolIndx = str.indexOf("$");
    str = str.substring(dolIndx+1,str.length);
    }
    return str;
 }

}

function setDfltShpCost(cost){
  if(null != cost){
      cost = "$" + formatAmt(cost);
      document.ShopCartForm.dfltShpCost.value = cost;
  }
} 

function storeUpdate(aForm,storeNumber,address1,address2,city,state,zip) {
    if(null != aForm) {
        aForm.storeNumber.value = storeNumber;
        aForm.address1.value = address1;
        aForm.address2.value = address2;
        aForm.city.value = city;
        aForm.state.value = state;
        aForm.zipCode.value = zip;
        aForm.submit();
    }
}

function chkZipTriger(aKey) {
	var entireZipTrigger = getCookie('zipTrigger');
	var currentSessionId = getCookie('JSESSIONID');
	var showTriger = false;
	if (entireZipTrigger != null){
		var key = entireZipTrigger.indexOf("|");
		var cookedSessId = entireZipTrigger.substring(0, key);
		var trigger = entireZipTrigger.substring(key,entireZipTrigger.length);
		if (currentSessionId == cookedSessId){
		  if (trigger.indexOf(aKey) < 0){
			showTriger = true;
			entireZipTrigger = entireZipTrigger + aKey;
			setCookie("zipTrigger",entireZipTrigger);
		  }
		}
	} else {
		entireZipTrigger = currentSessionId + "|" + aKey;
		setCookie("zipTrigger",entireZipTrigger);
		showTriger = true;
	}
	return showTriger;
}

if(typeof jQuery != "undefined")
{
	/* fix for "null" results message on search page - remove after fixed on back end */
	jQuery.parseQuery = function(qs,options) {
		var q = (typeof qs === 'string'?qs:window.location.search),
			o = {'f':function(v){return unescape(v).replace(/\+/g,' ');}},
			options = (typeof qs === 'object' && typeof options === 'undefined')?qs:options,
			o = jQuery.extend({}, o, options),
			params = {};
		jQuery.each(q.match(/^\??(.*)$/)[1].split('&'),function(i,p){
			p = p.split('=');
			p[1] = o.f(p[1]);
			params[p[0]] = params[p[0]]?((params[p[0]] instanceof Array)?(params[p[0]].push(p[1]),params[p[0]]):[params[p[0]],p[1]]):p[1];
		});
		return params;
	}

	$(document).ready(function() {
		var oneCol = $('#one-column h1'),
			oneColText = oneCol.text(),
			isSearchPage = (oneColText.indexOf("we couldn't find any matches for") >= 0);
		if(isSearchPage) {
			var qString = document.URL.split('?'),
				myqString = $.parseQuery(qString[1]),
				hasNull = (oneCol.text().indexOf('null') >= 0);
				if(hasNull) {
					var newText = oneColText.replace('null', myqString.Ntt);
					oneCol.html(newText);
				}
		}
	});
	/* end fix */
}
