/* Variable Declaration - Starts Here */

var MAX_MATCHES = 10;

var MAP_SESSION_TIMEOUT = "could not read session";
var SEARS_LOCATOR_ERROR_GENERAL = 0;
var SEARS_LOCATOR_ERROR_NO_CITY_STATE_ZIP = 1;
var SEARS_LOCATOR_ERROR_NO_RESULTS = 2;
var SEARS_LOCATOR_ERROR_INVALID_ADDRESS = 3;
var SEARS_LOCATOR_ERROR_MULTIPLE_ADDRESS = 4;
var SEARS_LOCATOR_ERROR_INVALID_RADIUS = 5;
var SEARS_LOCATOR_ERROR_INVALID_ROUTE_ADDRESS = 6;
var SEARS_LOCATOR_ERROR_MULTIPLE_ADDRESS_RET = 7

/*Errors Given by Google Maps.*/
var SEARS_LOCATOR_ERROR_GOOGLE_GEO_UNKNOWN_ERROR = 10;
var SEARS_LOCATOR_ERROR_GOOGLE_GEO_UNKNOWN_ADDRESS = 11;
var SEARS_LOCATOR_ERROR_GOOGLE_GEO_SERVER_ERROR = 12;
var SEARS_LOCATOR_ERROR_GOOGLE_GEO_BAD_REQUEST = 13;
var SEARS_LOCATOR_ERROR_GOOGLE_GEO_UNKNOWN_DIRECTIONS = 14;

var strJsonObj=null;
var waitFlag = false;
var fromLoc = new Object();

/* Constant JSON indicating the country options shown in state dropdown */
var jsonCountry={
					PR:1,
					VI:1
				}

/*Variable declaration for WCS Store Locator*/
var map = null;
var geocoder = null;
var searchLoc = new Object();
var resultData = null;
var resultCount;
var directions = null;


/* Variable Declaration - Ends Here */

/* DOM READY CALLS - Starts Here */
$(document).ready(function($){
    var domBodySetup = "<div id=\"divWait\" class=\"msgbox\" style=\"display:none;\">";
    domBodySetup+= "<br>Processing Search<br><img src=\""+imagePath+"img/dots.gif\"/><br>";
    domBodySetup+= "</div>";
    domBodySetup+= "<div id=\"divMsg\" class=\"msgbox\" style=\"display:none;\">";
	domBodySetup+= "You must have at least 1 store type selected to search<br><input type=\"button\" value=\"Close\" onClick=\"hideMessageBox();\"/>";
	domBodySetup+= "</div>";
    $('body').prepend(domBodySetup);
});

$(document).ready(function($){
	//clear form
	
	$('input#txtAddress').val('');
	$('input#txtCity').val('');
	$('input#txtRadius').val('30');
	$('select#selStateProvince').val('');
	var currentURL = self.location.href;
	if(currentURL.indexOf("sessionerror=1") >= 0){
		$('div.error').html("<span>Action Required<span>&nbsp;-&nbsp;<span>Your search session has expired due to inactivity, please re-enter you search criteria to search again.</span>");
		$('div.error').show();
	}
	
	if(svcFlag == 'Y' || svcFlag == 'y'){
		fnSubmitSearch();
	}else{
		$('input#txtPostalCode').val('');
	}
	
	$(window).unload( function () { 
		if(typeof GUnload != 'undefined'){ 
			GUnload();
		}
});
});


$(function(){
	// Search on click of Search button
	$('img[alt="search"]').click(function(){
		fnSubmitSearch();
	});
	
	// Search on click on enter key in the form
	$("input#txtAddress, input#txtPostalCode, input#txtCity, input#txtRadius, select#selStateProvince").keypress(function(e) {
		if(e.keyCode == 13) {
			fnSubmitSearch();
		}
	});
});

/* DOM READY CALLS - Ends Here */

/* General Methods for Store Locator - Starts Here */

function errorFunction(jsonResponse){
	var err = fnGetErrMsg(SEARS_LOCATOR_ERROR_GENERAL);

    if (err == "Unknown Error")
        err = exp;
	$('div.error').html("<span>" + err+"</span>");
	$('div.error').show();
	
	// Hide the loading image
	fnHideWaitBox();
	return false;
}

// This function will be called when user clicks on search button
function fnSubmitSearch(){
	try{
		//If search is in progress then wait
		if(waitFlag)return;
		
		//Clear existing error messages on screen
		fnClearScreen();
		
		//Perform Client side validation on address
		fnValidateAddress()
	
		// If it passes client side validation display the loading image
		fnShowWaitBox();
			
		//Initialize Google Maps API
		initialize();
		
		//Perform Geocoding and Proceed with search for the given Location
		performGeocoding(searchLoc);
	}catch(exp){
	    var err = fnGetErrMsg(exp);
	    if (err == "Unknown Error")
	        err = exp;
		$('div.error').html("<span>" + err+"</span>");
		$('div.error').show();
		// Hide the loading image
		fnHideWaitBox();
		return false;
	}
}

function fnValidateAddress(){
	searchLoc.address = $('input#txtAddress').val();
	searchLoc.city = $('input#txtCity').val();
	searchLoc.state = $('select#selStateProvince').val();
	searchLoc.zip = $('input#txtPostalCode').val();
	if(jsonCountry[searchLoc.state] != 'undefined' && jsonCountry[searchLoc.state] == 1){
		searchLoc.country = searchLoc.state;
	}else{
		searchLoc.country = "US";
	}
	fromLoc = searchLoc;

		var radius = $('input#txtRadius').val();

		//client side validations
		if(!((!isBlank(searchLoc.city) && !isBlank(searchLoc.state)) || !isBlank(searchLoc.zip))){
				throw SEARS_LOCATOR_ERROR_NO_CITY_STATE_ZIP;
		}
		if(!isBlank(searchLoc.zip)){
			if(!checkZip(searchLoc.zip)){
			throw SEARS_LOCATOR_ERROR_NO_CITY_STATE_ZIP;
			}
		}
		if(!checkPositiveNumeric(radius)){
				throw SEARS_LOCATOR_ERROR_INVALID_RADIUS;
		}
}
		
function performGeocoding(searchLoc) {
	var address = searchLoc.address + "+" + searchLoc.city + "+" + searchLoc.state + "+" + searchLoc.zip + "+" + searchLoc.country;
	
	if (geocoder) {
		if(searchLoc.country == "US"){
			geocoder.setBaseCountryCode("US");
		}else{
			geocoder.setBaseCountryCode(searchLoc.state);
		}
		geocoder.getLocations(address,geocodingResponse);
	}
}

function geocodingResponse(geocoderData){
	//Since this is a call back function, start a new try block
	try{
		if (!geocoderData || geocoderData.Status.code != 200) {
          throw SEARS_LOCATOR_ERROR_INVALID_ADDRESS;
        }
		if(geocoderData.Placemark.length>1){
			// Multiple match found for the entered location, Show Alternate Locations
			drawAltResults(geocoderData.Placemark);
		}else{
			if(geocoderData.Placemark[0].AddressDetails.Accuracy > 1){
				searchLoc.latitude = geocoderData.Placemark[0].Point.coordinates[1];
				searchLoc.longitude = geocoderData.Placemark[0].Point.coordinates[0];
				
				//Single match found for the entered location, perform store search
				searchresults(searchLoc);
			}else{
				throw SEARS_LOCATOR_ERROR_INVALID_ADDRESS;
			}
		}
	}catch(exp){
	    var err = fnGetErrMsg(exp);
	    if (err == "Unknown Error")
	        err = exp;
		$('div.error').html("<span>" + err+"</span>");
		$('div.error').show();
		// Hide the loading image
		fnHideWaitBox();
		return false;
	}
}

// This function will be called when user clicks on one of the locations displayed in alternate result section
function fnAlternateSearch(latitude,longitude){
	if(waitFlag)return;
		fnShowWaitBox();
		
	fnClearScreen();
	
	var searchLoc = new Object();
	searchLoc.latitude = latitude;
	searchLoc.longitude = longitude;
	searchresults(searchLoc);
}

/**********************************************************************
 * Function Name     : searchresults
 * Description       : This is called on click of search button
 
 **********************************************************************/
function searchresults(searchLoc){
	try{
		//Make an AJAX call to get the Stores
		var radius = $('input#txtRadius').val();
		var url="StoreLocatorSearch?storeId="+storeId+"&latitude="+searchLoc.latitude+"&longitude="+searchLoc.longitude+"&distance="+radius+"&sourcePage=storeLocator";   
		$.ajaxSetup( {
			error : errorFunction 
		});
    	$.getJSON(url,fnCheckResult);
	}catch(exp){
	    var err = fnGetErrMsg(exp);
	    if (err == "Unknown Error")
	        err = exp;
		$('div.error').html("<span>" + err+"</span>");
		$('div.error').show();
		
		// Hide the loading image
		fnHideWaitBox();
		
		return false;
	}
	return false;
}

/**********************************************************************
 * Function Name     : fnCheckResult
 * Description       : This is called to check the result type-Store Details/Alt Result
 **********************************************************************/
 function fnCheckResult(strLocJsonObj){
	try{
		var resulttype=strLocJsonObj.resulttype;
		if(resulttype=="StoreLocator"){
			//Result obtained is actual stores
			if(strLocJsonObj.result.length == 0){
				throw SEARS_LOCATOR_ERROR_NO_RESULTS;
			}
			//call the function to generate checkbox Json
			var myJsonObj = fnConstructCheckboxJson();
			drawResults(strLocJsonObj.result,myJsonObj);
			strJsonObj=strLocJsonObj;
		}else if(resulttype=="InvalidAddress"){
			throw SEARS_LOCATOR_ERROR_INVALID_ADDRESS;
		}else{
			// Not possible
			throw SEARS_LOCATOR_ERROR_NO_RESULTS;
		}
		fnHideWaitBox();
	}catch(exp){
	    var err = fnGetErrMsg(exp);
	    if (err == "Unknown Error")
	        err = exp;
		$('div.error').html("<span>" + err+"</span>");
		$('div.error').show();
		
		// Hide the loading image
		fnHideWaitBox();		
		return false;
	}
}

/**********************************************************************
 * Function Name     : fnOnchangeChk
 * Description       : This function is called on check/uncheck of checkbox 
 * this section.
 **********************************************************************/
 
function fnOnchangeChk(){
	if(strJsonObj != null){
		var myJsonObj = fnConstructCheckboxJson();	
		drawResults(strJsonObj.result,myJsonObj);	
	}
}

/**********************************************************************
 * Function Name     : fnClearScreen
 * Description       : This is will clear the error mesages and hide 
 * this section.
 **********************************************************************/
function fnClearScreen(){
	$('div.error').html("&nbsp;");
	$('div.error').hide();
	$('div.locationResults').html("&nbsp;");
	$('div.locationResults').hide();
	$('h3.resultsHeader').html("Stores found near your location:<span>&lt;not specified&gt;</span>");
}

/**********************************************************************
 * Function Name     : fnNarrowSearch
 * Description       : This function is called on click of Narrow 
 * Search checkbox. It will search for stores again if some results are 
 * already displayed.
 **********************************************************************/
function fnNarrowSearch(objThis){	
	try{
		var cntChkBox = parseInt(document.getElementById("cbCount").value);
		var chkBoxObj;
		var chkSelFlag = "NO";
		for(var i=0; i < cntChkBox; i++){
			chkBoxObj = document.getElementById("cbx" + i);
			if(chkBoxObj.checked){
				chkSelFlag = "YES";
				break;
			}
		}
		if(chkSelFlag == "NO") {
		    objThis.checked = true;
			showMessageBox("You must have at least 1 store type selected to search");
			return;
		}
		//call the function to generate Json	
		fnOnchangeChk();
	}catch(exp){
	 	var err = fnGetErrMsg(exp);
	    if (err == "Unknown Error")
	        err = exp;
		$('div.error').html("<span>" + err+"</span>");
		$('div.error').show();
		
		// Hide the loading image
		//fnHideWaitBox();		
		return false;
	}
}


/**********************************************************************
 * Function Name     : fnGetErrMsg
 * Description       : This function is used to get the appropriate 
 * error message to be displayed based on the exceptions being caught 
 * in the validations.
 **********************************************************************/
function fnGetErrMsg(code){
    var inCode = code.toString();
	if(inCode.toLowerCase().indexOf(MAP_SESSION_TIMEOUT) > -1){
		var currentURL = self.location.href;
		if(currentURL.indexOf("sessionerror=1") == -1){
			if(curentURL.indexOf("?") >= 0)
				currentURL += "&"
			else
				currentURL += "?"
			currentURL += "sessionerror=1";
		}
		self.location.href = url;
	}
	switch(parseInt(code)){
		case SEARS_LOCATOR_ERROR_NO_CITY_STATE_ZIP:
			return "Please enter a correct 5-digit Zip code or your address to continue."
		case SEARS_LOCATOR_ERROR_NO_RESULTS:
			return "Sorry, no stores were found near this location, please perform another search.";
		case SEARS_LOCATOR_ERROR_INVALID_ADDRESS:
			return "Address couldn't be found, please provide more details.";
		case SEARS_LOCATOR_ERROR_MULTIPLE_ADDRESS:
			return "Multiple address have been found, please select the correct address to continue.";
		case SEARS_LOCATOR_ERROR_INVALID_RADIUS:
			return "Radius entered is invalid, please enter a numeric value.";
		case SEARS_LOCATOR_ERROR_INVALID_ROUTE_ADDRESS:
			return "Please enter a valid address for the origin of the route.";
		case SEARS_LOCATOR_ERROR_GENERAL:
			return "An Error has occurred, please try again";
		case SEARS_LOCATOR_ERROR_MULTIPLE_ADDRESS_RET:
			return "Multiple address have been found, please provide more details.";
		case SEARS_LOCATOR_ERROR_GOOGLE_GEO_UNKNOWN_ERROR:
			$('input#googleDirErrorMessage').val("Google Server: An unknown error occurred.");
			return "Address could not be found, please provide more details.";
		case SEARS_LOCATOR_ERROR_GOOGLE_GEO_UNKNOWN_ADDRESS:
			$('input#googleDirErrorMessage').val("Google Server: No corresponding geographic location could be found for"+ 
							              " one of the specified addresses. This may be due to the fact that"+ 
							              " the address is relatively new, or it may be incorrect.");
			return "Address could not be found, please provide more details.";
		case SEARS_LOCATOR_ERROR_GOOGLE_GEO_SERVER_ERROR:
			$('input#googleDirErrorMessage').val("Google Server: A geocoding or directions request could not be"+ 
							              " successfully processed, yet the exact reason for the failure is"+ 
							              " not known.");
			return "Address could not be found, please provide more details.";
		case SEARS_LOCATOR_ERROR_GOOGLE_GEO_BAD_REQUEST:
			$('input#googleDirErrorMessage').val("Google Server: The route request could not be successfully parsed.");
			return "Address could not be found, please provide more details.";
		case SEARS_LOCATOR_ERROR_GOOGLE_GEO_UNKNOWN_DIRECTIONS:
			$('input#googleDirErrorMessage').val("Google Server: Could not find a route between those two locations.");
			return "Address could not be found, please provide more details.";
		default:
			return "An Error has occurred, please try again";
	}
}

/* General Methods for Store Locator - Ends Here */


/* Utility Methods used in Store Locator - Starts Here */

/**********************************************************************
 * Function Name     : fnShowWaitBox
 * Description       : This function is used to show the loading 
 * wait box on the screen.
 **********************************************************************/
function fnShowWaitBox(){
	waitFlag = true;
	var hpos = (($('body').width()/2)-170);
	if($.browser.msie){ var vpos =  document.body.scrollTop;}else{ var vpos = window.pageYOffset; }vpos+=200;
	$('div.progress').css({ left:hpos, top:vpos }).show();
	$('div#divWait').css({ left:hpos, top:vpos }).show();
}

/**********************************************************************
 * Function Name     : fnHideWaitBox
 * Description       : This function is used to hide the loading 
 * wait box on the screen.
 **********************************************************************/
function fnHideWaitBox() {
	waitFlag = false;
	$('div#divWait').hide();
}

/**********************************************************************
 * Function Name     : showMessageBox
 * Description       : This function is used to show the dhtml 
 * message box.
 **********************************************************************/
function showMessageBox(text){
	waitFlag = true;
	var hpos = (($('body').width()/2)-100);
	if($.browser.msie){ var vpos =  document.body.scrollTop;}else{ var vpos = window.pageYOffset; }vpos+=200;
	$('div#divMsg').css({ left:hpos, top:vpos }).show();
}

/**********************************************************************
 * Function Name     : hideMessageBox
 * Description       : This function is used to hide the dhtml 
 * message box.
 **********************************************************************/
function hideMessageBox(){
	waitFlag = false;
	$('div#divMsg').hide();
}

function trimSPUStr(st) {
	if(st == undefined || st == null){
		return "";
	}
	st += "";
	var len = st.length
	var begin = 0, end = len - 1;
	while ((st.charAt(begin) == " " || st.charAt(begin) == "\n") && begin < len) {
		begin++;
	}
	while ((st.charAt(end) == " " || st.charAt(end) == "\n") && begin < end) {
		end--;
	}
	return st.substring(begin, end+1);
}

//****************************************************************************************************
// Is Blank Function
//****************************************************************************************************
function isBlank(str){
	//Pre: str != null
	//Post: if str = '' return true, else false
	str = trimSPUStr(str);
	if(str == ''|| str=='(000)000-0000'|| str=='(#00)000-0000') return true;
	return false;
}


//****************************************************************************************************
// Check Positive Numeric Function
//****************************************************************************************************
function checkPositiveNumeric(str){
	//Pre: str != null
	//Post: If str is a Number and a greater or equal to zero
	//		 return true, else false
	if(!checkNumeric(str)){
		return false;
	}
	var val = parseFloat(str);
	return (val>=0)
}


//****************************************************************************************************
// Check Zip (US)
//****************************************************************************************************
function checkZip(str){
	//Pre: zip != null
	//Post: if zip is a valid zipcode return true, else false;
	if (str.length < 5)
		return false;
	if(!checkNumeric(str.charAt(0) + str.charAt(1) + str.charAt(2) + str.charAt(3) + str.charAt(4)))
			return false;
	if(str.length == 5)
			return true;
	if((str.charAt(5) != '-') || (str.length != 10))
			return false;
	if(!checkNumeric(str.charAt(6) + str.charAt(7) + str.charAt(8) + str.charAt(9)))
		return false;
	return true; 
}
//****************************************************************************************************
// checkNumeric (String)
//****************************************************************************************************
function checkNumeric(str){
	//Pre: str != null
	//Post: If str is a Number return true, else false
	strLength = str.length;
	var isFloat = false;
	
	error = false;
	var i = 0;
	for (i; i < strLength; i++)
	{
		
		if ( (str.charAt(i) < '0') || (str.charAt(i) > '9') )
		{
			if(!isFloat && (str.charAt(i) == '.')){
				isFloat = true;
			}
			else if ( i == 0)
			{
				if ((str.charAt(i) != '-'))
				{
					error = true;
					break;
				}	
			}
			else
			{
				error = true;
				break;
			}
		}
	}

	return !error;
}

/**********************************************************************
 * Function Name     : drawAltResults
 * Description       : This function is used to generate the Html for Alt results. 

 **********************************************************************/
function drawAltResults(storeLocJson){

      $('h3.resultsHeader').html("Please Select a Result:");
      var ga;
      var html = "";
      var li_reSize = storeLocJson.length;
      for(var i=0; i< li_reSize&&i<MAX_MATCHES; i++){
            ga = storeLocJson[i];
            html += "<div class=\"store\">";
            html += "<strong><a href='javascript:;' onclick='fnAlternateSearch(\"" + ga.Point.coordinates[1] + "\",\"" + ga.Point.coordinates[0] + "\")'>";  
            html +=ga.address;
            html += "</a></strong></div>";                
            }
      // Update the alternate Locations in result section.
      $('div.locationResults').html(html);
      
      // Update alternate row colour for result section
      $('div.locationResults .store:odd').addClass('zebra');
      $('div.locationResults .store:first').css({borderTop:'none'});
      if(li_reSize == 0){
      	throw SEARS_LOCATOR_ERROR_NO_RESULTS;
      }
      // Display the result section.
      $('div.locationResults').show();
     throw SEARS_LOCATOR_ERROR_MULTIPLE_ADDRESS;
}

function isNoOptionChecked(){
	try{
		var cntChkBox = parseInt(document.getElementById("cbCount").value);
		var chkBoxObj;
		//create json obj dynamically
		for(var i=0; i < cntChkBox; i++){
			chkBoxObj = document.getElementById("cbx" + i);
			if(chkBoxObj.checked){		
				return false;
			}
		}
	}catch(e){
		return false;
	}

	return true;
}

function isDropOffLoc(strInfo){
	try{
		for(var i=0; i < strInfo.attrname.length; i++){
			try{
				var name = strInfo.attrname[i];
				if(name == "" || name == null)
					break;
				if(name == "Drop-off Location")
					return true;
			}catch(ex){
				break;
			}
		}
	
	}catch(e){
		return false;
	}
	return false;
}


/**********************************************************************
 * Function Name     : drawResults
 * Description       : This function is used to generate the Html for Store Details result type. 
 **********************************************************************/
function drawResults(storeLocJson,myJsonObj){
		//resultData=storeLocJson;
		resultData = new Array();
		resultCount = 0;
		$('h3.resultsHeader').html("Stores found near your location:<span>&lt;not specified&gt;</span>");
		var loc;
		var html = "";
		var recordCount=0;
		var srchSize = storeLocJson.length;
		//var noOptionCheckedInd = isNoOptionChecked();
		//sort the obtanied json result based on the distance
		storeLocJson = fnSortBasedOnDistance(storeLocJson);
		
		for(var i=0; i < srchSize && recordCount < MAX_MATCHES; i++){
			var strLocJson = storeLocJson[i];
			if(!((eval("myJsonObj.Drop_Off_Locations") == 1) && isDropOffLoc(strLocJson)) && (eval("myJsonObj."+strLocJson.storeName)!=1)){
				continue;
			}
			resultData.push(strLocJson);
			resultCount++;
	        var hldHtml = "<div class=\"store\">";
			hldHtml += "<div class=\"num\">" + (recordCount+1) + "</div>";
			hldHtml += "<div class=\"column locinfo\"><p>";
			//Display store type
			//if(strLocJson.type2  == "A"){
				//hldHtml += "<strong>" + kmartStore.titleCase() + "</strong><br>";
			//}else if(strLocJson.type2  == "B"){
				//hldHtml += "<strong>" + searsEssentialStore.titleCase() + "</strong><br>";
			//}
			if(strLocJson.storeName  == "Kmart"){
				hldHtml += "<strong>" + kmartStore.titleCase() + "</strong><br>";
			}else if(strLocJson.storeName  == "Sears_Essentials"){
				hldHtml += "<strong>" + searsEssentialStore.titleCase() + "</strong><br>";
			}else if(strLocJson.storeName  == "Sears_Stores"){
				hldHtml += "<strong>" + searsStore.titleCase() + "</strong><br>";
			}else if(strLocJson.storeName  == "Sears_Auto_Centers"){
				hldHtml += "<strong>" + searsAutoCenters.titleCase() + "</strong><br>";
			}else if(strLocJson.storeName  == "Hometown_Dealers"){
				hldHtml += "<strong>" + hometownDealers.titleCase() + "</strong><br>";
			}else if(strLocJson.storeName  == "Hardware_Stores"){
				hldHtml += "<strong>" + hardwareStores.titleCase() + "</strong><br>";
			}else if(strLocJson.storeName  == "Sears_Appliance_Outlet_Stores"){
				hldHtml += "<strong>" + appliancesOutlet.titleCase() + "</strong><br>";
			}else if(strLocJson.storeName  == "Service_Centers_Repair_Drop_off_Locations"){
				hldHtml += "<strong>" + repairPartsCenter.titleCase() + "</strong><br>";
			}
			//if STore type is 'A' and Store Name is KMART then dont dispaly Store as 'Kmart Store' else display Store Name
			if(strLocJson.type2  == "A" && strLocJson.name == "Kmart") {
			
			}else{
				hldHtml += "<strong>"+strLocJson.name.titleCase()+" Stores</strong><br>";	
			}		
			//display store address city and stae code
			hldHtml += "<span>" + strLocJson.address.titleCase() + "</span><br>";
			hldHtml += "<span>" + strLocJson.city.titleCase() + ", " + strLocJson.stat + " " + strLocJson.zip.substring(0, 5) + "</span>";
			hldHtml += "</p><p>";
			hldHtml += "<strong>Phone Number:</strong><br>";
			hldHtml += "</br>";
			if(strLocJson.phone1 != ""){
				hldHtml += "<span>"+fnFormatPhoneNo(strLocJson.phone1)+"</span><br>";
			}/*if(strLocJson.phone2 != ""){
				hldHtml += "<span>"+fnFormatPhoneNo(strLocJson.phone2)+"</span><br>";
			}*/
			hldHtml += "</p></div>";						
			hldHtml += "<div class=\"column services\">";
			hldHtml += fnGetStoreHourHtml(strLocJson);
			hldHtml += fnGetHolidayHourHtml(strLocJson);
			hldHtml += fnGetStoreServicesHtml155(strLocJson);
			hldHtml += "</div>";
			hldHtml += "<div class=\"column actions\">";
	
			//urlGetDirection=mapquestDirUrl+"&destTitle="+strLocJson.name+"&destPhone="+strLocJson.phone1+"&destAddress="+strLocJson.address+"&destCity="+strLocJson.city+"&destStateProvince="+strLocJson.stat+"&destPostalCode="+strLocJson.zip+"";
			//urlSeeMap=mapquestMapUrl+"&destTitle="+strLocJson.name+"&destPhone="+strLocJson.phone1+"&destAddress="+strLocJson.address+"&destCity="+strLocJson.city+"&destStateProvince="+strLocJson.stat+"&destPostalCode="+strLocJson.zip+"";

			urlFromLocation="&origAddress="+fromLoc.address+"&origCity="+fromLoc.city+"&origStateProvince="+fromLoc.state+"&origPostalCode="+fromLoc.zip;					
			hldHtml += "<input type=\"image\" onclick=\"fnOpenDirections("+ (resultCount-1) +");\" src=\""+imagePath+"img/storeLocator/btn_getdirec.gif\" width=\"111\" height=\"24\" alt=\"Get Directions\">";
			hldHtml += "<input type=\"image\" onclick=\"fnOpenSeeMap("+ (resultCount-1) +");\" src=\""+imagePath+"img/storeLocator/btn_seemap.gif\" width=\"111\" height=\"24\" alt=\"See Map\">";

			hldHtml += "</div>";
			hldHtml += "</div>";
			html += hldHtml;
			hldHtml = "";		
			recordCount++;				
		}
		
		if(recordCount == 0){
			$('div.locationResults').html("&nbsp;");
			$('div.locationResults').hide();
			throw SEARS_LOCATOR_ERROR_NO_RESULTS;
		}
		
		// Update the result count
		if(resultCount >= MAX_MATCHES){
			$('h3.resultsHeader span').text(MAX_MATCHES+"+");
		}else {
			$('h3.resultsHeader span').text(resultCount);
		}
		
		//clear the previous error message
		$('div.error').html("&nbsp;");
		$('div.error').hide();
	
		// Update the result
		$('div.locationResults').html(html)
		
		// Update alternate row colour for result section
		$('div.locationResults .store:odd').addClass('zebra');
		$('div.locationResults .store:first').css({borderTop:'none'})
		
		// Show thw result section.
		$('div.locationResults').show();
		//$('div.locationResults').css({ display:block !important }).show();

}

//sort method - to sort based on the distance
function fnSortBasedOnDistance(storeDetailsJson1){
	var attrArray = new Array();
	for(var i=0; i < storeDetailsJson1.length; i++){
		attrArray.push(storeDetailsJson1[i]);
	}
	return attrArray.sort(callbackFuncDist);
}

// call back function
function callbackFuncDist(a,b){
	var distance1 = a.distance;
	var distance2 = b.distance;
	return distance1 - distance2;
}
function fnConstructCheckboxJson(){
	var myJsonObj = {};
		
	// fetch narrowdown value
      var noOptionCheckedInd = isNoOptionChecked();
	var cntChkBox = parseInt(document.getElementById("cbCount").value);
	var narrowdown="";/* Temporary code starts */
	var chkBoxObj;
	//create json obj dynamically
	for(var i=0; i < cntChkBox; i++){
		chkBoxObj = document.getElementById("cbx" + i);
            if(noOptionCheckedInd || chkBoxObj.checked){          
			eval("myJsonObj."+chkBoxObj.value+"=1");
		}
	}
	return myJsonObj;
}



function fnSelectStoreButton(storeUnitNumber,storeName,storeCity,storeState,street,zip){
	var store=new Object();
	store.unitNo =storeUnitNumber;
	store.storeName =storeName;
	store.city =storeCity;
	store.state =storeState;
	store.defaulted ="false";
	store.superK="false";
	store.street=street;
	store.zip=zip;
		
	//Change the store and redirect the user back to browse page
	fnChangeStoreInit(store,true);
	
}
function fnGetStoreServicesHtml155(strInfo){
 
		var html = "";
		var attrArray = new Array();
		var name, rank;
		for(var i=0; i < strInfo.attrname.length; i++){
			try{
				name = strInfo.attrname[i];
				if(name == "" || name == null)
					break;
					
				rank = strInfo.attrrank[i];
				flag = strInfo.attrflag[i];
				if(flag != ""){
					attrArray.push(new SearsAttr(name, rank, flag));
				}
			}catch(ex){
				break;
			}

		}
		
		if(attrArray.length > 0){
			attrArray.sort(sortAttributes);
			
			var attr;
			for(var i=0; i < attrArray.length; i++){
				var storeType = attrArray[i].name;
				if(storeType == "STORE PICK UP"){
					//if(EnableShopByLink == 1){
						html += "<br><span class=\"spu\">"+storeType.titleCase()+"</span><br>"
					//}
					}
			  		  else if(storeType == "PHARMACY"){
						var phone = fnFormatPhoneNo(strInfo.phPhone);
					  
						if(!isBlank(phone)&& !phoneNotValid(phone)){
					 		html += "<span>"+storeType.titleCase()+ " "+phone+"  </span> ";
						}
						else{
							 	html += "<span>"+storeType.titleCase()+"</span>";
						}
				 }
				 
				else if(storeType == "ONE HOUR PHOTO"){
					var phone = fnFormatPhoneNo(strInfo.ohpPhone);
					    
						if(!isBlank(phone)&& !phoneNotValid(phone)){
					 		html += "<span>"+storeType.titleCase()+ " "+phone+"  </span>";
						}
						else{
							 	html += "<span>"+storeType.titleCase()+"</span>";
						}
				 }
				else if(storeType == "PORTRAIT STUDIO"){
					var phone = fnFormatPhoneNo(strInfo.psPhone);
					   
						if(!isBlank(phone)&& !phoneNotValid(phone)){
					 		html += "<span>"+storeType.titleCase()+ " "+phone+"  </span>";
						}
						else{
							 	html += " <span>"+storeType.titleCase()+"</span> ";
						}
				 }
				else  if(storeType == "PICTURE MAKER"){
				var phone = fnFormatPhoneNo(strInfo.pmPhone);
						//var phone = this.getPictureMakerPhoneNumber();
					     
						if(!isBlank(phone)&& !phoneNotValid(phone)){
					 		html += " <span>"+storeType.titleCase()+ " "+phone+"  </span> ";
						}
						else{
							 	html += "<br><span>"+storeType.titleCase()+"</span><br>";
						}
				 }else  if(storeType == "HAS WEBSITE"){
				  		var dealerURL=	"http://www.searshometownstores.com/";
				  		dealerURL =dealerURL+strInfo.unitno+".html";
					    html += "<br><span><a href=\"javascript:fnWebsite('"+dealerURL+"');\">Website</a></span><br>"
			  				 	
					 
				 }
				else{
					html += "<span>"+storeType.titleCase()+"</span>"
				}
			}
			if(html != ""){
				html = "<p class=\"services\"><strong>Store Services:</strong>" + html + "</p>";
			}
		}
		return html;
}

		
function fnWebsite(website){
	window.open(website, "DealerWebsite","location=yes, menubar=yes,resizable=yes,scrollbars=yes,toolbar=yes,top=25,left=25");
}
	    	        
function fnOpenSeeMap(rowNum){
	if($('#dialog')){
		$('#dialog').remove();
	}
	// Append the See Map Container to body
	var mapContent = fnGenarateSeeMapPop();	
	$('body').append(mapContent);
	
	// Load the google map data in the container
	showMap(resultData,rowNum,searchLoc);
	//$('#dialog').center();
	//JQMODUL DIALOG 
	$('#dialog').jqm();
	$('#dialog').jqmShow();
	
	//Scroll Page Up
	$('html,body').animate({scrollTop: 0}, 600);
	
	//Attach the close button event
	$('#dialog a.closeWin').click(function(){
		$('#dialog').jqmHide();
		$('#dialog').remove();
	});
}


function fnGenarateSeeMapPop(){
	var mapContent =	"<div id='dialog' class='jqmWindow' style=\"BACKGROUND-COLOR: white\">\n";
	mapContent +=	"	<a class='closeWin' title='Close Window' href='javascript:;' ><img src='"+imagePath+"img/btn/btn_closemap.gif' alt='Close' /></a>\n";
	mapContent +=	"	<h2 class='title'><span>See Map</span></h2>\n";
	mapContent +=		"<div class=\"printPage\"><a href=\"javascript:window.print();\" class=\"print\">Print page</a></div><BR>";
	mapContent +=		"<div class=\"locinfo\"></div>";
	mapContent +=		"<div id='map_canvas' class=\"map\"></div>";
	mapContent +=		"<div class=\"printPage\"><a href=\"javascript:window.print();\" class=\"print\">Print page</a></div>";
	mapContent +=	"	</div>";
	return mapContent;
}

var popDirData = null;
function fnOpenDirections(rowNum){
	if($('#dialog')){
		$('#dialog').remove();
	}
	// Append the See Map Container to body
	var mapContent = fnGenarateDirectionsPop();	
	$('body').append(mapContent);
	
	$('input#popAddress').val($('input#txtAddress').val());
	$('input#popCity').val($('input#txtCity').val());
	$('select#popStateProvince').val($('select#selStateProvince').val());
	$('input#popPostalCode').val($('input#txtPostalCode').val());

	fnPopulateToAddr(resultData[rowNum]);
	
	//showPopDirections();
		
	// Get Directions on click of Search button
	$('input[alt="get directions"]').click(function(){
		showPopDirections();
	});
	
	// Get Directions on click on enter key in the form
	$("input#popAddress, input#popPostalCode, input#popCity, select#popStateProvince").keypress(function(e) {
		if(e.keyCode == 13) {
			showPopDirections();
		}
	}); 
	// Load the google map data in the container
	//showDirections(resultData[rowNum], searchLoc);
	//$('#dialog').center();
	//JQMODUL DIALOG 
	$('#dialog').jqm();
	$('#dialog').jqmShow();
	
	//Scroll Page Up
	$('html,body').animate({scrollTop: 0}, 600);
	
	//Attach the close button event
	$('#dialog a.closeWin').click(function(){
		$('#dialog').jqmHide();
		$('#dialog').remove();
	});
}

//This fubnction will be called when user clicks on get direction button in the popup
function showPopDirections(){
	try{
		//If search is in progress then wait
		if(waitFlag)return;

		//Clear existing error messages on screen
	$('div.popError').hide();

		//Perform Client side validation on address
		fnValidateAddressDir()

		// If it passes client side validation display the loading image
		fnShowWaitBox();
		/*	
		var address = searchLoc.address + "+" + searchLoc.city + "+" + searchLoc.state + "+" + searchLoc.zip+ "+US" ;
	
		if (geocoder) {
			if(jsonCountry[searchLoc.state] != 'undefined' && jsonCountry[searchLoc.state] == 1){
				geocoder.setBaseCountryCode(searchLoc.state);
			}else{
				geocoder.setBaseCountryCode("US");
		}
			geocoder.getLocations(address,geocodingResponseDir);
		}*/
		
					$('div#mapd_canvas').html('');
		$('div#mapd_canvas').attr('style','');
					$('div#directions').html('');
				
		var fromAddr="";
		var toAddr="";
		if(searchLoc.address){
			fromAddr += searchLoc.address.titleCase()+", ";
	            }
		if(searchLoc.city){
			fromAddr += searchLoc.city.titleCase()+", ";
	          }
		if(searchLoc.state){
			fromAddr += searchLoc.state+" ";
	      }
		if(searchLoc.zip){
			fromAddr += searchLoc.zip.substring(0, 5);
}
		//toAddr = popDirData.address.titleCase()+","+popDirData.city.titleCase() + "," + popDirData.stat + "," + popDirData.zip.substring(0, 5);
		toAddr = popDirData.latitude+","+popDirData.longitude;
		showDirections(fromAddr, toAddr);
	      }catch(exp){
	    var err = fnGetErrMsg(exp);
	    if (err == "Unknown Error")
	        err = exp;
		$('div.popError').html("<span>" + err+"</span>");
		$('div.popError').show();
		// Hide the loading image
		fnHideWaitBox();
		$('div#mapd_canvas').html('');
		$('div#mapd_canvas').attr('style','');
		$('div#directions').html('');
		return false;
}
}
function fnValidateAddressDir(){
		searchLoc.address = $('input#popAddress').val();
		searchLoc.city = $('input#popCity').val();
		searchLoc.state = $('select#popStateProvince').val();
		searchLoc.zip = $('input#popPostalCode').val();
		searchLoc.country = 'US';
		fromLoc = searchLoc;

		//client side validations
		if(!((!isBlank(searchLoc.city) && !isBlank(searchLoc.state)) || !isBlank(searchLoc.zip))){
				throw SEARS_LOCATOR_ERROR_NO_CITY_STATE_ZIP;
}
		if(!isBlank(searchLoc.zip)){
			if(!checkZip(searchLoc.zip)){
			throw SEARS_LOCATOR_ERROR_NO_CITY_STATE_ZIP;
			}
		}
}

//function geocodingResponseDir(geocoderData){
	//try{
	
		//if (!geocoderData || geocoderData.Status.code != 200) {
          //throw SEARS_LOCATOR_ERROR_INVALID_ADDRESS;
        //}
		//if(geocoderData.Placemark.length>1){
			// Multiple match found for the entered location, Show Alternate Locations
			//throw SEARS_LOCATOR_ERROR_MULTIPLE_ADDRESS_RET;
		//}else{
			//if(geocoderData.Placemark[0].AddressDetails.Accuracy >= 5){
				//searchLoc.latitude = geocoderData.Placemark[0].Point.coordinates[1];
				//searchLoc.longitude = geocoderData.Placemark[0].Point.coordinates[0];
				
				//Single match found for the entered location, show directions
				//$('div#mapd_canvas').html('');
				//$('div#mapd_canvas').attr('style','');
				//$('div#directions').html('');
				//showDirections(popDirData, searchLoc);
			//}else{
				//throw SEARS_LOCATOR_ERROR_INVALID_ADDRESS;
			//}
		//}
	//}catch(exp){
	    //var err = fnGetErrMsg(exp);
	    //if (err == "Unknown Error")
	        //err = exp;
		//$('div.popError').html("<span>" + err+"</span>");
		//$('div.popError').show();
		// Hide the loading image
		//fnHideWaitBox();
		//$('div#mapd_canvas').html('');
		//$('div#mapd_canvas').attr('style','');
		//$('div#directions').html('');
		//return false;
	//}
	      
//}

/**************************************************************************
 * Function Name     : fnPopulateToAddr
 * Description       : This function is used to generate the Store Address 
 * at the top the screen
 *************************************************************************/					
function fnPopulateToAddr(resultData){
	popDirData = resultData;
	var hldHtml ="<h3>To:</h3>";
	if(resultData.type2  == "A" && resultData.name == "Kmart") {
		hldHtml += "<p><strong>Kmart Stores</strong><br>";
	}else{
		hldHtml += "<p><strong>"+resultData.name.titleCase()+" Stores</strong><br>";	
	}		
	//display store address city and stae code
	hldHtml += "<span>" + resultData.address.titleCase() + "</span><br>";
	hldHtml += "<span>" + resultData.city.titleCase() + ", " + resultData.stat + " " + resultData.zip.substring(0, 5) + "</span>";
	hldHtml += "</p><p>";
	hldHtml += "<strong>Phone Number:</strong><br>";
	hldHtml += "</br>";
	if(resultData.phone1 != ""){
		hldHtml += "<span>"+fnFormatPhoneNo(resultData.phone1)+"</span><br>";
	}
	hldHtml += "</p>";
	$("div#toAddr").html(hldHtml);
}

function initialize() {
	try {
    	if (GBrowserIsCompatible()) {
        	geocoder = new GClientGeocoder();
      	}
	} catch(exp) {
		
		$('div.error').html("<span> An error occurred. The page needs to be refreshed </span>");
		$('div.error').show();
		// Hide the loading image
		fnHideWaitBox();
		return false;
		}

}

//Dummy Call back function
//function fnInitCallBack(){
//}

function fnGenarateDirectionsPop(){
	var mapContent =	"<div id='dialog' class='jqmWindow' style=\"BACKGROUND-COLOR: white\">\n";
	mapContent +=	"	<a class='closeWin' title='Close Window' href='javascript:;' ><img src='"+imagePath+"img/btn/btn_closemap.gif' alt='Close' /></a>\n";
	mapContent +=		"<div class=\"printPage\"><a href=\"javascript:window.print();\" class=\"print\">Print page</a></div>";
	mapContent +=	"	<h2 class='title'><span>See Directions</span></h2>\n";
	
	mapContent +=	"<div class=\"direct\">"+
					"	<div class=\"location\">"+
					"		<h3>From:</h3>"+
					"		<div class=\"input\">"+
					"			<label for=\"address\">Address</label>"+
					"			<input type=\"text\" name=\"txtAddress\" id=\"popAddress\" onchange=\"fnSetFlag();\"/>"+
					"		</div>"+
					"		<div class=\"input\">"+
					"			<label for=\"city\">City</label>"+
					"			<input type=\"text\" name=\"txtCity\" id=\"popCity\" onchange=\"fnSetFlag();\"/>"+
					"			<label class=\"state\" for=\"state\">State</label>"+
					"			<select name=\"selStateProvince\" id=\"popStateProvince\" onchange=\"fnSetFlag();\">"+
					"				<option value=\"\"></option><option value=\"AK\">AK</option>"+
					
					"<option value=\"AL\">AL</option>"+
					"<option value=\"AR\">AR</option>"+
					"<option value=\"AZ\">AZ</option>"+
					"<option value=\"CA\">CA</option>"+
					"<option value=\"CO\">CO</option>"+
					"<option value=\"CT\">CT</option>"+
					"<option value=\"DC\">DC</option>"+
					"<option value=\"DE\">DE</option>"+
					"<option value=\"FL\">FL</option>"+
					"<option value=\"GA\">GA</option>"+
					"<option value=\"GU\">GU</option>"+
					"<option value=\"HI\">HI</option>"+
					"<option value=\"IA\">IA</option>"+
					"<option value=\"ID\">ID</option>"+
					"<option value=\"IL\">IL</option>"+
					"<option value=\"IN\">IN</option>"+
					"<option value=\"KA\">KA</option>"+
					"<option value=\"KS\">KS</option>"+
					"<option value=\"KY\">KY</option>"+
					"<option value=\"LA\">LA</option>"+
					"<option value=\"MA\">MA</option>"+
					"<option value=\"MD\">MD</option>"+
					"<option value=\"ME\">ME</option>"+
					"<option value=\"MI\">MI</option>"+
					"<option value=\"MN\">MN</option>"+
					"<option value=\"MO\">MO</option>"+
					"<option value=\"MS\">MS</option>"+
					"<option value=\"MT\">MT</option>"+
					"<option value=\"NC\">NC</option>"+
					"<option value=\"ND\">ND</option>"+
					"<option value=\"NE\">NE</option>"+
					"<option value=\"NH\">NH</option>"+
					"<option value=\"NJ\">NJ</option>"+
					"<option value=\"NM\">NM</option>"+
					"<option value=\"NV\">NV</option>"+
					"<option value=\"NY\">NY</option>"+
					"<option value=\"OH\">OH</option>"+
					"<option value=\"OK\">OK</option>"+
					"<option value=\"OR\">OR</option>"+
					"<option value=\"PA\">PA</option>"+
					"<option value=\"PR\">PR</option>"+
					"<option value=\"RI\">RI</option>"+
					"<option value=\"SC\">SC</option>"+
					"<option value=\"SD\">SD</option>"+
					"<option value=\"TN\">TN</option>"+
					"<option value=\"TX\">TX</option>"+
					"<option value=\"UT\">UT</option>"+
					"<option value=\"VA\">VA</option>"+
					"<option value=\"VI\">VI</option>"+
					"<option value=\"VT\">VT</option>"+
					"<option value=\"WA\">WA</option>"+
					"<option value=\"WI\">WI</option>"+
					"<option value=\"WV\">WV</option>"+
					"<option value=\"WY\">WY</option>"+

					
					
					"			</select>"+
					"		</div>"+
					"		<div class=\"input\">"+
					"			<label for=\"zipcode\">ZIP Code</label>"+
					"			<input type=\"text\" name=\"txtPostalCode\" id=\"popPostalCode\" maxlength=\"10\" onchange=\"fnSetFlag();\"/>"+
					"		</div>"+
					"		<div class=\"search\">"+
					"				<input type=\"image\" src=\""+imagePath+"img/storeLocator/btn_getdirec.gif\" width=\"111\" height=\"25\" alt=\"get directions\">"+
					"		</div>"+
					"	</div>		"+
					"	<font size=\"2\" color=\"black\"><div class=\"locinfo narrow\" id=\"toAddr\"></div></font>"+
					"</div>";
	
	mapContent +=		"<div id=\"tdError\" class=\"popError\" style=\"margin:245pt 5px 4px;display:none;\"></div>";
	
	mapContent +=		"<div class=\"locinfo\"></div>";
	mapContent +=		"<table class=\"directions\" style=\"clear: left;\"><tr><th>&nbsp;</th></tr>";
	mapContent +=    	"<tr><td valign=\"top\"><div id='mapd_canvas' class=\"map\"></div></td>";
	mapContent +=    	"<tr><th><BR>&nbsp;</th>";
	mapContent +=    	"<tr><td valign=\"top\"><div id='directions' style=\"width: 600px; font-size:12px;\"></div></td></tr></table>";
	mapContent +=		"<div class=\"printPage\"><a href=\"javascript:window.print();\" class=\"print\">Print page</a></div>";
	mapContent +=	"	</div>";
	return mapContent;
	}


function fnSetFlag(){

}

    function createCenterMarker(point) {
		
		var centerIcon = new GIcon(G_DEFAULT_ICON);
		centerIcon.image = "http://maps.google.com/mapfiles/arrow.png";
		centerIcon.shadow = "http://maps.google.com/mapfiles/arrowshadow.png";
		centerIcon.iconSize = new GSize(39, 34);
		centerIcon.shadowSize = new GSize(39, 34);
		centerIcon.iconAnchor = new GPoint(9, 34);
		centerIcon.infoWindowAnchor = new GPoint(9, 2);
    	
    	
    	//getAddress(point);
		// Set up our GMarkerOptions object
		markerOptions = { icon:centerIcon };
		var marker = new GMarker(point, markerOptions);
		//marker.openInfoWindowHtml("You are<BR>here");
		
		//GEvent.addListener(marker, "click", function() {
			//marker.openInfoWindowHtml("3333 Beverly Rd,<BR>Hoffman Estates,<BR>IL 60179");
		//});
		return marker;
	}
    


		    
    // Creates a marker whose info window displays the letter corresponding
	// to the given index.
	function createMarker(point,locResult) {
	  	// Create a lettered icon for this point using our icon class
		var letter;
		if(storeId==10151)
			letter = String.fromCharCode("K".charCodeAt(0));
		else
			letter = String.fromCharCode("S".charCodeAt(0));
		
	  	var letteredIcon = new GIcon(G_DEFAULT_ICON);
	  	letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
		//letteredIcon.image = imagePath+"favicon.ico";
		letteredIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		letteredIcon.iconSize = new GSize(20, 30);
		letteredIcon.shadowSize = new GSize(30, 20);
		letteredIcon.iconAnchor = new GPoint(9, 34);
		letteredIcon.infoWindowAnchor = new GPoint(9, 2);
    
	  // Set up our GMarkerOptions object
	  markerOptions = { icon:letteredIcon };
	  var marker = new GMarker(point, markerOptions);
	
	  GEvent.addListener(marker, "click", function() {
	    marker.openInfoWindowHtml("<STRONG>"+locResult.name.titleCase()+"&nbsp;stores</STRONG><BR>"+locResult.address.titleCase()+",<BR>"+locResult.city.titleCase() + ",<BR>" + locResult.stat + " " + locResult.zip );	    
	  });
	  return marker;
	}
	
	function createSelectMarker(point,locResult) {
	  	// Create a lettered icon for this point using our icon class
		var letter;
		if(storeId==10151)
			letter = String.fromCharCode("K".charCodeAt(0));
		else
			letter = String.fromCharCode("S".charCodeAt(0));
		
	  	var letteredIcon = new GIcon(G_DEFAULT_ICON);
	  	letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
		//letteredIcon.image = imagePath+"favicon.ico";
		letteredIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		letteredIcon.iconSize = new GSize(27, 40);
		letteredIcon.shadowSize = new GSize(40, 30);
		letteredIcon.iconAnchor = new GPoint(9, 34);
		letteredIcon.infoWindowAnchor = new GPoint(9, 2);
    
	  // Set up our GMarkerOptions object
	  markerOptions = { icon:letteredIcon };
	  var marker = new GMarker(point, markerOptions);
      //marker.openInfoWindowHtml(locResult.address.titleCase()+",<BR>"+locResult.city.titleCase() + ",<BR>" + locResult.stat + " " + locResult.zip );	    

	  GEvent.addListener(marker, "click", function() {
	    marker.openInfoWindowHtml("<STRONG>"+locResult.name.titleCase()+"&nbsp;stores</STRONG><BR>"+locResult.address.titleCase()+",<BR>"+locResult.city.titleCase() + ",<BR>" + locResult.stat + " " + locResult.zip );	    
	  });
	  return marker;
	}
	

    function showMap(locationResult,selectLoc, originAddress){
    	var txtlat = originAddress.latitude;
    	var txtlng = originAddress.longitude;
    	var map = new GMap2(document.getElementById("map_canvas"),{size: new GSize(600,500)});
    	map.enableScrollWheelZoom();
        map.setCenter(new GLatLng(txtlat, txtlng),9);
		map.addControl(new GLargeMapControl3D());
		map.addControl(new GMapTypeControl());
		map.addOverlay(createCenterMarker(new GLatLng(txtlat, txtlng)));
        
        //var latlngbounds = new GLatLngBounds( );
		for (var i = 0; i < locationResult.length && i < MAX_MATCHES; i++) {
          
          var point = new GLatLng(locationResult[i].latitude,locationResult[i].longitude);
          if(i==selectLoc){
          	map.addOverlay(createSelectMarker(point,locationResult[i]));
          } else{
	          map.addOverlay(createMarker(point,locationResult[i]));
	      }
          //latlngbounds.extend( point);
          
        }
         //map.setCenter(new GLatLng(txtlat, txtlng),map.getBoundsZoomLevel( latlngbounds ));
    }
    
    function showDirections(fromAddr,toAddr){
    	//var txtlat = originAddress.latitude;
    	//var txtlng = originAddress.longitude;
    	var map = new GMap2(document.getElementById("mapd_canvas"),{size: new GSize(600,400)});
    	//map.setCenter(new GLatLng(txtlat, txtlng),12);
		map.addControl(new GLargeMapControl3D());
		map.addControl(new GMapTypeControl());
		directions = new GDirections(map, document.getElementById("directions"));
      	GEvent.addListener(directions, "error", handleDirErrors);
       	directions.load("from:"+fromAddr+" to: "+toAddr);
      	fnHideWaitBox();
    }	    			

	function handleDirErrors() {
	    try{
	        if (directions.getStatus().code == G_GEO_SUCCESS)
	                throw SEARS_LOCATOR_ERROR_GOOGLE_GEO_UNKNOWN_ERROR;  
	        else if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	           throw SEARS_LOCATOR_ERROR_GOOGLE_GEO_UNKNOWN_ADDRESS;
	        else if (directions.getStatus().code == G_GEO_SERVER_ERROR)
	            throw EARS_LOCATOR_ERROR_GOOGLE_GEO_SERVER_ERROR;
	        else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
				throw SEARS_LOCATOR_ERROR_GOOGLE_GEO_BAD_REQUEST;
	        else if (directions.getStatus().code == G_GEO_UNKNOWN_DIRECTIONS)
	            throw SEARS_LOCATOR_ERROR_GOOGLE_GEO_UNKNOWN_DIRECTIONS;
	    }catch(exp){
		    var err = fnGetErrMsg(exp);
		    if (err == "Unknown Error")
		        err = exp;
			$('div.popError').html("<span>" + err+"</span>");
			$('div.popError').show();
			// Hide the loading image
			fnHideWaitBox();
			$('div#mapd_canvas').html('');
			$('div#mapd_canvas').attr('style','');
			$('div#directions').html('');
			return false;
		}
	 }
	 
/**** Popup plugin : Starts ***/
/*
 * jqModal - Minimalist Modaling with jQuery
 *
 * Copyright (c) 2007 Brice Burgess <bhb@iceburg.net>, http://www.iceburg.net
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * $Version: 2007.??.?? +r12 beta
 * Requires: jQuery 1.1.3+
 */
(function($) {
/**
 * Initialize a set of elements as "modals". Modals typically are popup dialogs,
 * notices, modal windows, and image containers. An expando ("_jqm") containing
 * the UUID or "serial" of the modal is added to each element. This expando helps
 * reference the modal's settings in the jqModal Hash Object (jQuery.jqm.hash)
 * 
 * Accepts a parameter object with the following modal settings;
 * 
 * (Integer) zIndex - Desired z-Index of the modal. This setting does not override (has no effect on) preexisting z-Index styling (set via CSS or inline style).  
 * (Integer) overlay - [0-100] Translucency percentage (opacity) of the body covering overlay. Set to 0 for NO overlay, and up to 100 for a 100% opaque overlay.  
 * (String) overlayClass - This class is applied to the body covering overlay. Allows CSS control of the overlay look (tint, background image, etc.).
 * (String) closeClass - A close trigger is added to all elements matching this class within the modal.
 * (Mixed) trigger - An open trigger is added to all matching elements within the DOM. Trigger can be a selector String, a jQuery collection of elements, a DOM element, or a False boolean.
 * (Mixed) ajax - If not false; The URL (string) to load content from via an AJAX request.
 *                If ajax begins with a "@", the URL is extracted from the requested attribute of the triggering element.
 * (Mixed) target - If not false; The element within the modal to load the ajax response (content) into. Allows retention of modal design (e.g. framing and close elements are not overwritten by the AJAX response).
 *                  Target may be a selector string, jQuery collection of elements, or a DOM element -- but MUST exist within (as a child of) the modal.
 * (Boolean) modal - If true, user interactivity will be locked to the modal window until closed.
 * (Boolean) toTop - If true, modal will be posistioned as a first child of the BODY element when opened, and its DOM posistion restored when closed. This aids in overcoming z-Index stacking order/containment issues where overlay covers whole page *including* modal.
 * (Mixed) onShow - User defined callback function fired when modal opened.
 * (Mixed) onHide - User defined callback function fired when modal closed.
 * (Mixed) onLoad - User defined callback function fired when ajax content loads.
 *
 * @name jqm
 * @param Map options User defined settings for the modal(s).
 * @type jQuery
 * @cat Plugins/jqModal
 */
$.fn.jqm=function(p){
var o = {
zIndex: 9998,
overlay: 50,
overlayClass: 'jqmOverlay',
closeClass: 'jqmClose',
trigger: '.jqModal',
ajax: false,
target: false,
modal: false,
toTop: false,
onShow: false,
onHide: false,
onLoad: false
};


// For each element (aka "modal") $.jqm() has been called on;
//  IF the _jqm expando exists, return (do nothing)
//  ELSE increment serials and add _jqm expando to element ("serialization")
//    *AND*...
return this.each(function(){if(this._jqm)return;s++;this._jqm=s;

// ... Add this element's serial to the jqModal Hash Object 
//  Hash is globally accessible via jQuery.jqm.hash. It consists of;
//   c: {obj} config/options
//   a: {bool} active state (true: active/visible, false: inactive/hidden)
//   w: {JQ DOM Element} The modal element (window/dialog/notice/etc. container)
//   s: {int} The serial number of this modal (same as "H[s].w[0]._jqm")
//   t: {DOM Element} The triggering element
// *AND* ...
H[s]={c:$.extend(o,p),a:false,w:$(this).addClass('jqmID'+s),s:s};

// ... Attach events to trigger showing of this modal
o.trigger&&$(this).jqmAddTrigger(o.trigger);
});};

// Adds behavior to triggering elements via the hide-show (HS) function.
// 
$.fn.jqmAddClose=function(e){return HS(this,e,'jqmHide');};
$.fn.jqmAddTrigger=function(e){return HS(this,e,'jqmShow');};

// Hide/Show a modal -- first check if it is already shown or hidden via the toggle state (H[{modal serial}].a)
$.fn.jqmShow=function(t){return this.each(function(){!H[this._jqm].a&&$.jqm.open(this._jqm,t)});};
$.fn.jqmHide=function(t){return this.each(function(){H[this._jqm].a&&$.jqm.close(this._jqm,t)});};

$.jqm = {
hash:{},

// Function is executed by $.jqmShow to show a modal
// s: {INT} serial of modal
// t: {DOM Element} the triggering element

// set local shortcuts
//  h: {obj} this Modal's "hash"
//  c: {obj} (h.c) config/options
//  cc: {STR} closing class ('.'+h.c.closeClass)
//  z: {INT} z-Index of Modal. If the Modal (h.w) has the z-index style set it will use this value before defaulting to the one passed in the config (h.c.zIndex)
//  o: The overlay object
// mark this modal as active (h.a === true)
// set the triggering object (h.t) and the modal's z-Index.
open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=/^\d+$/.test(h.w.css('z-index'))&&h.w.css('z-index')||c.zIndex,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});h.t=t;h.a=true;h.w.css('z-index',z);
 
 // IF the modal argument was passed as true;
 //    Bind the Keep Focus Function if no other Modals are open (!A[0]),
 //    Add this modal to the opened modals stack (A) for nested modal support,
 //    and Mark overlay to show wait cursor when mouse hovers over it.
 if(c.modal) {!A[0]&&F('bind');A.push(s);o.css('cursor','wait');}
 
 // ELSE IF an overlay was requested (translucency set greater than 0);
 //    Attach a Close event to overlay to hide modal when overlay is clicked.
 else if(c.overlay > 0)h.w.jqmAddClose(o);
 
 // ELSE disable the overlay
 else o=false;

 // Add the Overlay to BODY if not disabled.
 h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):false;
 
 // IF IE6;
 //  Set the Overlay to 100% height/width, and fix-position it via JS workaround
 if(ie6&&$('html,body').css({height:'100%',width:'100%'})&&o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}

 // IF the modal's content is to be loaded via ajax;
 //  determine the target element {JQ} to recieve content (r),
 //  determine the URL {STR} to load content from (u)
 if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?$(r,h.w):$(r),u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u;
 
  // Load the Content (and once loaded);
   // Fire the onLoad callback (if exists),
   // Attach closing events to elements inside the modal that match the closingClass,
   // and Execute the jqModal default Open Callback
  r.load(u,function(){c.onLoad&&c.onLoad.call(this,h);cc&&h.w.jqmAddClose($(cc,h.w));O(h);});}
 
 // ELSE the modal content is NOT to be loaded via ajax;
 //  Attach closing events to elements inside the modal that match the closingClass
 else cc&&h.w.jqmAddClose($(cc,h.w));

 // IF toTop was passed and an overlay exists;
 //  Remember the DOM posistion of the modal by inserting a tagged (matching serial) <SPAN> before the modal
 //  Move the Modal from its current position to a first child of the body tag (after the overlay)
 c.toTop&&h.o&&h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);	
 
 // Execute user defined onShow callback, or else show (make visible) the modal.
 // Execute the jqModal default Open Callback.
 // Return false to prevent trigger click from being followed.
 (c.onShow)?c.onShow(h):h.w.show();O(h);return false;
 
},

// Function is executed by $.jqmHide to hide a modal
  // mark this modal as inactive (h.a === false)
close:function(s){var h=H[s];h.a=false;
 // If modal, remove from modal stack.
   // If no modals in modal stack, unbind the Keep Focus Function
 if(h.c.modal){A.pop();!A[0]&&F('unbind');}
 
 // IF toTop was passed and an overlay exists;
 //  Move modal back to its previous ("remembered") position.
 h.c.toTop&&h.o&&$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
 
 // Execute user defined onHide callback, or else hide (make invisible) the modal and remove the overlay.
 if(h.c.onHide)h.c.onHide(h);else{h.w.hide()&&h.o&&h.o.remove()}return false;
}};

// set jqModal scope shortcuts;
//  s: {INT} serials placeholder
//  H: {HASH} shortcut to jqModal Hash Object
//  A: {ARRAY} Array of active/visible modals
//  ie6: {bool} True if client browser is Internet Explorer 6
//  i: {JQ, DOM Element} iframe placeholder used to prevent active-x bleedthrough in IE6
//    NOTE: It is important to include the iframe styling (iframe.jqm) in your CSS!
//     *AND* ...
var s=0,H=$.jqm.hash,A=[],ie6=($.browser.msie && parseInt($.browser.version) < 8),i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),

//  O: The jqModal default Open Callback;
//    IF ie6; Add the iframe to the overlay (if overlay exists) OR to the modal (if an iframe doesn't already exist from a previous opening)
//    Execute the Modal Focus Function
O=function(h){if(ie6)h.o&&h.o.html('<p style="width:100%;height:100%"/>').prepend(i)||(!$('iframe.jqm',h.w)[0]&&h.w.prepend(i)); f(h);},

//  f: The Modal Focus Function;
//    Attempt to focus the first visible input within the modal
f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(e){}},

//  F: The Keep Focus Function;
//    Binds or Unbinds (t) the Focus Examination Function to keypresses and clicks
F=function(t){$()[t]("keypress",x)[t]("keydown",x)[t]("mousedown",x);},

//  x: The Focus Examination Function;
//    Fetch the current modal's Hash as h (supports nested modals)
//    Determine if the click/press falls within the modal. If not (r===true);
//      call the Modal Focus Function and prevent click/press follow-through (return false [!true])
//      ELSE if so (r===false); follow event (return true [!false])
x=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);r&&f(h);return !r;},

// hide-show function; assigns click events to trigger elements that 
//   hide, show, or hide AND show modals.

// Expandos (jqmShow and/or jqmHide) are added to all trigger elements. 
// These Expandos hold an array of modal serials {INT} to show or hide.

//  w: {DOM Element} The modal element (window/dialog/notice/etc. container)
//  e: {DOM Elemet||jQ Selector String} The triggering element
//  y: {String} Type (jqmHide||jqmShow)

//  s: {array} the serial number of passed modals, calculated below;
HS=function(w,e,y){var s=[];w.each(function(){s.push(this._jqm)});

// for each triggering element attach the jqmHide or jqmShow expando (y)
//  or else expand the expando with the current serial array
 $(e).each(function(){if(this[y])$.extend(this[y],s);
 
 // Assign a click event on the trigger element which examines the element's
 //  jqmHide/Show expandos and attempts to execute $.jqmHide/Show on matching modals
 else{this[y]=s;$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return false;});}});return w;};
})(jQuery);
/**** Popup plugin : Ends ***/
