/**
*	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');

			// 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;
			$item.next().find('li.first a').trigger('mouseenter');
		},
		hideMainMenu: function() {
			$('.corner').hide();
			$('.rt-corner').hide();
			$('#globalMenu a.selected').removeClass('selected');
			$('#globalMenu .sub-level').removeClass('visible');

			isNavigating = false;

			if ( menuTimeout !== undefined ) { clearTimeout( menuTimeout ); }
		},
		/*
		homepageState: function() {
			if (isHomepage && !isNavigating) {
				$('#globalMenu a.trigger:first').addClass('selected');
			}
		},
		*/
		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+Items_4294832078_4294937087_"><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')) ? null : ppos.top-1;

	$('.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();
}

/* 14717 - Updated to Stop Search Default Text from Being Inserted into User Entered Text */
;(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');
				
				if ($placeholder.attr('value') === "")
				{
					$placeholder.attr('value', attrPh);
				}
				
				$placeholder.css('color', settings.blurColor).bind('focus', function() {
					var $this = $(this);
					var strValue = $this.val();
					if (strValue.indexOf(attrPh) > -1) {
						$this.val(strValue.replace(attrPh, "")).css('color', settings.focusColor);
					}
				}).bind('blur', function() {
					var $this = $(this);
					if ($this.val() === '') {
						$this.val(attrPh).css('color', settings.blurColor);
					}
				});
			}
		});
	};
})(jQuery);


/* Original Masthead Functions */
var guestReg;
var thisStoreID;
var thisLangID;
var thisCatID;
var thisRedirectURLAfterLogon;
var vCurrent = 0,
	vTotal = 1,
	vDuration = 5000,
	intInterval = 0,
	vTmp = 24;
//=============================================
$(document).ready(function(){
	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';
	}
    if(typeof(URLAfterLogon) == "undefined") {
		thisRedirectURLAfterLogon = 'TopCategoriesDisplayView';
	} else {
		thisRedirectURLAfterLogon = encodeURL(URLAfterLogon);
	}

	/* 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);
	}

	
	if($.browser.msie){
		setTimeout(chkStoreCookies,500);
		setTimeout(getCartInfo,500);
	} else {
		chkStoreCookies();
		getCartInfo();
	}
	setMyAccountLinks();
	getWelcomeInfo();
	
	vTotal = $(".banner_slides").children().size() -1;
				intInterval = setInterval(fnLoop, vDuration);
				$("#banner_object").find(".banner_slide").each(function(i) { 
					vTmp = ((i-1) * 24) + (vCurrent * 24);
					$(this).css({"top": vTmp+"px"});
				});
	// Testing async add this load
	initAddThis();
	cartFix(); /* Removing additional .last from the <tr>'s */
	removeFree(); /* Removes the word FREE from the shipping info areas for a specific item */

	setupEmailModal();
});

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 removeFree() {

	var item_url = '&productId=3272271',
		//item_url = 'pd_74025-25428-85595_0',
		item_id = '3272271',
		$cart_item_links = $('#my-cart-contents .prod-details a');

	if ( window.location.href.indexOf(item_url) >= 0 ) {

		$('.promo-text').html(''); //'<strong>Price includes the $4.95 <br> shipping and handling cost.</strong>'
		$('#pricing').css('padding-bottom', '0px');
		$('.ship-options-pickup').parent('li').remove();
		$('.ship-options-deliver').parent('li').remove();
		$('.delivery-estimate').remove();
		/*$('#OrderItemAddForm').remove();*/

	}

	$cart_item_links.each(function(i, item){

		var $item = $(item);

		if ( $item.attr('href').indexOf(item_id) >= 0 ) {

			var $delivery = $item.parents('.prods').next('.delivery');

			$delivery.find('.delivery-options .promo-text').remove();
			$('.ship-options-pickup', $delivery).parent('li').remove();
			$('.ship-options-deliver', $delivery).parent('li').remove();

		}

	});

	if ( $('#item_3272271').length === 1 ) {

		var $item = $('#item_3272271');

		if ( $item.find('.addToCart').length === 1 ) {

			$item.find('.availability-info').empty();
			//.html('<p><strong>Price includes the $4.95.</p>').css({'position':'relative', 'top':'-40px'});

		}

	}

}

function cartFix() {
	var $items = $('#my-cart-contents tbody tr');

	$items.each(function(i, item) {
		var $item = $(item);

		//console.log('TR: ', $item, $item.hasClass('last'), i + 1, $items.length);

		// 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 initAddThis() {
	try {
		addthis.init();
	}catch(e){}
}

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">');
	}
}

/* Global For Spring */
function toggle_spring_pop() {
	if($('#spring-global-pop').hasClass('flag_set')) {
		$('#spring-global-pop').removeClass('flag_set').fadeOut();
	} else {
		$('#spring-global-pop').addClass('flag_set').fadeIn();
	}
}
/* End: Global For Spring */

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(){
      var linkBool;
      if(guestReg == 'G'){
            linkBool = 'true';
      } else {
            linkBool = 'false';
      }
	if($('#myAccountTopNav').length > 0){
		/*$('#masthead #top-nav ul#cart-account li a#nav-my-account').attr('href','javascript:displayURL(\'UserAccountView?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID+'&state=P\',\'false\')');*/
		$('#nav-my-profile').attr('href','javascript:displayURL(\'UserAccountView?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID+'&state=P\',\''+linkBool+'\')');
		$('#nav-my-order').attr('href','javascript:displayURL(\'OrderStatusDisplay?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID+'\',\''+linkBool+'\')');
		$('#nav-my-rebates').attr('href','javascript:displayURL(\'MyRebatesDisplayView?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID+'\',\''+linkBool+'\')');
		$('#nav-my-credit-center').attr({'href':'https://credit.lowes.com','target':'_blank'});
		$('#nav-my-projects').attr('href','javascript:displayURL(\'MyProjectsDisplayView?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID+'\',\''+linkBool+'\')');
		$('#nav-my-subscriptions').attr('href','javascript:displayURL(\'UserSubscriptionView?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID+'\',\''+linkBool+'\')');
	}

}
//=============================================

function getCartInfo(){
	if($('#masthead_content .cart-total').length > 0){
		if(chkCookie('SHOPPINGCART')){
			var cartInfo = chkCookie('SHOPPINGCART').split('|');
			var items = cartInfo[0];
			var total = cartInfo[1];
			$('#masthead_content .cart-total').text(total +' ('+items+' items)');
		} else {
			$('#masthead_content .cart-total').text('$0.00 (0 items)');
		}
		$('#myAccountTopNav .my-orders').attr('href','OrderStatusDisplay?storeId='+thisStoreID+'&catalogId='+thisCatID);
		$('#masthead_content .my-cart').attr('href','OrderItemDisplay?storeId='+thisStoreID+'&catalogId='+thisCatID);
		$('#masthead_content .checkout').attr('href','CheckoutLinkRouting?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID);
	}
}
//=============================================
function getWelcomeInfo(){
	var $salutation = $('#salutation');

	if( $salutation ) { /* #masthead #top-nav */
		var welcomeMsg,
			userStatus,
			userURL,
			acctStatus,
			acctURL,
			catDisplayURL; /* Variable that is added to end of URL */
		// Variable set by IT
		//if(typeof(redirectURLAfterLogon) == "undefined") {
		//	var redirectURLAfterLogon;
		//}
		if(!thisRedirectURLAfterLogon) {
			//catDisplayURL = 'StoreCatalogDisplay';
			catDisplayURL = 'TopCategoriesDisplayView';
		} else {
			catDisplayURL = thisRedirectURLAfterLogon;
		}
		//check to see if the firstName cookie exists
		if(chkCookie('firstName')){
			var custName;
			var custFirstName = chkCookie('firstName');
			// if the user's name is greater than 40 characters, truncate the name
			if(custFirstName.length >= 24){ /* Updated value to 24 from 40 to help fix a bug - SA */
				custName = custFirstName.substring(0,24)+'...';
			} else {
				custName = custFirstName;
			}
			acctStatus = 'Not You?';
			acctURL = '/webapp/wcs/stores/servlet/Logoff?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID+'&rememberMe=false&URL=TopCategoriesDisplayView';
			//check to see if the employee cookie is set
			if (chkCookie('userSegment') == 'Employee'){
				if (!chkCookie('invalidUserSegment')){
					welcomeMsg = 'Welcome ' + custName + ' <span class="user-type">- Employee</span>';
				} else {
					// this is an invalid user segment cookie, remove the 2 cookies
					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=/';
				}
			}else if (chkCookie('userSegment') == 'Realtor'){
				if (chkCookie('invalidUserSegment') != 'true'){
					welcomeMsg = 'Welcome ' + custName + ' <span class="user-type">- Realtor</span>';
				}else{
					// this is an invalid user segment cookie, remove the 2 cookies
					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=/';
				}
			}else{
				welcomeMsg = 'Welcome ' + custName;
			}
		} else {
			welcomeMsg = "Welcome to Lowe's ";
			acctStatus = 'Register';
			acctURL = '/webapp/wcs/stores/servlet/UserRegistrationForm?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID+'&new=Y&URL='+catDisplayURL;
		}
		// determine if the user is logged in
		if(guestReg == 'R'){
			userStatus = 'Log Out';
			userURL = '/webapp/wcs/stores/servlet/Logoff?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID+'&URL=TopCategoriesDisplayView';
		} else {
			userStatus = 'Log In';
			userURL = '/webapp/wcs/stores/servlet/LogonForm?langId='+thisLangID+'&storeId='+thisStoreID+'&catalogId='+thisCatID+'&URL='+catDisplayURL;
		}

		$salutation.find('.welcome').append(welcomeMsg);
		$salutation.find('#account-status').append(acctStatus).attr('href',acctURL);
		$salutation.find('#user-status').append(userStatus).attr('href',userURL);
		$salutation.show();
	}
}
//=============================================
function chkCookie(name) {
	var labelName = 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(labelName) == 0){
			return c.substring(labelName.length,c.length);
		}
	}
	return null;
}

//=============================================
function chkStoreZIP(cookie) {
	if(chkCookie(cookie)) {

		var cookie_info = chkCookie(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', 'selectedStore2', 'selectedStore3', 'selectedStore4', 'selectedStore5'];
	var storeChangeTimeOut;
	var storeInfoTimeOut;
	//---------------------------
	$(cookies).each(function(i){
		if(chkCookie(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, ','));
				}

				$('#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>');
			}
			//console.log($('#current-store-detail').attr('href'));
		}
	});
	//-------------------------
	$('#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);
			//console.log(($(this).position().left - 328)+'px');
			$('#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(chkCookie('selectedStore1')){
		$('#my-store').show();
		$('#masthead_masthead_storeLocation').hide();
	}else{
		$('#masthead_storeLocation').show();
		$('#masthead_storeLocation form#storeSearchForm #findMyStore').bind('click',function(){
			document.storeSearchForm.submit();
		});
	}
	//-----------------------------
}
//================================================
/* This is now being handled by Seth's $.replaceholder. */
/*
function clearMastInputs(){
	$('#header-block input[type=text]').each(function(i){
		var defaultInput = $(this).val();
		$(this).bind('focus',function(){
			if($(this).val() == defaultInput) {
				$(this).val('');
			}
		});
		$(this).bind('blur',function(){
			if($(this).val() == ''){
				$(this).val(defaultInput);
			}
		});
	});
$('#utility-content input[type=text]').each(function(i){
                var defaultInput = $(this).val();
                $(this).bind('focus',function(){
                        if($(this).val() == defaultInput) {
                                $(this).val('');
                        }
                });
                $(this).bind('blur',function(){
                        if($(this).val() == ''){
                                $(this).val(defaultInput);
                        }
                });
        });
}
*/
/*
 *	A generic set of functions to clear/restore an input field's value.
 *	Use: <input type="text" onblur="restoreValue(this);" onfocus="clearValue(this);" value="Original Value" />
 */
/* This is now being handled by Seth's replaceholder. */
/*
var defaultInput;
function clearValue(i){
	defaultInput = i.value;
	if(i.value == defaultInput) {
		i.value='';
	}
}
function restoreValue(i){
	if(i.value == ''){
		i.value=defaultInput;
	}
	defaultInput='';
}
*/
// End input value functions
//================================================
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').click(
		function(e) {
			e.preventDefault();
			$emailModal.dialog('open');
			$('#cm_email_dialog .email_modal_content iframe').attr('src', 'http://ebm.email.lowes.com/r/regf2?n=1&amp;a=0&amp;aid=2085936093');
		}
	)
}
