var boolFavStores = false;
var bInitialized = bLocalized = bHasLocalStore = false;
var bPageClicked = false;

$(document).ready(function(){
	initLocalizeStatus();
	initInventory();
	//initTabs();
	bindCheckBtn();
	bindTypeAhead();
	//initFavStore();
});


function initInventory () {
	// checkFavStores();	// Removed from redesign
	$('a.check-inventory',document.getElementById("instore-inventory")).click(function(e){
		e.preventDefault();
		//checkFavStores();	// Removed from redesign
		$(this).fadeOut('fast',function(){
			if (boolFavStores) {
				initFavStore('stock');
			} else {
				displayStores(true);
			}
			$('#storeInvLookup').focus();
		});
		// ACCESSIBILITY
		// add event listener for 'esc' to simulate the 'cancel' click
		$('#storeInvLookup').bind( 'keydown', 
			function(event) {
				if(event.keyCode == '27') {
					$('#storeInvLookup').unbind( 'keydown' );
					$('a.cancel', $("#inventoryFormDiv")).click();
				}
			}
		);
		return false;
	});
	$('a.cancel', $("#inventoryFormDiv")).click(function(e){
		e.preventDefault();
		//checkFavStores();	// Removed from redesign
		$('#inventoryFormDiv').fadeOut('fast', function(){
			if (boolFavStores) {
				initFavStore('stock');
			} else {
				$('a.check-inventory',$("#instore-inventory")).fadeIn('fast',
					function(){
						$('.check-inventory').focus();
					}
				);
			}
		});
		return false;
	});
	

	/* this button now invokes the overlay directly
	 * implemented in bindCheckBtn()
	$('a.check-other-stores', '#inventoryResults').click(function(){
		$('#inventoryResults').fadeOut('fast',function(){
			$('span.hdr-find-stores','#inventoryFormDiv').hide();
			$('span.hdr-check-other-stores','#inventoryFormDiv').show();
			$('#inventoryFormDiv', '.inventory').fadeIn('fast');
		});
		return false;
	});
	*/
}
function checkFavStores() {
	var favStores = $.cookie('favStores');
	if (favStores != null && favStores != '' && favStores != '""')
		boolFavStores = true;
	else
		boolFavStores = false;
}
function initStoreLink()
{
	$('.storeNameLink').click(function() {
		return false;
	});
	
	$('.storeNameLink').hover(function() {
		if ($(this).parent().find('.storeInfoBox').attr('class')!=null)
		{
			$(this).parent().find('.storeInfoBox').show();
		}
		else
		{
			var id = $(this).attr('id');
			data =  {
				searchTerm: id,
				searchBy:'postalCode',
				langId:   eStore.langId,
				storeId:   10051,
				skuNumber: $('#skuNum').text(),
				radius: 0,
				show: 'store'
			};
			$.ajax({
				url: '/webapp/wcs/stores/servlet/InStoreInventoryCheck',
				type: 'GET',
				data: data,
				dataType: 'html',
				success: function(html) {
					$('#'+id).parent().append(html);
					$('#'+id).parent().find('.storeInfoBox').show();
				},
				error: function() {
					//alert('fail');
				}
			}); 
		}
	},function() {
		$(this).parent().find('.storeInfoBox').hide();
	});
	
}
function initTabs() {  
	
	$('#right-nav #inventoryDiv .inventoryContent .contentDiv:first-child').addClass('selected');
	$('#right-nav .tabs .tab:first-child').addClass('selected');
	if ($('#right-nav .tabs .tab').length == 1  )
	{
		$('#right-nav .tabs').addClass('oneTab');
	}
	else
	{
		$('#right-nav .tabs .tab').each(function() {
			$(this).click(function(){
				if($(this).hasClass('selected'))
				{
				}
				else
				{
					$(this).parent().find('.tab').removeClass('selected');
					$(this).addClass('selected');
					var id=$(this).attr('id').replace('Tab','');
					$(this).parent().parent().find('.contentDiv').removeClass('selected');
					$(this).parent().parent().find('#'+id).addClass('selected');
				}
			});
		});
	}
}


bindCheckBtn = function(){
	$('#storeInvCheck').bind('click',function(e){
		e.preventDefault();
		if ($('#storeInvLookup').val() == '')
		{
			var alert_msg = 'Please enter your City and Province, Postal Code or Store #:';
			if (eStore.langId == -16)
				alert_msg = 'Veuillez saisissez votre ville et province, code postal ou num\u00E9ro de magasin :';
			alert(alert_msg);
			return false;
		}
		checkStore(0,'storeInvLookup','/webapp/wcs/stores/servlet/InStoreInventoryCheck',e);
		trackInstoreInventoryLaunch();
		startTimer();
		return false;
	});
	$('#checkForm').submit(function() {
		if ($('#storeInvLookup').val() == '')
		{
			var alert_msg = 'Please enter your City and Province, Postal Code or Store #:';
			if (eStore.langId == -16)
				alert_msg = 'Veuillez saisissez votre ville et province, code postal ou num\u00E9ro de magasin :';
			alert(alert_msg);
			return false;
		}
		checkStore(0,'storeInvLookup','/webapp/wcs/stores/servlet/InStoreInventoryCheck');
		trackInstoreInventoryLaunch();
		return false;
	});
	
	$(".check-stores",document.getElementById("inventoryResults")).click(function(e){
		e.preventDefault();
		if (bLocalized){
			var s0="";
			if (bHasLocalStore){
				oStore=getUserLocalStore();
				s0=oStore.postalCode.replace(" ","");
			}else{
				var oRegion=getLocalRegion();
				s0=oRegion.province?oRegion.city+","+oRegion.province:oRegion.city;
			}
			var e0=document.getElementById("storeInvLookup");
			if (e0){ e0.value=s0; }
			checkStore(0,'storeInvLookup','/webapp/wcs/stores/servlet/InStoreInventoryCheck',e);
			if (e0){ e0.value=""; }
			trackInstoreLocalizedInventoryLaunch();
		}
	});
}

// ************************************************* //
// ****************** REDESIGNED ******************* //
// ************************************************* //
function isLocalized(){
	var oRegion=getLocalRegion();	// @oRegion={...}
	var b0=false;
	if (typeof(oRegion)!="undefined" && oRegion!=null && typeof(oRegion.defaultRegion)!="undefined"){
		//console.log("//***** check local region=");
		//console.log(oRegion);
		b0=oRegion.defaultRegion=="false";
	}
	return b0;
}

function hasLocalStore(){
	var oStore=getUserLocalStore();	// @oStore={...}
	var b0=false;
	if (typeof(oStore)!="undefined" && oStore!=null && typeof(oStore.storeId)!="undefined"){
		//console.log("//***** check local store=");
		//console.log(oStore);
		b0=true;
	}
	return b0;
}

function initLocalizeStatus(){
	bLocalized=isLocalized();
	bHasLocalStore=hasLocalStore();	
	bInitialized=true;
	//console.log("##### bLocalized="+bLocalized+"; bHasLocalStore="+bHasLocalStore+"; bInitialized="+bInitialized);
}

function displayStores(update){
	// @update:bool
	var ajaxLoader=document.getElementById("ajax-loader-small");
	
	var populateHTML=function(search_term,has_local){
		// @search_term:string
		if (!search_term) { return; }
		//console.log("populateHTML():: search_term="+search_term);
		var e6=document.getElementById("inventoryResults");
		var e2=$(".inventoryResultsTbl tbody",e6); // @e2=jQ<table>
		var e3=$(".select-stores",e6), e4=$(".check-other-stores",e6);	// @e3=jQ,e4=jQ
		
		var data={
			searchTerm:search_term,
			searchBy:'postalCode',
			langId:eStore.langId,
			storeId:10051,
			skuNumber:$('#skuNum').text(),
			radius:200,
			show:'stock',
			hasStore:has_local
		};

		$.ajax({
			url: '/webapp/wcs/stores/servlet/InStoreInventoryCheck',
			type: 'GET',
			data: data,
			dataType: 'html',
			success: function(html) {
				e2.empty();
				if (ajaxLoader) { ajaxLoader.style.display="none"; }
				e2.append(html);
				//e2.find('.storeInfoBox').show();
				e2.find('a.storeNameLink').hover(function(){
					// hover in
					$(".storeInfoBox",this.parentNode).show();
				},function(){
					// hover out
					$(".storeInfoBox",this.parentNode).hide();
				});
				$(e6).fadeIn('fast');
				if (has_local){
					e3.hide();
					e4.show();
				}else{
					e3.show();
					e4.hide();
				}
				trackInstoreLocalizedInventoryLaunch();
			},
			error: function() {
				//alert('fail');
			}
		});
	};
	
	var updateDOM=function(){
		// no DOM update if check button hasn't been clicked
		var e10=$(".check-inventory",document.getElementById("instore-inventory"));
		if (e10[0].style.display != "none") { return; }
		
		var e0=$(document.getElementById("inventoryFormDiv"));	// @e0=jQ<div>
		var e1=$(document.getElementById("inventoryResults"));	// @e1=jQ<div>
		var e5=$(".inv-title-small",document.getElementById("instore-inventory"));	// @e5=jQ<h3>
		e1.hide();
		
		if (bLocalized){
			if (ajaxLoader) { ajaxLoader.style.display="block"; }
			var s0="";	// @s0:string
			// user is localized
			//console.log("// user is localized");
			e0.hide();
			e5.hide();
			
			if (bHasLocalStore){
				// has local store
				//console.log("// has local store");
				var oStore=getUserLocalStore();
				s0=oStore.postalCode.replace(" ","");
			}else{
				// no local store
				//console.log("// no local store");
				var oRegion=getLocalRegion();
				s0=oRegion.province?oRegion.city+","+oRegion.province:oRegion.city;
				// o.lat o.lng o.radius o.success o.limit
			}
			populateHTML(s0,bHasLocalStore);
		}else{
			// user is not localized
			//console.log("// user is not localized");
			e0.fadeIn('fast');
			e5.fadeIn('fast');
		}

	};
	
	updateDOM();
}	// end of displayStoresNearBy()

function getLocalRegion() {
	var cookie = $.cookie('localRegion');
	if (cookie != null) {
		var parts = cookie.split(',');
		return {
			marketId: parts[0],
			masterStoreId: parts[1],
			city: parts[2],
			coords: {lat: parts[3], lng: parts[4]},
			defaultRegion: parts[5],
			province: (parts[6]!="undefined")?parts[6]:""
		}
		
	}
}

	
function getUserLocalStore() {
	var cookie = $.cookie('userFavStore');
	if (cookie != null) {
		var parts = cookie.split(',');
		return {
			storeId: parts[0],
			storeName: parts[1],
			marketId: parts[2],
			coords: { lat: parts[3], lng: parts[4]},
			city: parts[5],
			province: (parts[6]!="undefined")?parts[6]:"",
			postalCode: (parts[7]!="undefined")?parts[7]:""
		}
	}
}
// ***************************************************** //
// ****************** END REDESIGNED ******************* //
// ***************************************************** //

function initFavStore(stock)
{
	var stock = stock;
	var favStores = $.cookie('favStores');
	if (favStores != null && favStores != '' && favStores != '""')
	{
		var stores = favStores.split('-');
		if (stock==null)
		{
			for ( i = 0; i < stores.length; i++)
			{
				var storeArr = stores[i].split(':');
				var checkBtnText = 'Check';
				if (eStore.langId == '-16')
				{
					var checkBtnText = 'V\u00E9rifier';
				}
				/*if (i == 1)
				{
						
				}
				$('.inventoryResultsTbl tbody').append('<tr class="storeRow"><td><div class="storeNameDiv"><a href="#" class="storeNameLink" id="'+storeArr[0]+'">'+storeArr[1]+'</a></div></td><td>&nbsp;</td></tr>');*/
				if (i == 0)
				{
					$('.inventoryResultsTbl tbody').append('<tr class="storeRow"><td><div class="storeNameDiv"><a href="#" class="storeNameLink" id="'+storeArr[0]+'">'+storeArr[1]+'</a></div></td><td rowspan="3" valign="bottom"><a href="#" id="checkInventoryBtn" class="button generic-button"><span>' + checkBtnText + '</span></a></td></tr>');
				}
				else
				{
					var trClass = '';
					if (i == 1)
					{
						trClass = ' alt';	
					}
					
					$('.inventoryResultsTbl tbody').append('<tr class="storeRow'+trClass+'"><td><div class="storeNameDiv"><a href="#" class="storeNameLink" id="'+storeArr[0]+'">'+storeArr[1]+'</a></div></td></tr>');
				}
				
			}
			/*$('.inventoryResultsTbl tbody').append('<tr class="storeRow"><td colspan="2"><a href="#" id="checkInventoryBtn" class="button generic-button"><span>' + checkBtnText + '</span></a></td></tr>');*/
			
			initStoreLink();

			$('#checkInventoryBtn').click(function()
			{
				startTimer();
				initFavStore('stock');
				return false();
			});
		}
		else
		{
			$('.inventoryResultsTbl .storeRow').remove();
			var storeIds = '';
			for ( i = 0; i < stores.length; i++)
			{
				var storeArr = stores[i].split(':');
				var id = storeArr[0];
				var name = storeArr[1];
				storeIds += id + ',';
			}
			data =  {
				searchTerm: storeIds,
				searchBy:'postalCode',
				langId:   eStore.langId,
				storeId:   10051,
				skuNumber: $('#skuNum').text(),
				radius: 0,
				show: 'stock'
			};
			$.ajax({
				url: '/webapp/wcs/stores/servlet/InStoreInventoryCheck',
				type: 'GET',
				data: data,
				dataType: 'html',
				success: function(html) {
					$('.inventoryResultsTbl tbody').append(html);
					$('.inventoryResultsTbl').find('.storeInfoBox').hide();
					$('.inventoryResultsTbl .storeRow').each(function () {
						var storeName = $(this).find('.storeNameLink').text();
						var stockNumber = $(this).find('.availSpan').text();
						//var prodName = $('.pip-area .prod-info h2').html();
						var prodName = $('.category',document.getElementById('global-crumb-trail')).html();
						//console.log("***** initFavStore prodName="+prodName+"; storeName="+storeName+"; stockNumber="+stockNumber);
						trackInstoreInventoryCalls(prodName, storeName, stockNumber);								
					});
					stopTimer();
					initStoreLink();
				},
				error: function() {
					//alert('fail');
				}
			});
		}
		
		$('#inventoryResults').show();
		$('#inventoryFormDiv').addClass('second-calc');
		if(eStore.langId == -15)
			$('#checkTitle').text('Check Other Stores');
		if(eStore.langId == -16)
			$('#checkTitle').text('Voir d\'autres magasins');
		$('#storeInvCheck').attr('class','button generic-button');
		$('#org-disclaimer').hide();
		/*if (eStore.langId == -15)
		{
			$('.inventory-disclaimer').html('Local store prices may vary from those displayed. Inventory levels change frequently, so please confirm with your (local) store.');
		}
		else
		{
			$('.inventory-disclaimer').html('Les prix \u00E0 votre magasin local peuvent varier de ceux indiqu\u00E9s ici. Les produits pr\u00E9sent\u00E9s comme \u00E9tant en stock le sont normalement, mais les quantit\u00E9s en stock ne peuvent \u00EAtre garanties. Veuillez confirmer avec votre magasin. ');
		}*/
		$('#inventoryFormDiv', '.inventory').hide();
	}
	else
	{
		/*
		$('#inventoryResults').hide();
		$('#inventoryFormDiv').removeClass('second-calc');
		if(eStore.langId == -15)
			$('#checkTitle').text('Check In-Store Inventory');
		if(eStore.langId == -16)
			$('#checkTitle').text('V\u00E9rifiez l\'inventaire en ligne');*/
		$('#checkTitle').text('');
		$('#org-disclaimer').show();
		$('#storeInvCheck').attr('class','button generic-button');
		/*$('.storeRow').remove();
		if (eStore.langId == -15)
		{
			$('.inventory-disclaimer').html('Price and availability may vary by store');
		}
		else
		{
			$('.inventory-disclaimer').html('Les prix et l\'offre des produits peuvent varier en magasin.');
		}*/

	}	
}

function checkStore(status,inputField, urlName,evt)
{
	var inputField = inputField;
	var radius = $('#radius').val();
	var urlName = urlName;
	if (radius == null)
		radius = 200;
	if (urlName == 'StoreLocator')
		skuNumber = null;
	else
		skuNumber = $('#skuNum').text();
		
	if (inputField != null)
	{
		var searchTerm = $('#'+inputField).val();
		searchTerm = replaceFrench(searchTerm);
		if (searchTerm == '')
			searchTerm = null;
	}
	else
	{
		var searchTerm = null;	
	}
	data =  {
		searchTerm: searchTerm,
		searchBy:'postalCode',
		langId:   eStore.langId,
		storeId:   10051,
		skuNumber: skuNumber,
		radius: radius,
		show: 'all'
	};
	
	
	var ajaxLoader=document.getElementById("ajax-loader-large");
	if (evt && evt.pageY && evt.pageX) {
		var ajaxImg=$("img",ajaxLoader);
		ajaxImg.css("position","absolute");
		ajaxImg.css("top",(+evt.pageY-66)+"px");
		ajaxImg.css("left",Math.ceil(evt.pageX/2)+"px");
	}
	if (ajaxLoader) {
		ajaxLoader.style.height=$(document).height()+"px";
		ajaxLoader.style.display="block";
	}
	
	var displayInStoreInventoryCheckView = function(status,msg){ 
		//console.log('in displayInStoreInventoryCheckView');
		if (status == '0')
		{
			eStore.UI.Blocker.clear();
			var popup = new eStore.UI.Window('inventory-box');
		}
		else
		{
			$('#inventory-box').remove();
			var popup = new eStore.UI.Window('inventory-box');
			
		}
		
		var html = '<div class="storeBox">';
		var e_thumb = document.getElementById('product-image-thumbnails');
		e_thumb = $('img.thumbnail',e_thumb).first();
		var title="View Product Availability";
		if (eStore.langId==-16){
			title="Voir les quantit&#233;s en stock d'un produit";
		}
		
		//html += '<h2>'+$('.main-product-info .main-info h1').html()+'</h2>';
		popup.title( title );
		//html += '<h2>' + title + '</h2>';
		html += '<img class="store-thumb" src="'+e_thumb.attr('src')+'" alt="'+$('.main-product-info .main-info h1 .brand').html()+'" />';
		html += '<h3>'+$('.main-product-info .main-info h1').html()+'</h3>';
		html += '<p class="prodDetail">'+$('.main-product-info .main-info .model-info').html()+'</p>';
		html += msg;
		popup
			.prepend(html)
			.removeClass('plain')
			.addClass('large')
			.addDecorators('<span class="btm-edge"></span>')
			.blockUI(true);
		
		popup.find('.close-button').click(function() {
			// put BV content back into hidden <div> in the DOM for subsequent retrievals
			//var tempBVContent = popup.find('#BVQAContainer');
			eStore.UI.Blocker.clear();
			trackInstoreInventoryClicks('close (top)');
			initFavStore('stock');
			if (bHasLocalStore){ displayStores(); }
			
		});
		popup.find('#closeTextBtn').click(function() {
			eStore.UI.Blocker.clear();
			trackInstoreInventoryClicks('close (bottom)');
			initFavStore('stock');
			if (bHasLocalStore){ displayStores(); }
			return false;
		});
		
		// ****************************************** //
		// ********** Redesigned functions ********** //
		// ****************************************** //
		var mapSearch = new eStore.UI.StoreLocator.SearchHelper();
		var myInvMap, myLocalStore;
		
		var initUserLocalStore=function(){
			$.cookie("favStores",null,{expires:0});	// erase old cookie
			var cookie=getUserLocalStore();	// @cookie=json
			//console.log("----- cookie -----");
			//console.log(cookie);
			if (typeof(cookie)=="undefined" || typeof(cookie.storeId)=="undefined") { return; }
			var j0=popup.find("#store-"+cookie.storeId);	// @j0=jQ<div>
			//console.log(j0);
			if (j0.length>0){
				$("a.set-fav-store",j0[0]).hide();
				$("p.my-local-store",j0[0])[0].style.display="block";	// for some weird reason .show() doesn't work
				myLocalStore="store-"+cookie.storeId;
			}
		};
		
		initUserLocalStore();
		
		var mapAction = function(obj){
			// @obj = <a>
			if (!obj){ return; }
			var eBox=obj.parentNode.parentNode.parentNode; // <div>
			var j0=$(obj);
			var s0=j0.attr("data-store-num");
			var s1=j0.attr("data-address");
			//console.log("******** mapAction *********");
			//console.log("***** store-num="+s0+"; address="+s1);
			
			// map opened - close it
			if( eBox.className.indexOf('map-selected') > -1 ) {
				// close the map
				$('#inventory-close-map').click();
				// change the link copy
				obj.innerHTML = obj.innerHTML.replace('Close','View').replace('Fermer','Voir la');
			}
			// open map
			else if (typeof(s0)=="string" && typeof(s1)=="string"){			
				mapSearch.searchByStoreNum({
					storeNum:s0,
					address:s1,
					success:function(){
						if (arguments.length<=0){ return; }
						var jStore=arguments[0][0];
						//console.log(jStore);
						var param={
							coords:jStore.coords,
							index:1,
							title:jStore.storeName,
							storeAddress:jStore.address+"<br/>"+jStore.city+" "+jStore.province+"<br/>"+jStore.postalCode
						}
						//console.log(param);
						
						var e0=$(document.getElementById("inventory-map-wrapper")); // e0=<div>
						var storeDiv=document.getElementById(e0.attr("data-store"));
						if (storeDiv) { $(storeDiv).removeClass("map-selected"); }
						var eDetails=$(document.getElementById("store-details-wrapper"));
						if (eDetails.hasClass("map-selected")) { eDetails.removeClass("map-selected"); }
						if (e0.attr("data-store")=="store-details-wrapper"){
							var storeNumber=storeDiv.getAttribute("data-store");
							if (storeNumber){
								storeDiv=document.getElementById(storeNumber);
								$(storeDiv).removeClass("map-selected");
							}
						}
						

						if (eBox) { e0.attr("data-store",eBox.id); }
						if (!myInvMap) {
							myInvMap=new eStore.UI.StoreLocator.Map({
								canvas:$(document.getElementById("inventory-map-canvas")),
								controls:{view3:false,zoomlevel:10}
							});
						}
						myInvMap.clearMarkers();
						myInvMap.addMarker(param);
						myInvMap.showMarkers();
						
						var jContent=$(".inventory-page",document.getElementById("inventory-wrapper"));
						var iTop=jContent.position().top;
						
						if (eBox){
							$(eBox).addClass("map-selected");
						}
						if (eBox.id=="store-details-wrapper"){
							$(document.getElementById(eBox.getAttribute("data-store"))).addClass("map-selected");
						}
						
						if (eBox.className.indexOf("-left") >= 0){
							e0[0].className="top-right";
						}else if(eBox.className.indexOf("-right") >= 0){
							e0[0].className="top-left";
						}
						//console.log("after-----box class="+eBox.className+"; map class="+e0.attr("class"));
						
						e0.css("top",-iTop+"px");
						e0.fadeIn("fast", function(){
							// change the link copy
							obj.innerHTML = obj.innerHTML.replace('View','Close').replace('Voir la','Fermer');
						});

					},
					error:function(){
						if (arguments.length<=0){ return; }
						console.log("XHR="+argument[0]+"; TextStatus="+argument[1]+"; Error="+argument[2]);
					}
				}); // end mapSearch.searchByStoreNum()
			}
			trackInstoreInventoryClicks('view map');
		};	// end of mapAction()
		
		var setFavStore=function(obj,is_details){
			// @obj=<a>
			// @is_details:bool
			if (!obj) { return; }
			// show/hide my local store icons
			var j0=$(obj);
			j0.hide();
			//console.log("myLocalStore="+myLocalStore);
			if (typeof(myLocalStore)=="string" && myLocalStore.length>0){
				var e0=document.getElementById(myLocalStore); // e0=<div>
				$("p.my-local-store",e0).hide();
				$("a.set-fav-store",e0).show();
			}
			var s0=j0.attr("data-store-num");
			var s1=j0.attr("data-address");
			
			myLocalStore="store-"+s0;
			
			$("p.my-local-store",obj.parentNode).show();
			if (is_details){
				var e1=document.getElementById(myLocalStore);
				$("a.set-fav-store",e1).hide();
				$("p.my-local-store",e1).show();
			}else{
				var eDetails=document.getElementById("store-details-wrapper");
				$("a.set-fav-store",eDetails).show();
				$("p.my-local-store",eDetails).hide();
			}
			
			//console.log("******** storeLocator *********");
			//console.log("***** store-num="+s0+"; address="+s1);
			//console.log(eStore.storeLocator);

			// -- save to cookie	
			if (typeof(s0)=="string" && typeof(s1)=="string"){		
				mapSearch.searchByStoreNum({
					storeNum:s0,
					address:s1,
					success:function(){
						if (arguments.length<=0){ return; }
						var jStore=arguments[0][0];
						//console.log(jStore);
						bLocalized=true;
						bHasLocalStore=true;
						eStore.storeLocator.setUserFavStore(jStore,{external:true,expires:365});
					},
					error:function(){
						if (arguments.length<=0){ return; }
						console.log("XHR="+argument[0]+"; TextStatus="+argument[1]+"; Error="+argument[2]);
					}
				}); // end mapSearch.searchByStoreNum()
			}
			
		};
		
		popup.find('#inventory-close-map').click(function(e){
			e.preventDefault();
			var e0=$(document.getElementById("inventory-map-wrapper"));
			e0.fadeOut("fast");
			var dataStore=e0.attr("data-store");
			var storeDiv=document.getElementById(dataStore);
			if (storeDiv) { $(storeDiv).removeClass("map-selected"); }
			var eDetails=$(document.getElementById("store-details-wrapper"));
			if (eDetails.hasClass("map-selected")) { eDetails.removeClass("map-selected"); }
			if (dataStore=="store-details-wrapper"){
				var storeNumber=storeDiv.getAttribute("data-store");
				if (storeNumber){
					storeDiv=document.getElementById(storeNumber);
					$(storeDiv).removeClass("map-selected");
				}
			}
		});
		
		popup.find('a.store-details-show').click(function(e){
			// Inventory popup show/hide details control
			e.preventDefault();
			var eBox=this.parentNode.parentNode; // <div>
			var eDetails=document.getElementById("store-details-wrapper");	//
			var link=this;
			//console.log("***** eBox.class="+eBox.className+"; a.class="+this.className+"; eDetails.class="+eDetails.className);
			var callBackAction=function(e){
				eDetails=$(eDetails);
				eBox=$(eBox);
				if (link.className.indexOf("in-summary")>0) {
					// show details
					eDetails.html(eBox.html());
					eDetails.find('a.store-details-hide').click(function(ev){
						ev.preventDefault();
						// accessibility
						try {
							if( ev.clientX == 0 || ev.clientY == 0 ) {
								$('.store-details-show',eBox).focus();
							}
						} catch(cold) {/*eat soup*/}
						// hide details
						eDetails.fadeOut("fast",function(){
							$(this).removeClass();
						});
					});
					eDetails.find('a.view-map').click(function(e){
						e.preventDefault();
						mapAction(this);
					});
					eDetails.find('a.set-fav-store').click(function(e){
						e.preventDefault();
						setFavStore(this,true);
					});
					var jContent=$(".inventory-page",document.getElementById("inventory-wrapper"));
					var iTop=jContent.position().top;
					var i0=0;
					
					if (eBox.hasClass("map-selected")){
						eDetails.addClass("map-selected");
					}
					
					eDetails.attr("data-store",eBox.attr("id"));
					
					if (eBox.hasClass("inventory-left")){
						if (eBox.hasClass("row-1")){
							eDetails.addClass("top-left");
						}else if (eBox.hasClass("row-3") || eBox.hasClass("row-2")){
							i0=eBox.innerHeight();
							eDetails.addClass("bottom-left");
						}
					}else if(eBox.hasClass("inventory-right")){
						if (eBox.hasClass("row-1")){
							eDetails.addClass("top-right");
						}else if (eBox.hasClass("row-3") || eBox.hasClass("row-2")){
							i0=eBox.innerHeight();
							eDetails.addClass("bottom-right");
						}
					}

					eDetails.css("top",function(index,value){
						//console.log("change top value from"+eDetails.position().top+" to "+-iTop+"; ebox height="+eBox.outerHeight(false));
						return -iTop+i0+"px";
					});

					// show details
					eDetails.fadeIn("fast");
					$('.store-details-hide',eDetails).focus();

					// accessibility
					
					// set up tabbing out of details
					// if tabbing backward out of favorite store
					// or tabbing forward out of hide details
					// then hide the details
					eStore.UI.KeyboardHelper.tabAction(
						eDetails.find('.set-fav-store'),
						true,
						function(){
							eBox.find('a.store-details-show').focus();
							eDetails.find('a.store-details-hide').click();
						}
					);
					eStore.UI.KeyboardHelper.tabAction(
						eDetails.find('a.store-details-hide'),
						false,
						function(){
							eBox.find('a.store-details-show').focus();
							eDetails.find('a.store-details-hide').click();
						}
					);

				}
			};
			
			if (eBox && eDetails){
				if (eDetails.className){
					$(eDetails).fadeOut("fast",function(){
						$(this).removeClass();
						callBackAction(e);
					});
				}else{
					callBackAction(e);
				}
			}
		});
		
		popup.find('a.pagination-link').click(function(e){
			e.preventDefault();
			// Inventory popup pagination control
			if (bPageClicked) { return; }
			bPageClicked=true;
			if (this.className.indexOf("inactive")>=0) { 
				bPageClicked=false;
				return;
			}
			var jContent=$(".inventory-page",document.getElementById("inventory-wrapper"));
			var jViewport=$(".storeInfo",document.getElementById("inventory-wrapper"));
			var iTop=jContent.position().top;
			var i0=jViewport[0].clientHeight, i1=jContent[0].scrollHeight;
			//console.log("*****top before="+iTop+"; clientHeight="+i0+"; scrollHeight="+i1);
			var b0=true;
			if (this.id=="store-link-prev"){
				if (iTop<0){
					// scroll up only when top position is negative
					jContent.animate({top:"+="+i0+"px"},"fast",function(){
						bPageClicked=false;
					});
					$(document.getElementById("store-link-next")).removeClass("inactive");
				}
				b0=iTop+i0<0;
			}else if (this.id=="store-link-next"){
				if (iTop>i0-i1){
					// scroll down only when total height - in view height >= out view height
					jContent.animate({top:"-="+i0+"px"},"fast",function(){
						bPageClicked=false;
					});
					$(document.getElementById("store-link-prev")).removeClass("inactive");
				}
				b0=iTop-i0>i0-i1;
			}
			if (!b0 && this.className.indexOf("inactive")<0){
				this.className+=" inactive";
			}
		});

		popup.find('a.view-map').click(function(e){
			// Inventory popup view map control
			e.preventDefault();
			mapAction(this);
		});
		
		popup.find('a.set-fav-store').click(function(e){
			e.preventDefault();
			setFavStore(this);
		});
		// ************************************************* //
		// ********** End of redesigned functions ********** //
		// ************************************************* //

		//console.log('faves');
		
		
		var favStores = $.cookie('favStores');
		if (favStores != null && favStores != '' && favStores != '""')
		{
			var stores = favStores.split('-');
			for ( i = 0; i < stores.length; i++)
			{
				var storeArr = stores[i].split(':');
				var className = 'favStore';
				if (i == 2)
				{
					className += ' last';
				}
				popup.find('.favStores').append('<span class="'+className+'"><a href="#" class="storeLink" id="'+storeArr[0]+'">'+storeArr[1]+'</a><a href="#" class="removeStoreLink">Remove</a></span>');
				popup.find('.storeTbl').find('tr').each(function()
				{
					if($(this).hasClass('tr_'+storeArr[0]))
					{
						var savedText = 'Currently Saved';
						if (eStore.langId == -16)
							savedText = 'Sauvegarde en cours';
						$(this).find('.save').html('<span class="savedText">'+savedText+'</span>');
					}
				});
			}
			popup.find('.savedBar').show();
		}
		else
		{
			popup.find('.savedBar').hide();
		}
		popup.find('.storeLink').click(function()
		{
			return false;
		});
		popup.find('.storeLink').hover(function()
		{
			if ($(this).parent().find('.storeInfoBox').attr('class')!=null)
			{
				$(this).parent().find('.storeInfoBox').show();
			}
			else
			{
				var id = $(this).attr('id');
				data =  {
					searchTerm: id,
					searchBy:'postalCode',
					langId:   eStore.langId,
					storeId:   10051,
					radius: 0,
					show: 'oneStore',
					type: 'userStore'
				};
				$.ajax({
					url: '/webapp/wcs/stores/servlet/StoreLocator',
					type: 'GET',
					data: data,
					dataType: 'html',
					success: function(html) {
						$('.favStores').find('#'+id).parent().append(html);
						
					},
					error: function() {
						//alert('fail');
					}
				}); 
			}
		},function()
		{
			$(this).parent().find('.storeInfoBox').hide();	
		});
		
		popup.find('.removeStoreLink').click(function()
		{
			var time = new Date().getTime();
			var storeInfo={
				storeName:$(this).parent().find('.storeLink').text(),
				storeNumber:$(this).parent().find('.storeLink').attr('id'),
				time:time,
				action:'remove'
			};
			//ajaxCall('FavouriteStoreUpdate','GET',storeInfo,$(this).find('span').text('saved'), alert('you can only save up to three favourites'));
			$.ajax({
				url: '/webapp/wcs/stores/servlet/FavouriteStoreUpdate',
				type: 'GET',
				data: storeInfo,
				dataType:'html',
				success: function(html) {
					checkStore(1,'oldLookup','/webapp/wcs/stores/servlet/InStoreInventoryCheck');
				},
				error: function() {
					//alert('fail');
				}
			});
			trackInstoreInventoryClicks('remove store:'+$(this).parent().find('.storeLink').text());
			return false;
		});
		popup.find('#storeInvCheck2').click(function()
		{
			if ($('#storeInvLookup2').val() == '')
			{
				var alert_msg = 'Please enter your City and Province, Postal Code or Store #:';
				if (eStore.langId == -16)
					alert_msg = 'Veuillez saisissez votre ville et province, code postal ou num\u00E9ro de magasin :';
				alert(alert_msg);
				return false;
			}
			checkStore(1,'storeInvLookup2','/webapp/wcs/stores/servlet/InStoreInventoryCheck');
			trackInstoreInventorySearch();
			return false;
		});
		popup.find('.save').find('a').each(function()
		{
			$(this).click(function()
			{
				var time = new Date().getTime();
				var storeInfo={
					storeName:$(this).parent().find('.storeNameSave').val(),
					storeNumber:$(this).parent().parent().attr('class').replace('tr_','').replace(' btm','').replace(' alt',''),
					time:time,
					action:'add'
				};
				//ajaxCall('FavouriteStoreUpdate','GET',storeInfo,$(this).find('span').text('saved'), alert('you can only save up to three favourites'));
				$.ajax({
					url: '/webapp/wcs/stores/servlet/FavouriteStoreUpdate',
					type: 'GET',
					data: storeInfo,
	   				dataType:'html',
					success: function(html) {
						//var result = html.result;
						//alert(html);
						if (html.match('true'))
						{
							//$(this).find('span').text('saved');
							//eStore.UI.Blocker.clear();
							checkStore(1,'oldLookup','/webapp/wcs/stores/servlet/InStoreInventoryCheck');
						}
						else
						{
							var alert_msg = 'You have already saved three stores.\nPlease remove one of your three saved stores to save this store.';
							if (eStore.langId == -16)
								alert_msg = 'Vous avez d\u00E9j\u00E0 sauvegard\u00E9 trois magasins. \nVeuillez retirer l\'un de ceux sauvegard\u00E9s pour sauvegarder celui-ci.';
							alert(alert_msg);
							return false;
						}
					},
					error: function() {
						//alert('fail');
					}
				});
				trackInstoreInventoryClicks('save to favourites:'+$(this).parent().find('.storeNameSave').val());
				return false;
			});
		});
		popup.find('#storeInvLookup2').bind('keyup',function(){
		   typeAhead('#storeInvLookup2','#typeAheadArea2');
	   	});
		
		popup.find('.storeTbl').find('tr').each(function() {
			if ($(this).hasClass('btm'))
			{
			}
			else
			{
				var storeName = $(this).find('.name').text();
				var stockNumber = $(this).find('.availSpan').text();
				//var prodName = $('.pip-area .prod-info h2').html();
				var prodName = $('.category',document.getElementById('global-crumb-trail')).html();
				//console.log("***** checkStore prodName="+prodName+"; storeName="+storeName+"; stockNumber="+stockNumber);
				trackInstoreInventoryCalls(prodName, storeName, stockNumber);
			}
		});
		stopTimer();
		
		if (ajaxLoader) { ajaxLoader.style.display="none"; }
		popup.open();

		// <accessibility>
		// set focus
		$('#storeInvLookup2').focus();
		// add event listener to the search field
		// makes sure that the tab+shift key goes to the next>> button
		eStore.UI.KeyboardHelper.backwardFocus( $('#storeInvLookup2'), $('#store-link-next') );
		// add event listener to next>> button
		// makes sure that the tab key goes to the search field
		eStore.UI.KeyboardHelper.forwardFocus( $('#store-link-next'), $('#storeInvLookup2') );
		// when the dialog is closed
		popup.find('.close-button').bind( "click", function(e) {
			// make sure to remove the event listeners
			$('#storeInvLookup2').unbind( "keydown" );
			$('#store-link-next').unbind( "keydown" );
			// goto previous input field
			try {
				$('#storeInvLookup').focus();
			} catch(cold) {/*eat soup*/}
		});

		// hides the map once focus to the area is lost
		$('.inventory-page').find('a').bind( "focus", function(){
			var p1 = this.parentNode.parentNode.className;
			var p2 = this.parentNode.parentNode.parentNode.className;
			if( !( p1.indexOf('map-selected') > -1 ) && !( p2.indexOf('map-selected') > -1 ) ) {
				$("#inventory-close-map").click();
			}
		});
		// </accessibility>

	}
	
	//ajaxCall('InStoreInventoryCheck','GET',data, displayInStoreInventoryCheckView, displayError);
	$.ajax({
		url: urlName,
		type: 'GET',
		data: data,
		dataType: 'html',
		success: function(html) {
			//alert(status);
			displayInStoreInventoryCheckView(status,html);
			//console.log(html);
		},
		error: function() {
			alert('fail');
			return false;
		}
	}); 
}


var typeAheadResponseText='';
var enteredVal='';
var reset = false;
var closeTypeAheadArea = true;

bindTypeAhead = function(){ 
	$('#storeInvLookup').bind('keyup',function(){
	   typeAhead('#storeInvLookup','#typeAheadArea');
   });
}

function typeAhead(inputField, outputField)
{
	
	enteredVal = $(inputField).val();
	
	if (enteredVal.match(/[0-9]/))
	{
		return false;
	}
	enteredVal = replaceFrench(enteredVal);
	
	inputText ={
		city: enteredVal,
		langId:   eStore.langId,
		storeId:   10051
	};
	
	if(reset){
		resetSearchCache(outputField);
	}						
	if(enteredVal.length <=1){ 
		resetSearchCache(outputField);
	}else{
		var returnVal = filterByInputedText(enteredVal,inputField,outputField);
		if (returnVal){
			if(enteredVal.length > 1){
				reset = false;
				//ajaxCall('TypeAheadCityProvinceName','GET',inputText, displayTypeAheadView, displayError);
				$.ajax({
				   type: 'GET',
				   url: '/webapp/wcs/stores/servlet/TypeAheadCityProvinceName',
				   data: inputText,
				   dataType:'html',
				   success: function(html){    
						//processAction(rdata);
						typeAheadResponseText =html;
						renderDropDownList(html, inputField, outputField); 
						//alert(html);
				   }, 
				   error: function(){ 
						//errorAction(msg);
						//alert('error');
				   }
				 });
			}
		}
	}
	
	$(outputField).hover(function(){
		closeTypeAheadArea = false;
	},function() {
		closeTypeAheadArea = true;
	});
								  
	$(inputField).blur(function(){
		if (closeTypeAheadArea){
			$(outputField).hide();
		}
	});
	

}
function replaceFrench(value)
{
	var frenchChar = ["\u00C0","\u00C1","\u00C2","\u00C3","\u00C4","\u00C5","\u00C7","\u00C8","\u00C9","\u00CA","\u00CB","\u00CC","\u00CD","\u00CE","\u00CF","\u00D1","\u00D2","\u00D3","\u00D4","\u00D5","\u00D6","\u00D9","\u00DA","\u00DB","\u00DC","\u00DD","\u00E0","\u00E1","\u00E2","\u00E3","\u00E4","\u00E5","\u00E7","\u00E8","\u00E9","\u00EA","\u00EB","\u00EC","\u00ED","\u00EE","\u00EF","\u00F0","\u00F1","\u00F2","\u00F3","\u00F4","\u00F5","\u00F6","\u00F9","\u00FA","\u00FB","\u00FC","\u00FD","\u00FF"];
	var replaceChar = ["A","A","A","A","A","A","C","E","E","E","E","I","I","I","I","N","O","O","O","O","O","U","U","U","U","Y","a","a","a","a","a","a","c","e","e","e","e","i","i","i","i","o","n","o","o","o","o","o","u","u","u","u","y","y"];

	for(var i=0; i<frenchChar.length; i++) {
		/*if (value.indexOf(frenchChar[i])>=0)
		{
			alert(frenchChar[i]);	
		}*/
	  value=value.replace(frenchChar[i],replaceChar[i]);
	  
	} 
	//alert(value);
	return value;
}

resetSearchCache = function(outputField){
	typeAheadResponseText='';
	$(outputField).css('display','none'); 
}


filterByInputedText = function(inValue, inputField, outputField){ 
	if(typeAheadResponseText != '' && inValue.length>1){ 
		renderDropDownList(typeAheadResponseText, inputField, outputField);
		return false;
	}else{
		//alert('filterByInputedText exit with emtpy resposneText');
		return true;
	}
}


renderDropDownList = function(lContent, inputField, outputField){
	var taContent='';
	var listNum = 0;
	//var list = lContent.replace(/<div>/g, '').replace(/<\/div>/g, ';').replace(/ /g,'').replace(/\n/g,'').replace(/\s/g,'');
	 
	var list = lContent.replace(/<div>/g, '').replace(/<\/div>/g, ';').replace(/\n/g,'');  

	list = list.replace(/^\s+|\s+$/g,"");
	list = list.substring(0, list.length-1); 
	
 
	var listArr = list.split(';');
	$.each(listArr, function(i,mListText){  
			//var mListText = mList.replace(/ /g, '');
			var pos1 = mListText.indexOf(enteredVal.substring(0,2).toUpperCase());
			if(i==0 && pos1 != 0){ 
				reset = true;
			} 
			if(!reset){
				var pos = mListText.indexOf(enteredVal.toUpperCase());
				
				if(mListText.indexOf(enteredVal.toUpperCase()) ==0 && listNum < 10){
					listNum++;
					taContent = taContent+'<div class="promptText" ><strong>'+enteredVal.toUpperCase()+'</strong><span>'+mListText.substring(enteredVal.length)+'</span></div>';
				}
			}
	});
	
	if(taContent != '')
		$(outputField).html(taContent).show();
	else
		$(outputField).hide();
	//if (outputField == '#typeAheadArea2' && eStore.langId == -16)
		//$(outputField).css('left','412px');
	//$(outputField).html(taContent).show();

	bindPromptText(inputField, outputField);
}

bindPromptText =function (inputField, outputField){ 
	$('.promptText').hover(function(){
		$(this).css('background-color','#ddd'); 
	},function(){
		$(this).css('background-color','#fff');
	});
	
	$('.promptText').bind('click',function(){ 
		 $(inputField).val($(this).text());
		 $(outputField).css('display','none'); 
	});
}

displayError = function (){
	$('#storeFinder').css('display','block').html('there is an error occurred, please try again later'); 
}
		
function ajaxCall(url,method, iData, processAction, errorAction){ 
	$.ajax({
	   type: method,
	   url: url,
	   data: iData,
	   dataType:'json',
	   success: function(rdata){    
			processAction(rdata);
	   }, 
	   failed: function(msg){ 
			errorAction(msg);
	   }
	 });

}

var timerStarted = false;
function startTimer() { 
	var theStart = new Date().getSeconds();
	timerStarted = true;
	$('#timer').val(theStart);
}

function stopTimer() { 
	if (timerStarted == true) {
		var theVal = new Date().getSeconds();
		if ($('#timer').val() > theVal) {
			theVal = eval(theVal+60) - $('#timer').val();
		} else {
			theVal = theVal - $('#timer').val();
		}
		timerStarted = false;
		var prodName = $('.category',document.getElementById('global-crumb-trail')).html();
		trackInstoreInventoryTime(theVal, prodName);
	}	
	
}

