/**
  *  Global variables.
  *
  **/
var directionDisplay; //  Google Directions display object
var directionsService = new google.maps.DirectionsService(); // Google Directions service object
var map; // Google Map object

var allMarkers = new Array(); // Holds all markers
var allInfoWindows = new Array(); // Holds all info windows

var storeLocator = false; // Is this the store locator page?
var locatorPopup = false; // Is this a popup?
var searchLocatorPopup = false; // Is this a popup on the search page?
var registrationLocatorPopup = false; // Is this a popup on the registration page?
var homepageLocatorPopup = false; // Is this a popup on the home page?
var shoppingListLocatorPopup = false; // Is this a popup on the shopping list page?
var catalogListItemPopup = false; // Is this a microsite page?
var microSite = false; // Is this a microsite page?

var myStoreNum = 9999; // Must be 'number' type
var postalValidate = /^[A-Za-z][0-9][A-Za-z]([ ]?)[0-9][A-Za-z][0-9]$/; // Postal code validation
var defaultPostalCode = "A1A1A1"; // Used to query for my store
var selectedStore = -1; // Used in city type-ahead
var mapZoom = 15; // Zoom level after clicking on a store list numbered icon


/**
  *  $(document).ready()
  *
  *  Checks page type based on specific page elements.
  *  Creates dynamically generated page elements.
  *  Adds listeners for button clicks, form tabbing, and 'Enter' key presses.
  *  Creates loading bar dialog.
  *
  **/
$(document).ready(function() {
	// Fix Safari map issues
	if(navigator.userAgent.match(/Safari/i)) {
		$("#header").css("z-index","auto");
		$("#mainWrap").css("z-index","auto");	
	}	
	// Add autocomplete="off" to city type-ahead
	$('#city').attr("autocomplete","off");
	// Check if Store Locator
	if ($("div#storeLocatorForm").length != 0) {
        storeLocator = true;		
    }
	// Check if homepage popup
    if ($("a#hpStoreLocatorPopUp").length != 0) {
		locatorPopup = true;
        homepageLocatorPopup = true;
		homepageMyStoreCheck();
    }    
	// Check if search popup
    if ($("form#guidedNavePopupFrom").length != 0) {
		$("input#find_postalcode").attr('maxlength','7');
		locatorPopup = true;
        searchLocatorPopup = true;
    }
	// Check it shopping list popup
	if ($("form#shoppingListPopupForm").length != 0) {
		$("input#find_postalcode").attr('maxlength','7');
		locatorPopup = true;
        shoppingListLocatorPopup = true;
    }
	// Check if registration popup
    if ($("form#registration").length != 0 || $("form#settings").length != 0) {
		$("input#reg_postalcode").attr('maxlength','7');
		$("input#reg_postalcode").css('width','60px');
		locatorPopup = true;
        registrationLocatorPopup = true;
        if( $('#settings_page').val() == 'true' ) {
        	displayAccountStore();
        } else {
        	accountMyStoreCheck();
        }
    }
    // Check if catalog listing page
    if ($("form#catalogue_items_form").length != 0) {
        catalogListItemPopup = true;
        locatorPopup = true;
    }
    // Check if micro site
    if ($("div#microSite").length != 0) {
        microSite = true;
    }

    if (!microSite) {
        // Dynamic DOM elements
        $('<span id="directionsTo" style="display:none;"></span>').insertAfter("#storesNear");
        $('<div id="directionsToHeader" class="bodyContent clearfix" style="display:none;"></div>').insertAfter("#storeLocator .header");
        $('<div id="storeLocatorIntro" class="clearfix" style="display:none;"></div>').insertAfter("#storeLocator #map_canvas");
        $('<div class="actions"><a href="#" class="grey-button print"><span class="first-child"><span class="inner">' + storeLocatorText.printButton + '</span></span></a><a href="http://www.addthis.com/bookmark.php?v=250&amp;username=xa-4c3f57c75aba131e" class="addthis_button grey-button share"><span class="first-child"><span class="inner">' + storeLocatorText.shareButton + '</span></span></a></div>').insertAfter("#storeLocator .header h2");
		$('<div id="search_form_error" style="display:none;"></div>').insertAfter("form#guidedNavePopupFrom");
		$('<div id="shoplist_form_error" style="display:none;"></div>').insertAfter("form#shoppingListPopupForm");
        $('<div id="reg_form_error" style="display:none;"></div>').insertAfter("a#reg_find_store");
		$('<div id="noSearchResults" class="bodyContent no_search_results" style="display:none;">' + storeLocatorText.noSearchResults + '</div>').insertAfter("#map_canvas");
		$("#directionsToHeader .to").css("float","left");
		$("#directionsToHeader .from").css("float","left");
		$("#city").css("width","120px");	
		
		// Print buttons
		$("a.print").click(function(){		
			window.print();
		});	

		// Loading bar
		$('<div id="loadingBar" style="display:none;"></div>').insertAfter("#map_canvas");
		$("#loadingBar").dialog({
			autoOpen: false,
			dialogClass: "loadingBarWindow",
			closeOnEscape: false,
			draggable: false,
			width: 220,
			minHeight: 65,
			modal: true,
			buttons: {},
			resizable: false,
			open: function() {
				// Do something
			},
			close: function() {
				// Do something
			}
		}); // end of dialog
		$("#loadingBar").css("background","url(/Images/common/loading-bar.gif) no-repeat");
		$("#loadingBar").css("padding-left","25px");
		$(".loadingBarWindow .ui-dialog-titlebar-close").css("display","none");
				
        // Set header and footer text
        $('<h2 id="title">' + storeLocatorText.storeLocator + '</h2>').insertBefore("#storeLocator .header h2");
        $("#storeLocator .header h2:eq(1)").hide();

        // Set and show intro text
        $("#storeLocatorIntro").html(storeLocatorText.storeLocatorIntro);
        $("#storeLocatorIntro").show();

        // Hide pagination
        $(".pagination.locator").hide();

		// Set maxlength
		$("input#postalcode").attr('maxlength','7');

		// Update button label
		$("#update_store span span.inner").html(storeLocatorText.findButton);

		// Error message
		$('<div id="sl_message" class="error" style="display:none;"></div>').insertAfter("#storeLocatorForm h3");
	}

	$("#driving_directions").addClass("bodyContent");

    // Store Locator Pop-up
    if (locatorPopup) {
		if (homepageLocatorPopup) {
			// Postal Code Dialog
			var postalCodeDialog = ['<div id="postalCodeDialog" style="display:none;">' +
				'<form id="homepagePostalCodeFrom" onsubmit="return false;" action="#">' +
					'<p>' + storeLocatorText.enterYourPostalCode + '</p><br />' +
					'<div style="display:none;" id="homepage_postalcode_form_error" class="error"></div>' +
					'<label for="homepage_postalcode">' + storeLocatorText.postalCode + '</label> ' +					
    				'<input type="text" maxlength="7" size="8" name="homepage_postalcode" id="homepage_postalcode">' +
					'<br /><br />' +
				    '<a href="#" id="homepage_find_store" class="button with-arrow" onclick="return false;"><span class="first-child"><span class="inner">' + storeLocatorText.findMyHomeStore + '</span></span></a>' +
				'</form></div>'].join();				
				
			$(postalCodeDialog).insertAfter("#selectYourStoreHome"); // Homepage
			$(postalCodeDialog).insertAfter("#selectYourStoreDetails"); // Product detail page
		
			$("#postalCodeDialog").dialog({
				autoOpen: false,
				dialogClass: "",
				closeOnEscape: false,
				draggable: false,
				width: 220,
				minHeight: 65,
				modal: true,
				buttons: {},
				resizable: false,
				open: function() {
					// Do something
				},
				close: function() {
					// Do something
					$("#homepage_postalcode").val("");
					$("#homepage_postalcode_form_error").html("");
				}
			}); // end of dialog
			
			// Add popup code to page
			$(storeLocatorPopupForm()).insertAfter("#selectYourStoreHome"); // Homepage
			$(storeLocatorPopupForm()).insertAfter("#selectYourStoreDetails"); // Product detail page

			// Button click handler
			$("a#hpStoreLocatorPopUp").click(function(){				
				openPostalCodeDialog();
				// Update button label
				$("#update_store span span.inner").html(storeLocatorText.findButton);
				return false;
			});
			
			// Button click handler			
			$("a#homepage_find_store").click(function(){
				storeLocatorPopup('homepage');
				return false;
			});
			// 'Enter' key press handler
			$('input#homepage_postalcode').keypress(function(event) {
				if (event.keyCode == '13') {
					storeLocatorPopup('homepage');
					return false;
				}
			});
		}

		if (searchLocatorPopup || shoppingListLocatorPopup || catalogListItemPopup) {
			var popupType = "";

			if (shoppingListLocatorPopup) {
				$(storeLocatorPopupForm()).insertAfter("form#shoppingListPopupForm");	// Add form to shopping list page
				popupType = "shopping_list";
			}
			
			if (searchLocatorPopup) {
				if (!homepageLocatorPopup) {
					$(storeLocatorPopupForm()).insertAfter("form#guidedNavePopupFrom");	// Add popup code to page
				}
				popupType = "store";
			}
			
            if (catalogListItemPopup) {
				$(storeLocatorPopupForm()).insertAfter("form#catalogue_items_form");	// Add popup code to page
				popupType = "catalog";
			}

			// Button click handler
			$("a#find_store").click(function(){
				storeLocatorPopup(popupType);
				return false;
			});

			// 'Enter' key press handler
			$('input#find_postalcode').keypress(function(event) {
				if (event.keyCode == '13') {
					storeLocatorPopup(popupType);
					return false;
				}
			});
		}

		if (registrationLocatorPopup) {
			// Add popup code to page
			$(storeLocatorPopupForm()).insertAfter("a#reg_find_store");

			// Button click handler
			$("a#reg_find_store").click(function(){
				storeLocatorPopup('registration');
				return false;
			});

			// 'Enter' key press handler
			$('input#reg_postalcode').keypress(function(event) {
				if (event.keyCode == '13') {
					storeLocatorPopup('registration');
					return false;
				}
			});
		}
    }

	if (microSite) {
		$('#start_1').keypress(function(event) {
			if (event.keyCode == '13') {
				// Show loading screen
				openLoadingBar();
				calcRoute(1);
			}
		});
	}
	
	// Check for Postal Code in URL
	var postalCodeParam = getParam('setPostalCode');
	
	if (postalCodeParam != "") {
		// Clean postal code
		var postalCode = unescape(postalCodeParam);
		postalCode = postalCode.trim();
		postalCode = postalCode.replace("+","");
		postalCode = postalCode.replace(/\s/g,"");
		// Set postalCode cookie
		document.cookie = "postalCode=" + escape(postalCode) + "; path=/";
		// Delete city and province cookies
		delete_cookie("city");
		delete_cookie("province");
		// Set postal code in form
		$("#postalcode").val(postalCode);
		// Initialize
		initialize();
		// Show loading screen
		openLoadingBar();
		// Search stores
		updateStores();
	}

	/**
	  *
	  * City type-ahead
	  *
	  **/
	// Add the listing div
	if (storeLocator || locatorPopup) {
		if (!microSite) {
			$('<div id="cityTypeAhead" class="locatorTypeAhead clearfix" style="display:none;"><ul id="cities"></ul></div>').insertAfter("#city");		
	
			// Query the type-ahead service on keyup
			$("#city").keyup(function(event) {
				if ($("#city").val().length >= 2) {
					if ((event.keyCode != '38') && (event.keyCode != '40') && (event.keyCode != '13')) {
						$.getJSON('/' + storeLocatorText.lang + '/loc/getCityNames?c=' + $("#city").val() + '&p=' + $("#province").val(), function(data) {
							var cityName = "";
							var cityNameArray = new Array();
							var splitOp = "";
		
							selectedStore = -1;
		
							if(data.cities != "") {
								// Clear the listing on each new query
								$("#cityTypeAhead ul#cities").empty();
		
								for (var i = 0; i < data.cities.length; i++) {
									cityName = "";
		
									if (data.cities[i].indexOf("-") != -1) {
										splitOp = "-";
									} else {
										splitOp = " ";
									}
		
									cityNameArray = data.cities[i].split(splitOp);
		
									// camelCase city names
									for (var j = 0; j < cityNameArray.length; j++) {
										cityName += cityNameArray[j].substr(0,1).toUpperCase() + cityNameArray[j].substr(1).toLowerCase() + splitOp;
									}
		
									$("#cityTypeAhead ul#cities").append('<li class="typeAheadCity" id="city_' + i + '" onclick="typeAheadExecute(' + i + ');">' + cityName.substr(0,cityName.length-1) + '</li>');
								}
		
								// Show city listing
								$("#cityTypeAhead").show();
							} else {
								// Hide city listing
								if ($("#cityTypeAhead").css("display") == "block") {
									$("#cityTypeAhead").hide();
									selectedStore = -1;
								}
							}						
						});
					} else if (event.keyCode == '40') {
						// Arrow down key press
						if ($("#cityTypeAhead").css("display") == "none") {
							selectedStore = -1;
						} else {
							// Don't allow user to go past last store in list
							if (selectedStore != $("#cityTypeAhead ul#cities li").size()-1) {
								// Increment selected store num
								selectedStore++;
							}
							//Set list item background color
							$(".typeAheadCity").removeClass("active");
							$("#city_" + selectedStore).addClass("active");
	
							// Set city input box value
							$("#city").val($("#city_" + selectedStore).html());
						}
					} else if (event.keyCode == '38') {
						// Arrow up key press
						if ($("#cityTypeAhead").css("display") == "none") {
							selectedStore = -1;
						} else {
							// Don't allow user to go past first store in list
							if (selectedStore >= 1) {
								// Decrement selected store num
								selectedStore--;
							}
							//Set list item background color
							$(".typeAheadCity").removeClass("active");
							$("#city_" + selectedStore).addClass("active");
							// Set city input box value
							$("#city").val($("#city_" + selectedStore).html());
						}
					} else if (event.keyCode == '13') {
						// 'Enter' key press
						// Show the loading dialog
						openLoadingBar();
						// Get all stores
						updateStores();
					}
				} else {
					// Hide if < 2 characters
					$("#cityTypeAhead").hide();
				}
			});
		}
	}

	// Hide type-ahead listing on window click (when the user clicks somewhere else in the browser)
	$("html,body").click(function() {
		$("#cityTypeAhead").hide();
    });

	// Hide type-ahead listing on window blur (when the browser loses focus)
	$(window).blur(function() {
		$("#cityTypeAhead").hide();
    });

	// Find/Update button click handler
	$("#update_store").click(function(e) {
		// Show loading screen
		openLoadingBar();
		// Postal Code cookie
		if ($("#postalcode").val() != "") {
			// Set postalCode cookie
			document.cookie = "postalCode=" + escape($("#postalcode").val()) + "; path=/";
			// Delete province and city cookies
			delete_cookie("city");
			delete_cookie("province");
		}
		// City cookie
		if ($("#city").val() != "") {
			// Set city cookie
			document.cookie = "city=" + escape($("#city").val()) + "; path=/";
 			// Delete postalCode cookie
			delete_cookie("postalCode");
		}
		// Province cookie
		if ($("#province").val() != "") {
			// Set Province cookie
			document.cookie = "province=" + escape($("#province").val()) + "; path=/";
			// Delete postalCode cookie
			delete_cookie("postalCode");
		}
		// Search stores
		updateStores();
		e.preventDefault();
    });

	// 'Enter' key press handler(s)
	$('#postalcode').keypress(function(event) {
		if (event.keyCode == '13') {
			// Show loading screen
			openLoadingBar();
			// Set postalCode cookie
			document.cookie = "postalCode=" + escape($("#postalcode").val()) + "; path=/";
			// Delete city and province cookies
			delete_cookie("city");
			delete_cookie("province");
			// Search stores
			updateStores();
		}
	});
	$('#province').keypress(function(event) {
		if (event.keyCode == '13') {
			// Show loading screen
			openLoadingBar();
			// Set city cookie
			document.cookie = "city=" + escape($("#city").val()) + "; path=/";
			// Set province cookie
			document.cookie = "province=" + escape($("#province").val()) + "; path=/";
			delete_cookie("postalCode");
			// Search stores
			updateStores();
		}
	});
	$('#city').keypress(function(event) {
		if (event.keyCode == '13') {
			// Show loading screen
			openLoadingBar();
			// Set city cookie
			document.cookie = "city=" + escape($("#city").val()) + "; path=/";
			// Set province cookie
			document.cookie = "province=" + escape($("#province").val()) + "; path=/";
			delete_cookie("postalCode");
			// Search stores
			updateStores();
		}
	});

	if (storeLocator || locatorPopup) {
		// Clear form fields on click/focus
		$("#postalcode").click(function(){
			$("#city").val("");
			$("#province").val("");
			$("#cityTypeAhead").hide();
		});
		$("#postalcode").focus(function(){
			$("#city").val("");
			$("#province").val("");
			$("#cityTypeAhead").hide();
		});
		$("#province").click(function(){
			$("#postalcode").val("");
			$("#cityTypeAhead").hide();
		});
		$("#province").focus(function(){
			$("#postalcode").val("");
			$("#cityTypeAhead").hide();
		});
		$("#city").click(function(){
			$("#postalcode").val("");
			$("#cityTypeAhead").hide();
		});
		$("#city").focus(function(){
			$("#postalcode").val("");
			$("#cityTypeAhead").hide();
		});
	}

	if (locatorPopup) {
        // Don't initialize if popup
    } else if (storeLocator || microSite){
        initialize();
		if (storeLocator) {
			// Check for postal code cookie
			if (get_cookie('postalCode') != null) {
				// Set postal code value from cookie
				var postalCode = get_cookie('postalCode').replace(/["']{1}/gi,'');
				$("#postalcode").val(postalCode);
				// Clear other form elements
				$("#city").val("");
				$("#province").val("");
				// Show loading screen
				openLoadingBar();
				// Commence search
				updateStores();
			}
			// Check for city/province cookie
			if (get_cookie('city') != null && get_cookie('province') != null) {
				// Set city and province value from cookie
				var city = get_cookie('city');
				var province = get_cookie('province');
				$("#city").val(city);
				$("#province").val(province);
				// Clear other form elements
				$("#postalcode").val("");
				// Show loading screen
				openLoadingBar();
				// Commence search
				updateStores();
			}
		}
    } else {
		// Not a store lcoator page type
	}
});


/**
  *  initialize()
  *
  *  Initializes and creates the Google Map object.
  *  Adds marker to Microsite map.
  *
  **/
function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();

    if (microSite) {
        var lat = $("#lat").html();
        var lng = $("#lng").html();
        var opts = {
            center: new google.maps.LatLng( lat, lng ),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            zoom: mapZoom
        };
    } else {
        var opts = {
            center: new google.maps.LatLng( 59, -100 ),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            zoom: 3
        };
    }

    map = new google.maps.Map( document.getElementById("map_canvas"), opts );

    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("driving_directions"));

    // Add marker if micro site
    if (microSite) {
        var center = new google.maps.LatLng( lat, lng );
        addSingleMarker(map, center);
		microSiteMyStoreCheck();
    }
}


/**
  *  updateStores()
  *
  *  Called when "Find" button is clicked.
  *  Clears any driving directions dialog elements.
  *  Calls getStores().
  *
  **/
function updateStores() {
	// Empty/remove elements on update
	$("#directionsToHeader").empty();
	$("#storeList").empty();
	$(".popupIntroText").remove();

	// jQuery UI elements
	$(".dialog-ui").remove();
	$("#jsts").remove();

	// Hide directions, if visible
	$("#driving_directions").hide();
	clearRoute();

	// Hide type-ahead city listing
	$("#cityTypeAhead").hide();
	selectedStore = -1;	

	// Get stores
	getStores();
}


/**
  *  getStores()
  *
  *  Gets JSON data object via web service and send to getHandler().
  *
  *
  **/
function getStores(){
    var postalCode = $("#postalcode").val();
    var city = $("#city").val();
    var province = $("#province").val();

    if( postalCode != ""){
        if (postalValidate.test(postalCode)) {
			postalCode = postalCode.trim();
		    escapedPostalCode = escape(postalCode);

            $.getJSON('/' + storeLocatorText.lang + '/loc/stores.htm?pc=' + escapedPostalCode +'&o=0', getHandler());
            $("#storesNear").html("<span style='text-transform:uppercase;'>" + postalCode + "</span>");

			// Hide error message, if any
			$("#storeLocatorForm #sl_message").hide();
			$("#storeLocatorForm #sl_message").html("");

			// Update header
			$("#storeLocator .header h2#title").hide();
			$("#storeLocator .header h2:eq(1)").show();

			// Hide intro text
			$("#storeLocatorIntro").hide();
        } else {
            // Invalid postal code
			$("#storeLocatorForm #sl_message").html(storeLocatorText.invalidPostalCodeMessage);
			$("#storeLocatorForm #sl_message").show();
            resetMap();
        }
    } else if (city != "" && province != "") {
		city = city.trim();
		//escapedCity = escape(city); // uri encode 
		encodedCity = encodeURIComponent(city);
	    province = escape(province.trim());

        $.getJSON('/' + storeLocatorText.lang + '/loc/stores.htm?p='+province+'&c='+encodedCity+'&o=0', getHandler());
        $("#storesNear").html(city + ", <span style='text-transform:uppercase;'>" + province + "</span>");

		// Hide error message, if any
		$("#storeLocatorForm #sl_message").hide();
		$("#storeLocatorForm #sl_message").html("");

		// Update header
		$("#storeLocator .header h2#title").hide();
		$("#storeLocator .header h2:eq(1)").show();

		// Hide intro text
		$("#storeLocatorIntro").hide();
    } else {
		// Blank form
		$("#storeLocatorForm #sl_message").html(storeLocatorText.emptyFormMessage);
		$("#storeLocatorForm #sl_message").show();
		resetMap();
	}
}


/**
  *  getHandler()
  *
  *  Sends the data object to parseData().
  *
  *  @param {Number} page The current page of stores.
  *
  **/
function getHandler() {
    return function(data) {
        parseData(data);
    };
}


/**
  *  parseData()
  *
  *  Parses store data object.
  *  Calls addHTML() and addMarker() to add store items to listing and markers to map.
  *  If no stores are found, the map is reset via resetMap().
  *
  *  @param {Obj} data Store data object.
  *
  **/
function parseData(data) {
	var bounds = new google.maps.LatLngBounds();
	var count = 0;

	// Empty store list for each page
    $("#storeList").empty();

	if (data.stores) {
		if (data.total != 0) {
			// Store count
			var storeCount = data.stores.length;
			var totalStores = data.stores.length;
			var j = 0;				

			// Remove existing markers and info windows, if any.
			while( allMarkers.length > 0 ) {
				var marker = allMarkers.shift();
				marker.setMap( null );
			}
			while( allInfoWindows.length > 0 ) {
				var infowindow = allInfoWindows.shift();
			}

			// Check for set store
			if(data.mystore) {
				// Set lat and long vars for this store
				var mystoreHHLat = data.mystore[9];
				var mystoreHHLng = data.mystore[10];

				// Create Google lat/long object
				var mystoreHHLatLng = new google.maps.LatLng( mystoreHHLat, mystoreHHLng );

				// Add Store Item to listing and marker to map
				addHTML(myStoreNum, data.mystore, 0);
				addMarker(map, mystoreHHLatLng, data.mystore, myStoreNum);

				// Display label is store listing
				$("#myStore_" + myStoreNum).html(storeLocatorText.myStore);
				$("#myStore_" + myStoreNum).show();				

				count++;							
			}
			
			for (var i = 0; i < storeCount; i++) {
				var storeId = data.stores[i][0].replace("store", "");								

				// Set lat and long vars for this store
				var storeLat = data.stores[i][9];
				var storeLng = data.stores[i][10];

				// Create Google lat/long object
				var storeLatLng = new google.maps.LatLng( storeLat, storeLng );

				// Add this stire to map boundary
				bounds.extend( storeLatLng );

				// Add Store marker to the map
				addMarker( map, storeLatLng, data.stores[ i ], (i + 1));

				// Add Store Item to the listing
				addHTML((i + 1),  data.stores[ i ], i+count);
			}
			
			// Hide error message
			$("#noSearchResults").hide();

			if (locatorPopup) {
				$("#totalStores").show();
				$("#storesNear").show();
			}	
			
			// Update button label
			$("#update_store span span.inner").html(storeLocatorText.update);

			// Update header
			$("span#totalStores").html("<strong>" + totalStores + "</strong> " + storeLocatorText.storesNear);

			// Show store list
			$("#storeList").show();
			
			// Hide city listing
			$("#cityTypeAhead").hide();

			// Set map boundary
			map.fitBounds( bounds );

			// Close waiting screen
			closeLoadingBar();
		} else {
			// No stores found, "reset" the map
			resetMap();
		}
	} else {
        // No stores found, "reset" the map
        resetMap();
    }
}


/**
  *  addMarker()
  *
  *  Adds store marker to map.
  *  Adds info windows for each marker.
  *
  *  @param {GMap} map Google map object.
  *  @param {LatLng} location The lat/long of current store.
  *  @param {Obj} store Data object of current store.
  *  @param {Number} num The number of current store on current page.
  *
  **/
function addMarker(map, location, store, num) {
    var storeDistance = store[1];
    var storeName     = store[2];
    var storeAddress  = store[3];
    var storeCity     = store[4];
    var storeProvince = store[5];
    var storePostal   = store[6];
	var storePhone    = store[7];
	var storeType     = store[8];
	var storeWebsite  = store[11];

	
	var storeTypeIcon = storeLocatorText.HF;
	var storeTypeIconWidth = storeLocatorText.HF_w;
	var storeTypeIconHeight = storeLocatorText.HF_h;
	var storeNameOutput = "";

	// Numbered icons
	if (num == myStoreNum) {
		var icon = new google.maps.MarkerImage('/Images/icons/hh-closest.png',
			new google.maps.Size(37, 29),
			new google.maps.Point(0,0),
			new google.maps.Point(37,15)
		);
	} else {
		var icon = new google.maps.MarkerImage('/Images/icons/' + num + '.png',
			new google.maps.Size(38, 29),
			new google.maps.Point(0,0),
			new google.maps.Point(38,15)
		);
	}

    // Create the marker
    var storeMarker = new google.maps.Marker({
        position: location,
        map: map,
        icon: icon,
        title: storeName
    });

	if (storeWebsite) {
		storeNameOutput = '<a class="storeNameLink" href="/' + storeWebsite + '">' + stripslashes(storeName) + '</a>';
	} else {
		storeNameOutput = stripslashes(storeName);
	}

	// Set the infowindow content
	var storeInfo = ['<div class="storeInfoWindow">' +
					'<img src="/Images/store-locator/' + storeTypeIcon + '" width="' + storeTypeIconWidth + '" height="' + storeTypeIconHeight + '" alt="' + stripslashes(storeName) + '">' +
					'<p><strong>' + storeNameOutput + '</strong></p>' +
					'<p>' + storeAddress + '<br />' +
					storeCity + ', ' + storeProvince + '<br />' +
					storePostal + '<br />' +
					formatPhoneNumber(storePhone) + '</p>'].join();

	// Create the infowindow
	var infowindow = new google.maps.InfoWindow({
		content: storeInfo
	});

	// Clear all info windows if user closes one
	google.maps.event.addListener(infowindow, 'closeclick', function() {
		clearInfoWindows();
	});

	// Show the infowindow on click
	google.maps.event.addListener(storeMarker, 'click', function() {
		// Close all other info windows
		clearInfoWindows();
		// Open this info window
		infowindow.open(map, storeMarker);
	});

	// Add info window to array
	allInfoWindows.push( infowindow );

	// Add marker to array
    allMarkers.push( storeMarker );
}


/**
  *  addSingleMarker()
  *
  *  Adds store marker to map.
  *
  *  @param {GMap} map Google map object.
  *  @param {LatLng} location The lat/long of current store.
  *
  **/
function addSingleMarker(map, location) {
    // Custom icon
    var icon = new google.maps.MarkerImage('/Images/icons/hh-closest.png',
        new google.maps.Size(38, 29),
        new google.maps.Point(0,0),
        new google.maps.Point(38,15)
    );

    // Create the marker
    var storeMarker = new google.maps.Marker({
        position: location,
        map: map,
        icon: icon
    });

	// Add marker to array
    allMarkers.push( storeMarker );
}


/**
  *  addHTML()
  *
  *  Created and adds store data to store listing item.
  *
  *  @param {Number} countOutput Count value of current store.
  *  @param {Obj} store Data object of current store.
  *  @param {Number} count The number of stores on current page. Used for store item
  *  click function.
  *
  **/
function addHTML(countOutput, store, count){
    var storeId       = store[0].replace("store", "");
	var storeNumber   = storeId.replace("-", "");
    var storeName     = store[2];
    var storeAddress  = store[3];
    var storeCity     = store[4];
    var storeProvince = store[5];
    var storePostal   = store[6];
    var storePhone    = store[7];
    var storeType     = store[8];
    var storeLat      = store[9];
    var storeLng      = store[10];
    var storeWebsite  = store[11];
	var storeFlyer    = store[12];

	var appliances = store[ 12 ];
	var combo      = store[ 13 ];
	var elec       = store[ 14 ];
	var sleep      = store[ 15 ];

	var storeListItem = "";
	var setStoreOutput = "";
    var storeWebsiteOutput = "";
    var drivingDirectionsOutput = "";
    var flyerOutput = "";
	var myStoreOutput = "";
	var block = "";
	var position = "";
	var positionOutput = "";
	var distanceOutput = "";
	var storeNameOutput = "";

	var storeTypeIcon = storeLocatorText.HF;
	var storeTypeIconWidth = storeLocatorText.HF_w;
	var storeTypeIconHeight = storeLocatorText.HF_h;
		
    if( storePhone && storePhone.length == 10 ) {
        storePhone = formatPhoneNumber(storePhone);
    }

	if (countOutput == myStoreNum) {
		block = "block5";
		position = "HH";
		positionClass = "positionHH";	
	} else {
		block = "block4";
		position = countOutput;
		positionClass = "position";
	}	
	
	if (storeWebsite) {
		storeNameOutput = '<a class="storeNameLink" href="/' + storeWebsite + '">' + stripslashes(storeName) + '</a>';
	} else {
		storeNameOutput = stripslashes(storeName);
	}

    if (!locatorPopup) {
		// Check for website
        if (storeWebsite && storeWebsite != "")
            storeWebsiteOutput = '<li><a class="button with-logo" href="/' + storeWebsite + '"><span class="first-child"><span class="inner">' + storeLocatorText.viewWebsite + '</span></span></a></li>';

		// Show driving directions link if not popup
		drivingDirectionsOutput = '<li><a href="#" class="links" onclick="openDrivingDirectionsDialog('+countOutput+'); return false;">' + storeLocatorText.drivingDirections + '</a></li>';
    }
    
    var featBlock = "";
    
    if( appliances != "" ) {
    	featBlock += "<img src=\"" + appliances + "\" alt=\"" + storeLocatorText.storeTypeAppliances + "\" title=\"" + storeLocatorText.storeTypeAppliances + "\" />";
    }
    if( combo != "" ) {
    	featBlock += "<img src=\"" + combo + "\" alt=\"" + storeLocatorText.storeTypeCombo + "\" title=\"" + storeLocatorText.storeTypeCombo + "\" />";
    }
    if( elec != "" ) {
    	featBlock += "<img src=\"" + elec + "\" alt=\"" + storeLocatorText.storeTypeElec + "\" title=\"" + storeLocatorText.storeTypeElec + "\" />";
    }
    if( sleep != "" ) {
    	featBlock += "<img src=\"" + sleep + "\" alt=\"" + storeLocatorText.storeTypeSleep + "\" title=\"" + storeLocatorText.storeTypeSleep + "\" />";
    }    
   
    if( featBlock != "" ) {
    	featBlock = "<div class=\"storeFeatures\">" + featBlock + "</div>";
    }
    
	storeListItem = ['<li id="store_details_' + countOutput + '" class="store_item list_item_' + count + ' clearfix">' +
						'<div class="' + positionClass + '"><a href="#" class="infoWindowLink" id="infoWindoLink' + countOutput + '">' + position + '</a></div>' +
						'<div class="block1">' +
							'<span class="logo">' +
								'<img src="/Images/store-locator/' + storeTypeIcon + '" width="' + storeTypeIconWidth + '" height="' + storeTypeIconHeight + '" alt="' + stripslashes(storeName) + '" />' +
								'</span>' +	featBlock +								
						'</div>' +
						'<div class="block2">' +
							'<address>' +
								'<span class="storename">' + storeNameOutput + '</span><br />' +
								stripslashes(storeAddress) + '<br />' +
								stripslashes(storeCity) + ', ' + stripslashes(storeProvince) + '<br />' +
								storePostal + '<br />' +
								storePhone +
							'</address>' +
						'</div>' +
						'<div class="block3">' +
							'<ul>' +
								'<li id="setStoreLink_' + countOutput + '" class="setStoreLinkItem"><a href="#" class="button with-check" onclick="setStore(\'' + storeId + '\', \'' + countOutput + '\'); return false;"><span class="first-child"><span class="inner">' + storeLocatorText.setStore + '</span></span></a></li>' +
								'<li id="myStoreLink_' + countOutput + '" class="myStoreLinkItem" style="display:none;"><a class="button with-logo" href="#" onclick="return false;"><span class="first-child"><span class="inner"></span></span></a></li>' +
								storeWebsiteOutput +
								drivingDirectionsOutput +
								'<li><a href="' + storeLocatorText.eflyerURL + '?StoreNumber=' + storeId.replace( "-", "" ) + '" class="links">' + storeLocatorText.viewLocalEflyer + '</a></li>' +
							'</ul>' +
						'</div>' +
						'<div id="myStore_' + countOutput + '" class="' + block + '" style="display:none;"></div>' +
					'</li>' +
					'<div class="driving_directions_form form_item_' + count + '" id="driving_directions_form_'+countOutput+'" style="display:none;" title="' + storeLocatorText.yourAddress + '">' +
						'<form action="#" method="post" onsubmit="return false;">' +
							'<p>' + storeLocatorText.yourAddressText + '</p>' +
							'<input type="text" class="start_address" name="start" id="start_'+countOutput+'" value="" />' +
							'<div id="driving_directions_form_error_'+countOutput+'" style="display:none;"></div>' +
							'<br /><br />' +
					'		<p><a id="calculateRoute" class="button with-arrow" href="#" onclick="calcRoute('+countOutput+'); return false;"><span class="first-child"><span class="inner">' + storeLocatorText.getDirectionsButton + '</span></span></a>&nbsp;&nbsp;&nbsp;<a class="closelink" href="#" onclick="$(\'#driving_directions_form_'+countOutput+'\').dialog(\'close\'); return false;">' + storeLocatorText.closeButton + '</a></p>' +
							'<input type="hidden" name="selectedStoreNum" id="selectedStoreNum" value="'+countOutput+'" />' +
							'<input type="hidden" name="storeId" id="storeId" class="store_id_' + count + '" value="'+storeNumber+'" />' +
							'<input type="hidden" name="end" id="end_'+countOutput+'" value="' + stripslashes(storeAddress) + ', ' + stripslashes(storeCity) + ' ' + stripslashes(storeProvince) + ', ' + storePostal + '" />' +
							'<input type="hidden" name="storeName" id="storeName_'+countOutput+'" value="' + stripslashes(storeName) + '" />' +
							'<input type="hidden" name="storeAddress" id="storeAddress_'+countOutput+'" value="' + stripslashes(storeAddress) + '" />' +
							'<input type="hidden" name="storeCity" id="storeCity_'+countOutput+'" value="' + stripslashes(storeCity) + '" />' +
							'<input type="hidden" name="storeProvince" id="storeProvince_'+countOutput+'" value="' + stripslashes(storeProvince) + '" />' +
							'<input type="hidden" name="storePostal" id="storePostal_'+countOutput+'" value="' + storePostal + '" />' +
							'<input type="hidden" name="storePhone" id="storePhone_'+countOutput+'" value="' + storePhone + '" />' +
							'<input type="hidden" name="storeIcon" id="storeIcon_'+countOutput+'" value="' + storeTypeIcon + '" />' +
							'<input type="hidden" name="storeIconW" id="storeIconW_'+countOutput+'" value="' + storeTypeIconWidth + '" />' +
							'<input type="hidden" name="storeIconH" id="storeIconH_'+countOutput+'" value="' + storeTypeIconHeight + '" />' +
							'<input type="hidden" name="storeCountOutput" id="storeCountOutput_'+count+'" value="' + countOutput + '" />' +
						'</form>' +
					'</div>'].join();

    $("#storeList").append(storeListItem);
	$("span.storename").css("padding-right","10px");

	$('#start_' + countOutput).keypress(function(event) {
		if (event.keyCode == '13') {
			calcRoute(countOutput);
		}
	});	
	
	// Update for my store
	if (countOutput == myStoreNum) {
		setStoreOutput = '';
		$("#myStore_" + countOutput).html(storeLocatorText.myStore);
		$("#myStore_" + countOutput).show();
		$("#setStoreLink_" + countOutput).hide();
		// Show "my store" button
		$("#myStoreLink_" + countOutput + " a span.inner").html(storeLocatorText.yourHomeStore);
		$("#myStoreLink_" + countOutput).show();
		$("#myStoreLink_" + countOutput + " a").css("cursor","default");
		$("#myStoreLink_" + countOutput + " a span.inner").css("cursor","default");
		$("#myStoreLink_" + countOutput + " a span.inner").css("width","110px");
	} else {
		$("#myStore_" + countOutput).hide();
		$("#setStoreLink_" + countOutput).show();
	}

	// Open store info window on store position # click
	$('#infoWindoLink' + countOutput).click(function(){
		showInfoWindow(countOutput, count, storeLat, storeLng);
		return false;
	});
}


/**
  *  showInfoWindow()
  *
  *  Shows store info window on map.
  *
  *  @param {Number} countOutput Count value of current store.
  *  @param {Number} count The number of stores on current page. Used for store item
  *  click function.
  *  @param {Number} blockNum Block class number within store list item.
  *
  **/
function showInfoWindow(countOutput, count, storeLat, storeLng) {
	// Clear any info windows
	clearInfoWindows();
	// Zoom
	map.setZoom(mapZoom);
	if (locatorPopup) {
		// Only show marker
		var center = new google.maps.LatLng(storeLat, storeLng)
		map.setCenter(center);
	} else {
		// Open the info window
		allInfoWindows[count].open(map, allMarkers[count]);
	}
	if (!locatorPopup) {
		// Scroll to the top of the page
		toTop();
	}
}


/**
  *  storeLocatorPopup()
  *
  *  Creates store locator popup dialog.
  *  Initializes map on popups via initialize().
  *  Adds stores to store list on popup via updateStores().
  *
  *  @param {String} page Page type of calling page.
  *
  **/
function storeLocatorPopup(page) {
    var postalCode = "";
    var formError = "";

    switch(page) {
	case 'store':
		postalCode = $("input#find_postalcode").val();
		formError = "#search_form_error";
		break;
	case 'registration':
		postalCode = $("input#reg_postalcode").val();
		formError = "#reg_form_error";
		break;
	case 'shopping_list':
		postalCode = $("input#find_postalcode").val();
		formError = "#shoplist_form_error";
		break;
        case 'catalog':
        postalCode = $("input#find_postalcode").val();
		formError = "#catalogue_items_form_error";
		break;
	case 'homepage':
		postalCode = $("input#homepage_postalcode").val();
		formError = "#homepage_postalcode_form_error";
		break;
	default:
		break;
    }

	// Registration/search page require an initial postal code
    if (postalCode != "") {
        if (postalValidate.test(postalCode)) {
            $(formError).hide();
            $(formError).html("");
			
			// Set postalCode cookie
			document.cookie = "postalCode=" + escape(postalCode) + "; path=/";
			// Delete city and province cookies
			delete_cookie("city");
			delete_cookie("province");

            // Show the locator
            $("#storeLocatorPopup").dialog({
                title: storeLocatorText.selectYourHomeHardware,
                autoOpen: false,
                height: 525,
                width: 875,
                modal: true,
                close: function() {
                    // do something on close
                }
            });

            $('#storeLocatorPopup').dialog('open');
            $("#postalcode").val(postalCode);

            // Load the map
            initialize();

			// Update store list
            updateStores();
			
			$("#homepage_postalcode").val("");
			$("#homepage_postalcode_form_error").html("");
			closePostalCodeDialog();
        } else {
            $(formError).html("<strong>" + storeLocatorText.invalidPostalCode + "</strong>");
            $(formError).show();
        }
    } else {
        $(formError).html("<strong>" + storeLocatorText.blankPostalCode + "</strong>");
        $(formError).show();
    }
}


/**
  *  storeLocatorPopupForm()
  *
  *  Creates store locator popup form.
  *
  *  @return {String} storeLocatorPopupForm Form popup.
  *
  **/
function storeLocatorPopupForm() {
	var storeLocatorPopupForm = ['<div id="storeLocatorPopup" style="display:none;">'+
		'<div class="header clearfix">'+
			'<div id="storeLocatorIntro" class="bodyContent clearfix" style="display:none;"></div>' +
			'<div class="pagination locator">'+
				'<div class="bodyContent"><span id="totalStores"></span> <span id="storesNear"></span></div>'+
			'</div>'+
		'</div>'+
		'<div class="form">'+
			'<div id="map_canvas" style="width:329px; height:261px;" class="clearfix"></div>'+
			'<div id="storeLocatorForm" class="clearfix">'+
				'<h3>' + storeLocatorText.changeYourArea + '</h3>'+
				'<div id="sl_message" class="error" style="display:none;"></div>' +
				'<form action="#" method="post" autocomplete="off" onsubmit="return false;">'+

					'<div class="postalcode">'+
						'<label>' + storeLocatorText.postalCode + '</label>'+
						'<input type="text" name="test_postalcode" id="postalcode" value="" maxlength="7" /> ' + storeLocatorText.textOr +
					'</div>'+

					'<div class="province">'+
						'<label>' + storeLocatorText.province + '</label>'+
						'<select id="province" name=""><option value="">--</option><option value="ab">AB</option><option value="bc">BC</option><option value="mb">MB</option>  <option value="nb">NB</option><option value="nl">NL</option><option value="ns">NS</option><option value="nt">NT</option><option value="nu">NU</option><option value="on">ON</option><option value="pe">PE</option><option value="qc">QC</option><option value="sk">SK</option><option value="yt">YT</option></select>'+
					'</div>'+
					'<div class="city">'+
						'<label>' + storeLocatorText.city + '</label>'+
						'<input type="text" name="city" id="city" value="" />'+
					'</div>'+
					'<a id="update_store" class="button with-arrow" href="#">'+
						'<span class="first-child"><span class="inner">' + storeLocatorText.update + '</span></span>'+
					'</a>'+
				'</form>'+
			'</div>'+
		'</div>'+
		'<div id="noSearchResults" class="bodyContent no_search_results" style="display:none;">' + storeLocatorText.noSearchResults + '</div>' +
		'<ol id="storeList" class="clearfix"></ol>' +
		'</div>'].join();

	return storeLocatorPopupForm;
}


/**
  *  openDrivingDirectionsDialog()
  *
  *  Creates and opens driving directions dialog.
  *
  *  @param {Number} countOutput Count value of current store.
  *
  **/
function openDrivingDirectionsDialog(countOutput) {
	if (!microSite) {
	    $('#driving_directions_form_' + countOutput).dialog('destroy');
	} else {
		$("#start_1").val("");
	}

    // Directions form settings
    $("#driving_directions_form_" + countOutput).dialog({
            autoOpen: false,
            height: 175,
            width: 300,
            modal: true,
            close: function() {
                // do something
            }
        });

	// Open the dialog
    $('#driving_directions_form_' + countOutput).dialog('open');

	// Hide any errors when user clicks on text element
    $(".start_address").focus(function(){
        $("#driving_directions_form_error" + countOutput).hide();
    });
}


/**
  *  calcRoute()
  *
  *  Create the driving directions instructions via Google Directions service.
  *
  *  @param {Number} countOutput Count value of current store.
  *
  **/
function calcRoute(countOutput) {
    var directionsToHeader = "";
	var start = "";
	var end = "";

	// Set map to Google map object
	directionsDisplay.setMap(map);

	// Check for popup form or change form
	if ($("#start_change").length == 0) {
	    start = $("#start_"+countOutput).val();
	} else {
		start = $("#start_change").val();
	}
    end = $("#end_"+countOutput).val();

    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    // Display directions
    directionsService.route(request, function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            // Remove markers
            clearMarkers();

            // Hide error, store list, pagination
            $("#driving_directions_form_error_" + countOutput).hide();
            $("#storeList").hide();
            $(".pagination.locator").hide();

            // Show directions
            $("#driving_directions").show();

			// Check if this is micro site page
            if (!microSite) {
                // Update header
                $("#totalStores").hide();
                $("#storesNear").hide();
                $("#directionsTo").show();
                $("#directionsTo").html("<strong>" + storeLocatorText.directionsTo + "</strong> " + end);

                // Header
                directionsToHeader = ['<div class="from"><strong>' + storeLocatorText.from + '</strong> ' + storeLocatorText.addressOrPostalcode + '<br /><br />' +
					'<input type="text" name="start" id="start_change" class="start_address" value="' + start + '" />' +
					'<a id="submit_change" class="button with-arrow" href="#" onclick="calcRoute(' + countOutput + '); return false;"><span class="first-child"><span class="inner">' + storeLocatorText.changeButton + '</span></span></a></div>' +
					'<div class="to"><strong>' + storeLocatorText.to + '</strong><br /><br /><span class="logo"><img src="/Images/store-locator/' + $("#storeIcon_"+countOutput).val() + '" width="' + $("#storeIconW_"+countOutput).val() + '" height="' + $("#storeIconH_"+countOutput).val() + '" alt="' + $("#storeName_"+countOutput).val() + '" /></span><br />' +
					'<strong>' + $("#storeName_"+countOutput).val() + '</strong><br />' +
					$("#storeAddress_"+countOutput).val() +'<br />' +
					$("#storeCity_"+countOutput).val() +', ' + $("#storeProvince_"+countOutput).val() +'<br />' +
					$("#storePostal_"+countOutput).val() +'<br />' +
					$("#storePhone_"+countOutput).val() + '</div>'].join();

                $("#directionsToHeader").html(directionsToHeader);
                $("#directionsToHeader").show();
            }

			// 'Enter' key press handler
			$('#start_change').keypress(function(event) {
				if (event.keyCode == '13') {
					calcRoute(countOutput);
				}
			});

			// Close the driving directions dialog
            $('#driving_directions_form_'+countOutput).dialog('close');

			if (!microSite) {
				// Bizarre bug with jquery ui dialog which creates multiple instances of a dialog on click...
				// Solution: rename id of dialog after use as to not reuse same form id
				$('#driving_directions_form_'+countOutput).attr('id','driving_directions_form_closed');
				$('#start_'+countOutput).attr('id','start_closed');
			}

			// Display the driving directions
            directionsDisplay.setDirections(result);

			// Close waiting screen
			closeLoadingBar();
        } else {
            $("#driving_directions_form_error_"+countOutput).html(storeLocatorText.locationNotFound);
            $("#driving_directions_form_error_"+countOutput).show();
        }
    });

	clearInfoWindows();
}


/**
  *  clearRoute()
  *
  *  Removes driving directions from map.
  *
  **/
function clearRoute() {
	// Set map to null to remove directions on map
    directionsDisplay.setMap(null);

    // Update header
    $("#totalStores").show();
    $("#storesNear").show();
    $("#directionsTo").hide();
    $("#directionsToHeader").empty();

	// Clear info windows
	clearInfoWindows();
}


/**
  *  microSiteMyStoreCheck()
  *
  *  Checks to see if the user has a home store set. Determines the output
  *  of 'Set Home Store' link.
  *
  **/
function microSiteMyStoreCheck() {
	var myStoreNumber = "";
	var yourHomeStoreButton = "";
	var thisStoreNumber = $("#storeNumber").html();

	yourHomeStoreButton = ['<a class="button with-logo" href="#" onclick="return false;">' +
							'<span class="first-child">' +
								'<span class="inner">' + storeLocatorText.yourHomeStore + '</span>' +
							'</span>' +
						'</a>'].join();

	$.getJSON('/' + storeLocatorText.lang + '/loc/stores.htm?pc=' + defaultPostalCode + '&o=1', function(data) {
		// Check for set store
		if(data.mystore) {
			myStoreNumber = data.mystore[0];

			if (myStoreNumber == thisStoreNumber) {
				$("li#myStore").html(yourHomeStoreButton);
				$("li#myStore a").css("cursor","default");
				$("li#myStore a span.inner").css("cursor","default");
				$("li#myStore a span.inner").css("width","110px");
			}
		}
	});
}


/**
  *  accountMyStoreCheck()
  *
  *  Checks to see if the user has a home store set. Determines the output
  *  of text on Registration and Account Settings pages.
  *
  **/
function accountMyStoreCheck(){
	$.getJSON('/' + storeLocatorText.lang + '/loc/stores.htm?pc=' + defaultPostalCode + '&o=1', function(data) {
		// Check for set store
		if(data.mystore) {
			displayStore(data.mystore);
		}
	});
}

function displayAccountStore() {
	$.getJSON('/' + storeLocatorText.lang + '/loc/getStore.htm?ms=' + $('#store_id').val(), function(data) {
		// Check for set store
		if(data.store) {
			displayStore(data.store);
		}
	});
}

function displayStore(mystore){

	var myStoreNumber = mystore[0];
	var storeName     = mystore[2];
	var storeAddress  = mystore[3];
	var storeCity     = mystore[4];
	var storeProvince = mystore[5];
	var storePostal   = mystore[6];
	var storePhone    = mystore[7];
	var storeType     = mystore[8];
	var storeLat      = mystore[9];
	var storeLng      = mystore[10];

	var escapedPostal = escape(mystore[6]);

	var storeTypeIcon = storeLocatorText.HF;
	var storeTypeIconWidth = storeLocatorText.HF_w;
	var storeTypeIconHeight = storeLocatorText.HF_h;
	var logoAndAddress = "";

	// Display logo and address
    logoAndAddress = ['<div id="userStore" class="clearfix">' +
		'<div style="float:left; margin: 15px 0 0 10px;"><span class="logo"><img src="/Images/store-locator/' + storeTypeIcon + '" width="' + storeTypeIconWidth + '" height="' + storeTypeIconHeight + '" alt="' + storeName + '" /></span></div>' +
		'<div class="storeLogo"><span class="storeName">' + storeName + '</span><br /><br />' +
		storeAddress +'<br />' +
		storeCity +', ' + storeProvince +'<br />' +
		storePostal +'<br />' +
		formatPhoneNumber(storePhone) + '</div>' +
		'<div class="staticMap"><img border="0" src="http://maps.google.com/maps/api/staticmap?size=282x120&markers=icon:http://www.homehardware.ca/Images/icons/hh-closest.png|' + escape(storeAddress) + '+' + escape(storeCity)  + '+' + storeProvince + '+' + escapedPostal + '&sensor=false" width="282" height="120" alt="Map of ' + storeName + '" /></div>' +
		'</div>'].join();

	$("p#store_message").html(logoAndAddress);

	// Update button
    $("a#reg_find_store span.inner").html(storeLocatorText.changeHomeStoreButton);

	// Set postal code field value
	$("#reg_postalcode").val(storePostal);

	// Set hidden field store_id value
	$("form#registration input#store_id").val(myStoreNumber);

}

/**
  *  homepageMyStoreCheck()
  *
  *  Checks to see if the user has a home store set. Determines the output
  *  of text on the homepage.
  *
  **/
function homepageMyStoreCheck(){
	// Hide popup button if Store Locator link button is not present in the header
	if ($("#storeHeader #yourStore a.button").size() == 0) {
        $("#selectYourStoreHome").hide();
		$("#featuredProducts").css('top','0');
	}
}


/**
  *  setStore()
  *
  *  Sets the selected store to the session/user account.
  *
  *  @param {String} storeId Unique store number.
  *  @param {Number} countOutput Count value of current store.
  *
  **/
function setStore(storeId, countOutput){
	// Show the loading dialog
	openLoadingBar();
	
    var storeInfo = "";
    var url = '/' + storeLocatorText.lang + '/loc/setMyStore.htm?ms=' + storeId;
    
    if (registrationLocatorPopup) {
    	$('input#store_id').val(storeId);
    	url = '/' + storeLocatorText.lang + '/loc/getStore.htm?ms=' + storeId;
    }

    $.getJSON( url, function(data) {
        if (data.error) {
            alert(data.error);
        } else {
            // Set store info in header
            storeInfo = '<p>' + storeLocatorText.yourHomeStore + ' | <a href="/' + storeLocatorText.lang + '/' + storeLocatorText.storeLocatorURL + '">' + storeLocatorText.changeButton + '</a></p>' +
                        '<p><strong>' + data.store[2] + '</strong><br>' +
                        data.store[3] + '<br>' +
                        data.store[4] + ', ' + data.store[5] + '<br>' +
                        data.store[6] + '<br />' +
                        formatPhoneNumber(data.store[7]) + '</p>';

            // Set website link in header, if available
            if (data.store[11] && data.store[11] != "")
                storeInfo += '<p><a href="/' + data.store[11] + '">' + storeLocatorText.viewWebsite + '</a></p>';

            if(!registrationLocatorPopup){
            	$("#yourStore p:eq(1)").html(storeInfo);
            }
                       
      
        	$("#logo a img").eq(0).attr("src","/Images/logos/" + storeLocatorText.lang + "-hfurniture.png");
        	$("#logo a img.print").attr("src","/Images/logos/" + storeLocatorText.lang + "-hfurniture-print.gif");

            // Set store id to hidden field in registration form
            if (registrationLocatorPopup) {
                $("form#registration input#store_id").val(storeId);
                $("a#reg_find_store span.inner").html(storeLocatorText.changeHomeStoreButton);
                $("#storeHeader").removeClass('loggedOut');
                $('#storeLocatorPopup').dialog('close');
                displayStore(data.store);
			} else if (searchLocatorPopup || homepageLocatorPopup || shoppingListLocatorPopup || catalogListItemPopup) {
                // Reload the page
                location.reload();
            } else {
				// Set info in header
                $("#yourStore").html(storeInfo);
                $("#storeHeader").removeClass('loggedOut');
				// Hide all "my store" labels
				$(".block4").hide();
				// Show all "set store" links
				$(".setStoreLinkItem").show();
				// Hide all "my store" links
				$(".myStoreLinkItem").hide();
				
				if(!microSite) {
					// Clear info windows
					clearInfoWindows();
				
					// Get stores				
					getStores();
				}
            }

			if (microSite) {
				microSiteMyStoreCheck();
			}
        }
    });

	// Close waiting bar
	closeLoadingBar();
}


/**
  *  typeAheadExecute()
  *
  *  Adds full city name to city input box then gets all stores.
  *  Called on type-ahead item click.
  *
  *  @param {Number} cityId The id of the type-ahead listing item.
  *
  **/
function typeAheadExecute(cityId) {
	// Set city input box value
	$("#city").val($("#cityTypeAhead ul#cities li#city_" + cityId).html());

	// Show the loading dialog
	openLoadingBar();

	// Get all stores
	updateStores();
}


/**
  *  resetMap()
  *
  *  Resets the map and page elements to their default state.
  *
  **/
function resetMap() {
	// Update button label
	$("#update_store span span.inner").html(storeLocatorText.findButton);

    // Clear markers
    clearMarkers();

	// Clear info windows
    clearInfoWindows();

    // Hide any directions, if visible
    $("#driving_directions").hide();
    clearRoute();

    // clear header
    $("#totalStores").html("");
    $("#directionsTo").html("");
    $("#directionsToHeader").html("");

    // Set header and footer text
    $("#storeLocator .header h2#title").show();
    $("#storeLocator .header h2:eq(1)").hide();

	// Show error
	$("#noSearchResults").show();

	if (locatorPopup) {
		$("#totalStores").hide();
		$("#storesNear").hide();
	}

    // Set and show intro text
    if (!locatorPopup) {
        $("#storeLocatorIntro").html(storeLocatorText.storeLocatorIntro);
    	$("#storeLocatorIntro").show();
	}

    // Hide pagination
    $(".pagination.locator").hide();

    // Clear pagination
    $(".pagination.locator ul").html("");

    // Reset map lat/long/zoom
    var center = new google.maps.LatLng( 59, -100 );
    map.setCenter(center);
    map.setZoom(3);

	// Close waiting screen
	closeLoadingBar();
}


/**
  *  clearMarkers()
  *
  *  Removes all markers from the map.
  *
  **/
function clearMarkers() {
	for (var i = 0; i < allMarkers.length; i++) {
        allMarkers[i].setMap(null);
    }
}


/**
  *  clearInfoWindows()
  *
  *  Removes all info windows from the map. Also resets store list item background color.
  *
  **/
function clearInfoWindows() {
	for (var i = 0; i < allInfoWindows.length; i++) {
		allInfoWindows[i].close();
	}
}


/**
  *  toTop()
  *
  *  Sends the user to the top of the page automatically.
  *
  **/
function toTop() {
	// Scroll to the top of the page
	$('html, body').animate({scrollTop:0}, 1500);
}


/**
  *  openLoadingBar()
  *
  *  Shows the 'Loading' dialog.
  *
  **/
function openLoadingBar() {
	$("#loadingBar").dialog('option', 'title', storeLocatorText.loading);
	$("#loadingBar").dialog('open');
}


/**
  *  closeLoadingBar()
  *
  *  Hides the 'Loading' dialog.
  *
  **/
function closeLoadingBar() {
	$("#loadingBar").dialog('close');
}

/**
  *  openPostalCodeDialog()
  *
  *  Shows the 'Postal Code' dialog.
  *
  **/
function openPostalCodeDialog() {
	$("#postalCodeDialog").dialog('option', 'title', storeLocatorText.postalCode);
	$("#postalCodeDialog").dialog('open');
}


/**
  *  closeLoadingBar()
  *
  *  Hides the 'Loading' dialog.
  *
  **/
function closePostalCodeDialog() {
	$("#postalCodeDialog").dialog('close');
}


/**
  *  Helper functions.
  *
  **/
function stripslashes( str ) {
   return (str+'').replace(/\0/g, '0').replace(/\\([\\'"])/g, '$1');
}
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
function formatPhoneNumber(phoneNumber) {
	return phoneNumber.replace( /^(\d{3})(\d{3})(\d{4})$/, "($1) $2-$3" );
}
function get_cookie(cookie_name) {
	var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
	if (results) {
		return (unescape(results[2]));	
	} else {
    	return null;
	}
}
function delete_cookie(cookie_name) {
	var cookie_date = new Date();  // current date & time
	cookie_date.setTime(cookie_date.getTime() - 1);
	document.cookie = cookie_name += "=; path=/; expires=" + cookie_date.toGMTString();
}
function getParam(param) {
	param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+param+"=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if(results == null) {
    	return "";
	} else {
	    return results[1];
	}
}
