/**
*	Lowe's Masthead:
*	moving global nav timer functions outside of Masthead closure for scoping reasons
*	could be done by Wess.expose(), but with the time we have I'm trying to be quick.
*/

var menuTimeout,
	menuShowTimeout,
	menuTimeoutInterval = 300,
	isNavigating = false,
	disableFlyouts = false;

(function($){
	// Check to see if we have a Lowes namespace, if not create a container object.
	var Lowes = window.Lowes || {};
	//var isHomepage = true;
	// Masthead Namespace
	var Masthead = {
		init: function(options) {
			// When dealing with boolean, option check:
			// Because with the inline || (or) it will always eval incorrectly if option "false" is passed.
			// this.boolOption = (typeof options.boolOption !== undefined)? options.boolOption : true;
			// An example of setting up options

			options = options || {};

			//setting to false will prevent AJAX requests for flyouts
			disableFlyouts = $('#globalMenu').hasClass('narrow');

			// store orig top to restore when tabs change
			$('.corner').data('_origTop', $('.corner').css('top'));

			// Main Nav Buttons
			$("#globalMenu a.trigger").bind({
				mouseenter: function(){
					//Lowes.Masthead.showMainMenu(this);

					clearTimeout( menuTimeout );

					var self = this;

					if(!disableFlyouts && Lowes.Masthead.savingsXml === null)
					{
						Lowes.Masthead.fetchSavingsTab();
					}

					if ( isNavigating === true )
					{
						Lowes.Masthead.showMainMenu(this);

					} else {

						menuTimeout = setTimeout(function(){ Lowes.Masthead.showMainMenu(self); }, menuTimeoutInterval);

					}

				},
				mouseleave: function(){
					//isNavigating = false;
					clearTimeout( menuTimeout );
					menuTimeout = setTimeout(function() { Lowes.Masthead.hideMainMenu(); }, menuTimeoutInterval);
				}
			});

			// Tab Labels in Dropdown
			if (disableFlyouts){ 
				//hide the flyouts
				$('#globalMenu > li .sub-level').addClass('narrow-sub-level');
			}
			
			$('#globalMenu .categories > li > a').bind('mouseenter',function(){
				var $this = $(this);
				clearTimeout(menuTimeout);
				if (isNavigating){
					showMenuItems($this);
				}else{
					menuShowTimeout = setTimeout( function() { showMenuItems($this); } , menuTimeoutInterval );
				}
			}).bind('mouseleave',function(){ clearTimeout(menuShowTimeout); });
		

			$('#globalMenu .sub-level').bind({
				mouseenter: function(){
					isNavigating = true;
					if(menuTimeout != undefined){clearTimeout(menuTimeout);}
				},
				mouseleave: function(){
					isNavigating = false;
					menuTimeout = setTimeout(function() { Lowes.Masthead.hideMainMenu(); }, menuTimeoutInterval);
				}
			});

			$('.aux-nav > li').bind({
				mouseenter: function(){
					$(this).addClass('active');
				},
				mouseleave:function(){
					$(this).removeClass('active');
				}
			});

			$.fn.replaceholder();

		},
		showMainMenu: function(item) {
			this.hideMainMenu();
			//show the active menu, set timeout
			$item = $(item);
			$item.addClass('selected');

			isNavigating = true;
			
			if($item.attr('href')== '#Brands'){
				$('#menu-brands').addClass('visible').css('display','block');
					
			}else{
				$item.next().find('li.first a').trigger('mouseenter');
			}
		},
		hideMainMenu: function() {
			var origTop = $('.corner').data('_origTop');
			$('.corner').hide().css('top', origTop);
			$('.rt-corner').hide().css('top', origTop);
			$('#globalMenu a.selected').removeClass('selected');
			$('#globalMenu .sub-level').removeClass('visible').css('display','none');

			isNavigating = false;

			if ( menuTimeout !== undefined ) { clearTimeout( menuTimeout ); }
		},
		savingsXml: null,
		fetchSavingsTab: function() {
			$.ajax({
				type: "GET",
    			url: "/promos/Promos.xml",
    			dataType: "xml",
    			success:
					function(data, txt, xhr) {
						//parsePromos(data, 'Appliances');
						Lowes.Masthead.savingsXml = data;
					},
				error:
					function(xhr, txt, err) {
						if(typeof console != "undefined")
						{
							console.log('There was an error while fetching the savings: ' + txt);
						}
					},
				complete:
					function(xhr, txt){}
			});
		},
		parsePromos: function(xml, promoCategory, promoCategoryLink, promoCategoryText) {
			var promoSpot1Html = '',
		    	promoSpot2Html = '',
		    	promoDefault1Html = '',
				promoDefault2Html = '',
				promoPanelSidebar = '<div class="grid_4 omega"><div class="promo"> <a name="MASTHEAD_2_shop_new_lower_priced_items" href="/pl_New+Lower+Price_5003258_4294933768_"><img src="/images/promo-rr1.jpg" alt="New Lower Prices" /></a> </div><div class="promo"> <a name="MASTHEAD_2_special_financing_details" href="/cd_Credit+Card+Accounts+from+Lowes_781778798_"><img src="/images/promo-rr2.jpg" alt="Special Financing" /></a> </div><div class="promo third"> <a name="MASTHEAD_2_shop_click_pickup" href="/cd_Shipping+and+Delivery_378641591_#BOPUIS"><img src="/images/promo-rr3.jpg" alt="Shop.Click.Pick Up." /></a> </div></div>';

		    $(xml).find("Promos_Final").each(function() {
		        var $this = $(this),
					promoSpot = $this.find('PromoSpot').text(),
					today = new Date(),
					promoEnd = $this.find('PromoEndDate').text(),
					promoStart = $this.find('PromoStartDate').text();

				promoEnd = promoEnd.substring(promoEnd,promoEnd.indexOf('T')).split('-');
				promoStart = promoStart.substring(promoStart,promoStart.indexOf('T')).split('-');

				$.makeArray(promoEnd);
				$.makeArray(promoStart);

				promoEnd = new Date(promoEnd[0], (promoEnd[1]-1), promoEnd[2], 23, 59, 59);
				promoStart = new Date(promoStart[0], (promoStart[1]-1), promoStart[2], 00, 00, 01);
				
		        if ($this.find(promoCategory).text() == 1 && (promoSpot > 0 && today.valueOf() <= promoEnd.valueOf() && today.valueOf() >= promoStart.valueOf()))  {
		            var promoClass = (promoSpot == 1) ? "alpha" : (promoSpot == 2) ? "omega" : (promoSpot == 3) ? "alpha" : (promoSpot == 4) ? "omega" : "";
					var htmlString = '';

					htmlString += '<div class="grid_3 '+ promoClass +'"><div class="text_promo">';
		            htmlString += '<a class="promo_img" name="MASTHEAD_2_'+promoCategory+'_promo_img" href="' + $this.find("Link1URL").text() + '">';
		            htmlString += '<img height="100" width="100" src="' + $this.find("PromoImgPath").text() + '" alt="' + $this.find("PromoImgAlt").text() + '" /></a>';
		            htmlString += '<h3>' + $this.find("PromoTitle").text() + '</h3>';
		            htmlString += '<p>' + $this.find("ShorDesc").text() + '</p>';
		            htmlString += '<ul class="promo_links">';
		            htmlString += '<li><a name="MASTHEAD_2_'+promoCategory+'_promo_link1" class="more" href="' + $this.find("Link1URL").text() + '">' + $this.find("Link1Text").text() + '</a></li>';

		            if ($this.find("Link2Text").text() != 0){
		                htmlString += '<li><a name="MASTHEAD_2_'+promoCategory+'_promo_link2" class="more" href="' + $this.find("Link2URL").text() + '">' + $this.find("Link2Text").text() + '</a></li>';
		            }
		            if ($this.find("Link3Text").text() != 0){
		                htmlString += '<li><a name="MASTHEAD_2_'+promoCategory+'_promo_link3" class="more" href="' + $this.find("Link3URL").text() + '">' + $this.find("Link3Text").text() + '</a></li>';
		            }

		            htmlString += '</ul></div></div>';

					/* grab promo spots and default HTML, depending on type of promo */

					if(promoSpot == 1 && promoSpot1Html == '') {
						promoSpot1Html = htmlString;
					}

					if(promoSpot == 2 && promoSpot2Html == '') {
						promoSpot2Html = htmlString;
					}

					if(promoSpot == 3 && promoDefault1Html == '') {
						promoDefault1Html = htmlString;
					}

					if(promoSpot == 4 && promoDefault2Html == '') {
						promoDefault2Html = htmlString;
					}
		        }

		    });

			/* if promos are blank, provide defaults */

			if (promoSpot1Html == '')
			{
				promoSpot1Html = promoDefault1Html;
			}

			if (promoSpot2Html == '')
			{
				promoSpot2Html = promoDefault2Html;
			}
			return ('<h2>'+promoCategoryText+'</h2><div class="grid_6">' + promoSpot1Html + promoSpot2Html + '<div class="push_1 grid_4"> <a name="MASTHEAD_2_" href="'+promoCategoryLink+'" class="button"><span>View All Featured Savings</span></a> </div></div>' + promoPanelSidebar);
		}
     };

     // Add Masthead to our Lowes namespace (object).
     Lowes.Masthead = Masthead;
     window.Lowes = Lowes;
})(jQuery);

function showMenuItems(thisItem){
	isNavigating = false;

	var $parent = thisItem.parent(),
		ppos = $parent.position(),
		pposTop,
		finalHtml,
		$submenuDiv = thisItem.parent().parent().parent(),
		triggerHref = $submenuDiv.prev('.trigger').attr('href'),
		thisRel = thisItem.attr('rel'),
		thisLink = thisItem.attr('href'),
		thisText = thisItem.text();

	pposTop = ($parent.hasClass('first')) ? ppos.top : ppos.top-1;
	if (pposTop <= 0)
		pposTop = $('.corner').css('top');
	if ((triggerHref == '#HomeIdeas' || triggerHref == '#HelpCenter') &&
		parseInt(pposTop) < 32) {
		pposTop = 32;
	}

	$('.corner').show().css({top: (pposTop)});
	if(!$parent.hasClass('holiday-nav'))
	{
		$('.rt-corner').show().css({top: (pposTop)});
	}

	//check for flyout container
	if(thisItem.next('.menu_container').length < 1)
	{
		//append flyout container if it doesn't exist
		thisItem.after($('<div class="menu_container menu-content"></div>'));
	}

	//grab flyout container
	var menuContainer = thisItem.next('.menu_container');

	//content exists, make sure other content at this level is hidden
	$parent.siblings().find('.menu_container').css({ 'z-index':100 });

	if(!disableFlyouts)
	{
		//check to see if flyout has content
		if(menuContainer.hasClass('fetched'))
		{
			//show this one
			menuContainer.css({ 'z-index':1000 });
		}
		else
		{
			//if in Savings tab, load data from savingsTab object
			if(triggerHref == '#Savings')
			{
				var promosHtml = Lowes.Masthead.parsePromos(Lowes.Masthead.savingsXml, thisRel, thisLink, thisText);
				menuContainer.append(promosHtml).addClass('fetched').css({ 'z-index':1000 });
			}
			else
			{
				//content does not exist, fetch it; add class and bring to front after ajax load
				menuContainer.load( thisRel, function(response, status, xhr) {
		  				if(status != "error")
						{
			    			$(this).addClass('fetched').css({ 'z-index':1000 });
			  			}
				});
			}
		}
	}
	$submenuDiv.addClass('visible').show();
}

(function($) {
	$.fn.replaceholder = function(options) {
		settings = jQuery.extend({
			focusColor: '#000',
			blurColor: '#aaa'
		}, options);
		var $placeholder;
		(this.length > 0) ? $this = $(this) : $this = $('input[placeholder]');
		return $this.each(function() {
			var $placeholder = $(this);
			if ( $placeholder.length > 0 ) {
				var attrPh = $placeholder.attr('placeholder');
				$placeholder.attr('value', attrPh).css('color', settings.blurColor).bind('focus', function() {
					var $this = $(this);
					if ($this.val() === attrPh) {
						$this.val('').css('color', settings.focusColor);
					}
				}).bind('blur', function() {
					var $this = $(this);
					if ($this.val() === '') {
						$this.val(attrPh).css('color', settings.blurColor);
					}
				});
			}
		});
	};
})(jQuery);

// Login modal - displays on click of Account links
function displayURL(url, displayNav, params) {
	if (!$('#dialog_login').length){
		$('body').append('<div href="LogonFormNavIframe?langId=-1&amp;storeId=10151&amp;catalogId=10051&amp;URL=StoreCatalogDisplay" id="dialog_login"></div>');
	}
	
	if (!$('#dialog_login').length){
		$('body').append('<div id="dialog_login"></div>');
	}


	var scheme = location.protocol,
		$dialog_login = $('#dialog_login'),
		logonFormNavURL;
		
	if (displayNav == "true")
	{
		logonFormNavURL = (scheme == 'http:') ? "LogonFormNavIframe": "LogonFormNavIframeS";
		if (url != "")
		{
			if (params) params = params + "&URL=" + escape(url);
			else params = "?URL=" + escape(url);
		}
		
		// Don't add the iFrame more than once.		
		if ( $('#login_layer').length === 0 ) 
		{
			$dialog_login.load($dialog_login.attr('href'));
			if ( typeof console !== 'undefined' ) console.log($dialog_login.attr('href'));
		}
		
		$dialog_login.dialog({
			autoOpen: false,
			draggable: false,
			dialogClass: 'modal',
			height: 530,
			modal: true,
			resizable: false,
			width: 640,
			zIndex: 1000
		});
		
		$dialog_login.dialog('open');
		
    } else {
        window.location = url;
    }
}


/* Original Masthead Functions */
var guestReg,
	thisStoreID,
	thisLangID,
	thisCatID,
	thisRedirectURLAfterLogon,
	vCurrent = 0,
	vTotal = 1,
	vDuration = 5000,
	intInterval = 0,
	vTmp = 24;
//=============================================
$(document).ready(function(){
						   
	/* if kiosk hide weekly ad link */
	if(Lowes.Cookie.get('storeKiosk')){$('.aux-nav .first').css('display','none');}
	/* end kiosk */
	
	checkStylesheetMedia();

	zippedStatus=0;
	/* isHomepage=true; */
	Lowes.Masthead.init();

	if(typeof mastConfig != "undefined"){
		guestReg = mastConfig.registerType;
		thisStoreID = mastConfig.storeId;
		thisLangID = mastConfig.langId;
		thisCatID = mastConfig.catalogId;
	} else {
		guestReg = 'G';
		thisStoreID = '10151';
		thisLangID = '-1';
		thisCatID = '10051';
	}
	
    thisRedirectURLAfterLogon = (typeof(URLAfterLogon) == "undefined") ? 'TopCategoriesDisplayView' : encodeURL(URLAfterLogon);

	if($.browser.msie){
		setTimeout(chkStoreCookies,500);
		setTimeout(getCartInfo,500);
	} else {
		chkStoreCookies();
		getCartInfo();
	}
	
	setMyAccountLinks();
	getWelcomeInfo();

	/* set date/time for print view */
	if($('#stamps')){
		var curTime;
		var curDate;
		var todaysDateTime = new Date();
		var curHour = todaysDateTime.getHours();
		var curMin = todaysDateTime.getMinutes();
		var month = todaysDateTime.getMonth()+1;
		var year = todaysDateTime.getYear();
		var day = todaysDateTime.getDate();
		var curAMPM;

		if (curHour >= 12){
			curHour -= 12;
			curAMPM = " PM";
		} else {
			curAMPM = " AM";
		}
		if (curHour == 0) {
			curHour = 12;
		}
		curTime = curHour + ":"+ ((curMin < 10) ? "0" : "") + curMin + curAMPM;
		if(day<10) {
			day = "0" + day;
		}
		if(month<10) {
			month= "0" + month;
		}
		if(year<1000) {
			year+=1900;
		}
		curDate = month+'/'+day+'/'+year;
		$('#stamps p:first').html('Printed on  '+ curDate + ' at ' + curTime);
	}
	
	cartFix(); /* Removing additional .last from the <tr>'s */

	setupEmailModal();
	setupBadgeModal();
	fixWinSafMastButton();
});

function fnLoop(){
	( vCurrent === vTotal ) ? vCurrent = 0 : vCurrent++;
	$("#banner_object").find(".banner_slide").each(function(i) { 
		vPos = $(this).position();
		vTmp = vPos.top + 24;
		$(this).animate({"top": vTmp+"px"});
		if ( vTmp === "24" )
		{
			vTmp = (vTmp - ((vTotal+1) * 24));
			$(this).animate({"top": vTmp+"px"}, 0);
		}
	});
}

function cartFix() {
	// This function should be removed once cart issue is addressed
	var $items = $('#my-cart-contents tbody tr');

	$items.each(function(i, item) {
		var $item = $(item);

		// If the item already has a class of last
		if ( $item.hasClass('last') ) {
			// If the item is not the last item
			if ( (i + 1) !== $items.length ) {
				// Remove the .last class
				$item.removeClass('last');
			}
		} else {
			// If it is the last item
			if ( (i + 1) === $items.length ) {
				// Add the class
				$item.addClass('last');
			}
		}
	});
}

function checkStylesheetMedia() {
	var currentURL = document.location.href;
	if(currentURL.indexOf('productId') != -1 || currentURL.indexOf('/pl_') != -1) {
		$('link[href*="main.css"]').each(function(i,lnk){
			$(lnk).attr('media','screen');
		});
	}
	if(currentURL.indexOf('StoreLocatorDisplayView') != -1) {
		$('link[href*="main.css"]').attr('media','screen');
		$('head').append('<link charset="utf-8" media="print" type="text/css" href="/wcsstore/B2BDirectStorefrontAssetStore/css/print.css" rel="stylesheet">');
	}
}

function encodeURL(strURL){
	// enconde the char '?'
	var result = strURL.replace('?', '%3F');
	// enconde all chars '&'
	result = result.replace(/&/g, '%26');
	// enconde all chars '='
	result = result.replace(/=/g, '%3D');
	return result;
}


//=============================================
function setMyAccountLinks()
{	
	// The logic is backwards, false means "do not show modal".
	var linkBool = ( Lowes.Cookie.get('firstName') ) ? false : true;
	//linkBool = ( guestReg == 'G' ) ? 'true' : 'false';

	//mylowes functionality
	if($('#myAccountTopNav').length > 0)
	{
		// Hide Home Profile Based on Cookie Segment.
		(Lowes.User.isHomeProfileUser() ? $('#nav-home-profile').show() : $('#nav-home-profile').hide() );
		
		
		$('#nav-my-account').attr('href','UserAccountLanding?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID+'&state=P');
		$('#nav-my-profile').attr('href','UserProfileCmd?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID+'&state=P');
		/*Added to display Order History when user is logged in and Find Orders in other case*/
		if ( !linkBool )
		{
			/* Logged in user */
			$('#nav-my-order').attr('href','LowesOnLinePurchaseHistory?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID);
		}
		else
		{
			/* Annon User */
			$('#nav-my-order').attr('href','LowesFindOrders?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID);
		}
		/*End of Added to display*/
		$('#nav-my-subscriptions').attr('href','UserSubscriptionView?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID);
		$('#nav-favorites').attr('href', 'FavoritesListCmd?pageNo=1&pageView=Favorites&langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID);
		$('#nav-my-reminders').attr('href','RemindersListCmd?pageNo=1&pageView=ReminderListPage&langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID);
		$('#nav-my-rebates').attr('href','MyRebatesDisplayView?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID);
		//$('#nav-my-credit-center').attr('href','javascript:displayURL(\'MyCreditCenterDisplayView?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID+'\',\''+linkBool+'\')');
		//$('#nav-my-credit-center').attr({'href':'https://credit.lowes.com','target':'_blank'});
		$('#nav-my-library').attr('href','MyProjectsDisplayView?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID);
		//$('#nav-my-projects').attr('href', 'javascript:displayURL(\'MyProjectsDisplayView?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID+'\',\''+linkBool+'\')');
	}
}
//=============================================



function getCartInfo(){
	
	var $masthead_content = $('#masthead_content'),
		$cart_total = $masthead_content.find('.cart-total');
	
	if ( $cart_total.length > 0 ) 
	{
		if ( Lowes.Cookie.get('SHOPPINGCART') )
		{
			var cartInfo = Lowes.Cookie.get('SHOPPINGCART').split('|');
			var items = cartInfo[0];
			var total = cartInfo[1];
			$cart_total.text(total +' ('+items+' items)');
		} 
		else
		{
			// Set this val by default...in the HTML
			$cart_total.text('$0.00 (0 items)');
		}
		$('#myAccountTopNav').find('.my-orders').attr('href','OrderStatusDisplay?storeId='+thisStoreID+'&catalogId='+thisCatID);
		$masthead_content.find('.my-cart').attr('href','OrderItemDisplay?storeId='+thisStoreID+'&catalogId='+thisCatID);
		$masthead_content.find('.checkout').attr('href','CheckoutLinkRouting?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID);
	}
}
//=============================================

// @name isUserSignedIn
// @author NP
// @desc isUserSignedIn return if user is logged in or not, 
// by checking one cookie fireName is found or not found.
// @example if (isUserSignedIn()) { alert('User is logged in!'); }
function isUserSignedIn(){   	 
	return !!Lowes.Cookie.get('firstName');
};
 
  

function acctLogOff(){
	Lowes.Cookie.del('firstName');
}

//=============================================
/*
// @name getWelcomeInfo
// @author NP, legacy
// @desc Update welcome text in masthead based on login status, can  be called once or many times.
// @example isUserSignedIn();
*/
function getWelcomeInfo(){    
    var $salutation = $('#salutation');
    
	// Scope function clear 2 cookies
    function resetCookiesWelcome(){
        document.cookie = 'invalidUserSegment=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/';
        document.cookie = 'userSegment=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/';
    }

    if( $salutation ) { 
    /* #masthead #top-nav */
        var welcomeMsg, userStatus, userURL, acctStatus, acctURL, catDisplayURL, msgLabels,busName;
        
        // Define labels text
        msgLabels = { 
            signIn : 'Sign In',
            signUp : 'Sign Up',
            signOut : 'Sign Out',
            defWelcome : 'Welcome to Lowe\'s',
            welcomeUser: 'Welcome, ',
            employee: '(Employee)',
            realtor: '(Realtor)'
        };
        
        // resize width welcome to.. area. TODO: move into HTML
        $('.welcomeMessage').addClass('grid_5').removeClass('grid_3'); 
        
		// Default Welcome
        welcomeMsg = msgLabels.defWelcome;            
        acctStatus =  msgLabels.signUp;
        acctURL = '/webapp/wcs/stores/servlet/UserRegistrationForm?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID+'&new=Y&URL='+catDisplayURL;

        catDisplayURL = ( !thisRedirectURLAfterLogon ) ? 'TopCategoriesDisplayView' : thisRedirectURLAfterLogon;
            
        //check to see if the firstName cookie exists and if user is Signed in
        if ( Lowes.Cookie.get('firstName') && isUserSignedIn() ) {
            var custName,
            	custFirstName = Lowes.Cookie.get('firstName');
            
            // Check CBC account name
            if (Lowes.Cookie.get('memberGroup')) {
				busName = $.parseJSON( Lowes.Cookie.get('memberGroup') )['businessName'];
			    // found business name, replace customer name with bus name.
			    if (busName){
			     	custName = busName;
			     	custFirstName = busName;
			    }
			}
		
            // Trim custName if too long. else this will cause layout issues
            custName = ( custFirstName.length >= 16 ) ? $.trim(custFirstName.substring(0,16)) + '...' : custFirstName;
            acctStatus =  msgLabels.signUp;
            acctURL = '/webapp/wcs/stores/servlet/UserRegistrationForm?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID+'&new=Y&URL='+catDisplayURL;

            //check to see if the employee cookie is set
            welcomeMsg = msgLabels.welcomeUser + custName;

			// Check type of user Employee or Relator or Default Normal.
            if (Lowes.Cookie.get('userSegment') === 'Employee'){
                if (!Lowes.Cookie.get('invalidUserSegment')){
                    welcomeMsg += ' <span class="user-type">'+ msgLabels.employee +'</span>';
                } else {
                    // this is an invalid user segment cookie, remove the 2 cookies
                    resetCookiesWelcome();
                }
            } else if (Lowes.Cookie.get('userSegment') === 'Realtor'){
                if (Lowes.Cookie.get('invalidUserSegment') != 'true'){
                    welcomeMsg += ' <span class="user-type">'+ msgLabels.realtor +'</span>';
                }else{
                    // this is an invalid user segment cookie, remove the 2 cookies
                    resetCookiesWelcome();
                }
            } 
        } 
        
        // determine if the user is logged in, use signout or signin text+link
        if(isUserSignedIn() ){
            userStatus = msgLabels.signOut;
            userURL = '/webapp/wcs/stores/servlet/Logoff?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID+'&URL=TopCategoriesDisplayView' + (Lowes.Cookie.get('rememberMe') == 'true' ? '&rememberMe=true' : '');
        } else {
	        $salutation.find('#user-status').addClass('signInModal');
            userStatus = msgLabels.signIn;
            userURL = '/webapp/wcs/stores/servlet/LogonForm?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID+'&URL='+catDisplayURL;
        }

        // TODO: move into HTML .after account-status-link
        $salutation.find('.welcome').html(welcomeMsg).end()
                    .find('a#account-status').html(acctStatus).attr('href',acctURL).end()
                    .find('#user-status').html(userStatus).attr('href',userURL).bind('click', function(){
                    	if(isUserSignedIn() ){
                    		acctLogOff();
                    	};
                    }).end()
                    .find('#user-status').after(  $salutation.find('#account-status').show() );  // Reposition link    
  
        $('.welcomehead-extra').remove();

        // If showing signout link, hide 2nd link
        if (userStatus ==  msgLabels.signOut){
            $salutation.find('a#account-status').hide();
        } else {
            // if showing two links add OR text, TODO: move into HTML
            $salutation.find('a#account-status').before( $('<span class="welcomehead-extra"> or </span>') );
        }
        
        $salutation.show();
        $('.accountStatus').hide(); // area not needed. TODO: move into HTML
    }
}

//=============================================
function chkStoreZIP(cookie) {
	if(Lowes.Cookie.get(cookie)) {

		var cookie_info = Lowes.Cookie.get(cookie);
		var cookie_array = cookie_info.split('|');

		/* 12944 - Fixes Store Hours Formatting */
		cookie_array[8] = cookie_array[8].replace('\##', ',').replace(/am/gi, 'a.m.').replace(/pm/gi, 'p.m.');

		store_name = cookie_array[0];
		store_number = cookie_array[1];
		distance_to_store = cookie_array[2]; // in miles
		store_zip = cookie_array[3];
		remote_store = cookie_array[4];
		local_delivery = cookie_array[5];
		store_address = cookie_array[6];
		store_city = cookie_array[7];
		store_hours = cookie_array[8];
		store_phone = cookie_array[9];
		store_fax = cookie_array[10];

		return cookie_array;
	}
}

function mustRefreshStoreList(){
	var vStoreName = $('#my-store .current-location').attr('title');
	var storeHasChanged = (vStoreName != store_name.replace("##", ","));
	
	var storeList = $('#additional-stores li').length;

	return (storeHasChanged || storeList >= 0);
}

//=============================================
function setStoreListInfo(aStoreList) {
	var i = 2,
		lastItem,
		$additionalStores;
	
	/* Clear the actual additional stores info */
	$('#additional-stores li').each(function(i){
		if ($(this).hasClass("last")) {
			lastItem = $(this).html();
		}
		//$(this).empty();
	});
	//	$('#masthead #my-store-change-store .content ul#additional-stores').empty();

	dojo.forEach(aStoreList, function(store){
		if (selectedStoreNumber != store['storeNumber']) {
			setStoreInfo(store, i);
			i++;
		}
	});
	i = 0;
	
	$('#additional-stores').append('<li><a href="StoreLocatorDisplayView?storeId=10151&catalogId=10051">Enter A New Zip Code</a></li>');
	/* added to remove the first store */
	$('#additional-stores li:first').remove();
	/* end remove first store*/
	$('#additional-stores li:last').addClass('last');

	$('#additional-stores').append(lastItem);
	$('#additional-stores').append('</li>');


	$('#my-store-change-store .content a.more-info-link').each(function(i){
		$(this).bind('click',function(){
			var storeInfoUL = $(this).attr('id') + 'Info';
			if (storeInfoUL != 'selectedStore1Info') {
				if($('#my-store-change-store .content ul#'+storeInfoUL).hasClass('hidden')){
					$('#my-store-change-store .content ul#'+storeInfoUL).removeClass('hidden');
					$(this).text('Hide');
				} else {
					$('#my-store-change-store .content ul#'+storeInfoUL).addClass('hidden');
					$(this).text('More Info');
				}
			}
		});
	});

}
function setStoreInfo(aStore, aIndex) {
	var more_info_link = ''; /*'MastHeadStoreInfoView?storeId='+thisStoreID+'&catalogId='+thisCatID+'&selectedStoreNumber='+chkStoreZIP(this)[1];*/
	var thisStoreInfo =
		'<li>Store Number: '+aStore['storeNumber']+'</li>'+
		'<li>'+aStore['addressLine1']+'</li>'+
		'<li>'+getStoreCityAndState(aStore['storeName'], aStore['city'])+' '+aStore['zipCode']+'</li>'+
		'<li>Phone: '+aStore['phoneNumber']+'</li>'+
		'<li>Fax: '+aStore['faxNumber']+'</li>';
		'<li>Hours: '+aStore['storeHours'].replace(/##/g, ',') +'</li>';

	$('#my-store-change-store .content ul#additional-stores').append(
		'<li><div class="col-a">'+aStore['storeName'].replace('\##', ',') +
		'<br />('+aStore['distance']+' miles) <a id="selectedStore'+aIndex+'" class="more-info-link" href="#'+more_info_link+'">More Info</a><div>'+
		'<ul id="selectedStore'+aIndex+'Info" class="hidden">'+thisStoreInfo+'</ul></div></div>'+
		'<div class="col-b">'+
		'<a href="javascript:storeUpdate(document.storeUpdateForm,\''+
		    aStore['storeNumber']+'\',\''+aStore['addressLine1']+'\',\'\',\''+
		    aStore['city']+'\',\'\',\''+aStore['zipCode']+'\');" class="button-grey"><span>Shop This Store</span></a></div></li>');
}
//=============================================
var selectedStoreNumber;
//=======	End Updated Change ================
//=============================================
function chkStoreCookies() {
	//----------------------------
	var cookies = ['selectedStore1'];
	var storeChangeTimeOut;
	var storeInfoTimeOut;
	//---------------------------
	$(cookies).each(function(i){
		if(Lowes.Cookie.get(this)){
			var arr_storeInfo = chkStoreZIP(this);
			var thisStoreInfo = '<ul><li>Store Number: '+arr_storeInfo[1]+'</li><li>'+arr_storeInfo[6]+'</li><li>'+getStoreCityAndState(arr_storeInfo[0], arr_storeInfo[7])+' '+arr_storeInfo[3]+'</li><li>Phone: '+arr_storeInfo[9]+'</li><li>Fax: '+arr_storeInfo[10]+'</li><li>Hours: '+arr_storeInfo[8].replace(/##/g, ',')+'</li></ul>';
			var more_info_link = ''; /*'MastHeadStoreInfoView?storeId='+thisStoreID+'&catalogId='+thisCatID+'&selectedStoreNumber='+chkStoreZIP(this)[1];*/
			// if the first store, populate the my-store link
			if(i == 0){
				//add store id to weekly ad link
				if($('.weekly-ad').length > 0){
					$('.weekly-ad').attr('href','http://lowes.shoplocal.com/lowes/default.aspx?action=entryflash&storeref='+arr_storeInfo[1]);
				}
				//store info for print mast
				if($('#header-block #print-masthead #my-store-info')){
					$('#header-block #print-masthead #my-store-info').html(arr_storeInfo[0].replace('\##', ',')+'<br />Store Number: '+arr_storeInfo[1]+'<br />'+arr_storeInfo[6]+'<br />'+arr_storeInfo[7].replace('\##', ',')+' '+arr_storeInfo[3]+'<br />Phone: '+arr_storeInfo[9]+'<br />Hours: '+arr_storeInfo[8].replace(/##/g, ','));
				}
				/*AUTOZIP PANEL*/ $('#page1 .pg1_left #pref_location').append('<ul class="pref_loc"><li>'+arr_storeInfo[0].replace('\##', ',') + '</li><li>'+arr_storeInfo[6]+'</li><li>'+getStoreCityAndState(arr_storeInfo[0], arr_storeInfo[7])+' '+arr_storeInfo[3]+'</li></ul>');	 

				$('#my-store-more-info .current-store').append(arr_storeInfo[0].replace('\##', ','));
				$('#current-store-info').append(thisStoreInfo);
				$('#current-store-detail').attr('href','/StoreLocatorDisplayView?storeId='+thisStoreID+'&catalogId='+thisCatID+'&site='+arr_storeInfo[1]); /* #my-store-more-info .content:last p a */
				$('#my-store-change-store .content .current-store .col-a').append(arr_storeInfo[0].replace('\##', ',') + '<br />('+arr_storeInfo[2]+' miles) <a id="'+this+'" class="more-info-link" href="#'+more_info_link+'">More Info</a><div><ul id="'+this+'Info" class="hidden">'+thisStoreInfo+'</ul></div>');
				$('#my-store .current-location').append(arr_storeInfo[0].replace('\##', ',')).attr('title',arr_storeInfo[0].replace('\##', ','));
				$('#masthead-store-info').bind('click',function(){
					var position = $(this).position();
					var left = position.left + ($(this).width()/2) - 187;
					$('#my-store-more-info').css({ 'right': 'auto', 'left': left }).show();
					storeInfoTimeOut = setTimeout(function(){
						$('#my-store-more-info').hide();
					},5000);
					$('#my-store-change-store').hide();
				});
			} else {
				$('#additional-stores').append('<ul><li><div class="col-a">'+arr_storeInfo[0].replace('\##', ',') + '<br />('+arr_storeInfo[2]+' miles) <a id="'+this+'" class="more-info-link" href="#'+more_info_link+'">More Info</a><div><ul id="'+this+'Info" class="hidden">'+thisStoreInfo+'</ul></div></div><div class="col-b"><a href="javascript:storeUpdate(document.storeUpdateForm,\''+arr_storeInfo[1]+'\',\''+arr_storeInfo[6]+'\',\'\',\''+arr_storeInfo[7]+'\',\'\',\''+arr_storeInfo[3]+'\');" class="button-grey"><span>Shop This Store</span></a></div></li></ul>');
			}
		}
	});
	//-------------------------
	$('#my-store-change-store .content a.more-info-link').each(function(i){
		$(this).bind('click',function(){
			var storeInfoUL = $(this).attr('id') + 'Info';
			if($('#my-store-change-store .content ul#'+storeInfoUL).hasClass('hidden')){
				$('#my-store-change-store .content ul#'+storeInfoUL).removeClass('hidden');
				$(this).text('Hide');
			} else {
				$('#my-store-change-store .content ul#'+storeInfoUL).addClass('hidden');
				$(this).text('More Info');
			}
		});
	});
	//--------------------------
	$('#change-store-options').bind('click',function(){
			storeChangeTimeOut = setTimeout(function(){
				$('#my-store-change-store').hide();
			},5000);
			$('#my-store-change-store').show();
			$('#my-store-more-info').hide();
	});
	//--------------------------
	$('#my-store-change-store .topper a.close').bind('click',function(){
			$('#my-store-change-store').hide();
	});
	//--------------------------
	$('#my-store-more-info .topper a.close').bind('click',function(){
			$('#my-store-more-info').hide();
	});
	//--------------------------
	$('#my-store-more-info').bind('mouseenter',function(){
			clearTimeout(storeInfoTimeOut);
	}).bind('mouseleave',function(){
			storeInfoTimeOut  = setTimeout(function(){
			$(this).hide();
		},1000);
	});
	//---------------------------
	$('#my-store-change-store').bind('mouseenter',function(){
			clearTimeout(storeChangeTimeOut);
	}).bind('mouseleave',function(){
			storeChangeTimeOut = setTimeout(function(){
			$(this).hide();
		},1000);
	});
	//----------------------------
	if(Lowes.Cookie.get('selectedStore1')){
		$('#my-store').show();
		$('#masthead_masthead_storeLocation').hide();
	}else{
		$('#masthead_storeLocation').show();
		$('#masthead_storeLocation form#storeSearchForm #findMyStore').bind('click',function(){
			document.storeSearchForm.submit();
		});
	}
	//-----------------------------
}

//================================================
function refreshMHStoreInfo() {
      $('#additional-stores').empty();
      $('#my-store-more-info .current-store').empty();
      $('#current-store-info').empty();
      $('#my-store-change-store .content .current-store .col-a').empty();
      $('#my-store .current-location').empty();
      chkStoreCookies();
}
//================================================
function getStoreCityAndState(storeName, storeCity) {
	if(storeName.indexOf('\##') > -1) {
		vResult = storeCity + ', ' + storeName.split('\##')[1];
	} else {
		vResult = storeCity;
	}
	return vResult;
}
/*===================*/
function check_neg() {
	var obj = $('#giftcard-value');    /* Sets the 'obj' variable to the ID 'giftcard-value' */
	var value = parseInt($(obj).val());   /* Checks the value of the input field and turns it into a number */
	if(value<0) {        /* If that value is less than zero */
		value = value * -1;      /* Make that negative number positive number */
		$(obj).val(value);      /* Replace the value of the form field so the user will see it */
	}
}

function submit_gc_form() {
	var gc_msg = $('#gift-msg-txtarea').val(); /* Get the value of the textarea */
	var len = gc_msg.length;     /* Find that textareas text length */
	g_msg = gc_msg.replace(/[\n\r]+/g,'');  /* Regular Expression to find all spaces on a new line ... not functioning */
	if(len > 255) {        /* If greater than 255, shorten the message to 255 characters */
		gc_msg = gc_msg.substring(0,255);
	}
	check_neg();        /* Run the check_neg function */
	document.giftCardForm.submit();    /* Submit the form */
}

function removeClick() {
	var obj = $('#giftCardForm img');   /* Find the submit button image */
	var curr_btn = {
		width : obj.attr('width'),    /* Then find it's properties */
		height : obj.attr('height'),
		alt : obj.attr('alt'),
		src: obj.attr('src')
	};

	var new_btn = $('img')     /* Create a new button */
		.attr('src', 'http://www.lowes.com'+curr_btn.src)    /* Set the attributes to match the old button minus the onclick event */
		.attr('alt', curr_btn.alt)
		.bind('click', submit_gc_form);   /* Bind our own click event to run the submit_gc_form function */
	
	obj.replaceWith($(new_btn));    /* Replace the old object with the new object */
}

function setupEmailModal() {
	var $emailModal = $('#cm_email_modal').dialog({
		modal:true,
		dialogClass:'cm_email_dialog',
		autoOpen: false,
		resizable: false,
		draggable: false,
		width:620,
		height:280
	});
	$emailModal.attr('id', 'cm_email_dialog');

	$('#cm_email_trigger, .cm_email_trigger').click(function(e) {
		e.preventDefault();
		$emailModal.dialog('open');
		$('#cm_email_dialog .email_modal_content iframe').attr('src', 'http://pages.s4.exacttarget.com/lowes/quicksignup/');
	});
}

function setupBadgeModal() {
	/* These modals are the bottom three badges. The middle and right badge need to open a modal. */
	var $standard_modal = $('#standard_modal');

	if ( $standard_modal.length === 0 )
	{
		$standard_modal = $('<div/>', {
			'id': 'standard_modal'
		}).appendTo('#container');
	}

	$standard_modal.dialog({
		modal:true,
		dialogClass:'modal',
		autoOpen: false,
		resizable: false,
		draggable: false,
		width:500,
		height:230
	});

	$('#footer').find('.badgeList .footer_min').bind('click', function(e)
	{
		var $this = $(this),
			title = $this.attr('title');	

		if ( $this.attr('id') === 'pledge' || $this.attr('id') === 'security' )
		{
			e.preventDefault();
		
			$standard_modal.load($this.data('load'), function(){
				$standard_modal.dialog("option", "title", title).dialog('open');
			});
		}
	});
}

function fixWinSafMastButton()
{
	if (navigator.appVersion.indexOf("Win") != -1)
	{
		var strBrowserInfo = navigator.userAgent.toLowerCase();
		
		/* If Browser is Safari or Chrome */
		if (/webkit/.test(strBrowserInfo))
		{
			var $objMastBtns = $("#find_a_store_btn, #mainSearch");	
			var strDocTypeInfo = document.doctype.systemId;
			
			/* If its Safari */
			if (!/chrome/.test(strBrowserInfo))
			{
				$objMastBtns.css("padding-right", "8px !important");					
				$("#search .search_form").css("width", "250px");
				
				/* If the Page's DocType is Strict, Fix the Padding Differently Than Transitional */
				if (strDocTypeInfo.indexOf("strict") > -1)
				{
					$("span", $objMastBtns).css("top", "-2px");
				}
				else if (strDocTypeInfo.indexOf("transitional") > -1)
				{
					$("span", $objMastBtns).css("top", "-1px");
				}
			}
			else if (strDocTypeInfo.indexOf("transitional") > -1)
			{
				/* If the Chrome and Page's DocType is Transitional */
				$("span", $objMastBtns).css("top", "0");
			}
		}
	}
}

function lowesSelectedStore(inStoreIndex) {
	
	var storeName, state, storeNum, zip, distance, remote, ld, address1, city, hours,
		cookieValue = readCookie('selectedStore' + inStoreIndex);
	
	if ( cookieValue )
	{
		var valueArray = cookieValue.split('|');
		
		if ( valueArray ) 
		{
			if ( valueArray[0] )
			{
				var nameState = valueArray[0].split('## ');

				if ( nameState[0] )
				{
					storeName = nameState[0];
				}
				if (nameState[1]) {
					state = nameState[1];
				}
			}
			if (valueArray[1]) {
				storeNum = valueArray[1];
			}
			if (valueArray[2]) {
				distance = valueArray[2];
			}
			if (valueArray[3]) {
				zip = valueArray[3];
			}
			if (valueArray[4]) {
				remote = valueArray[4];
			}
			if (valueArray[5]) {
				ld = valueArray[5];
			}
			if (valueArray[6]) {
				address1 = valueArray[6];
			}
			if (valueArray[7]) {
				city = valueArray[7].replace(/##/g, ',');
			}
			if (valueArray[8]) {
				hours = valueArray[8].replace(/##/g, ',');
			}
		}
	}
	
	return {
		storeName: storeName, 
		state: state,
		storeNum: storeNum, 
		zip: zip, 
		distance: distance, 
		remote: remote, 
		ld: ld, 
		address1: address1, 
		city: city, 
		hours: hours
	};
}

function getCmExplorerAttributes()
{
	var attributes = '',
		SEP = '-_-';
		
	var selectedStore1 = lowesSelectedStore(1);
	
	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;
}


/*AUTOZIP PANEL*/
$(function() { 
  if ("http:" == document.location.protocol) {
		if(Lowes.Cookie.get('autozipConfirm') && Lowes.Cookie.get('selectedStore1')){  
			$("#autozip_container").hide();
		} else if(Lowes.Cookie.get('selectedStore1') && Lowes.Cookie.get('autozip')) {
			setTimeout ( "showWindow()", 2000 );	
		}
	} else {
		return false;
	}
});

function showWindow() { $("#autozip_container").slideDown(1000); }
function createZipCookie() { createCookie('autozipConfirm', 'true', 30); }

$(function() { 
 	var container = $("#autozip_container");

	/*if user Advanced Search link, the cookie is set*/
	/*or enter zip and click submit to close window, set cookie and shop*/
	$('.find_store_txt a.learn-more, .find_store, #my-store a#change-current-store').bind('click',function(event){
			createZipCookie();
	});
	
	/*if user hits the enter key to submit, the cookie is set*/
	$('input#autozipCode').bind('keypress', function(e) {
		if(e.keyCode==13){
			createZipCookie();
		}
	});
	
	/*Click yes to close window set cookie and shop*/
	/*or click Ignore and close panel / set panel cookie*/
	$('a#shop, a span.close').bind('click',function(event){
			event.preventDefault();
			container.slideUp(1000);
			createZipCookie();
	});
			
	/*show/hide why link content*/
	$("#why").bind('click',function(event){
			event.preventDefault();
			$('.why_txt').fadeIn("slow");
		});
	$('#why').mouseout(function() {
			$('.why_txt').fadeOut("slow");
		});
});

/* Code needed to append store info to print block until masthead goes dynamic */
$(document).ready(function(){

    var myStoreHeader = $('#my-store-more-info').find('.current-store').text();
	var myStore = $('#current-store-info ul li');
	var printText = "<div class='print-container'><h5>" + myStoreHeader + "</h5><ul>" + 
				 	"<li class='address'>" + myStore.eq(1).text() + "</li>" +
					"<li class='phone'>" + myStore.eq(3).text() + "</li>" +
				 	"<li class='hours'>Hours of Operation:</li>" +
					"<li>" + myStore.eq(5).text() + "</li></ul></div>";
	if (myStoreHeader !== "") {
		$('#print-masthead .print-store').append(printText);
	}

});

