// ############################ INITIALIZATION #################################
var debugMode = false; // Set the variable to "true" to view the alerts in all dealerlocator JS functions (Accross diffferent JS files also)
debugMode = document.location.search.indexOf("debugMode") != -1 ? true : false;
var positionedDealer = null;
var pinarray = new Array();
var dealerResultsGlobal = null;
var stateCodes='AK,AL,AR,AZ,CA,CO,CT,DC,DE,FL,GA,HI,IA,ID,IL,IN,KS,KY,LA,MA,MD,ME,MI,MN,MO,MS,MT,NC,ND,NE,NH,NJ,NM,NV,NY,OH,OK,OR,PA,RI,SC,SD,TN,TX,UT,VA,VT,WA,WI,WV,WY';

var eventGTR=false;
var searchTextGlobal=null; //variables to store searchText and radius 
var radiusGlobal=null;
var stateMgr = new DLStateManager();
// ############################ BEGIN DWR data acquisition code ################

var GENERAL_ERROR = 'There was a problem with your request. Please try again.';  // Common effor message accross the dealer locator application
var LOADING_MESSAGE = 'Please wait.. The search is under progress'; // Message to be displayed to while the DWR loading the results
var SENDING_EMAIL = 'Sending e-mail to user'; // Messae used while saving the dealer info to E-mail

// added by kartik for GTR
var gtrFilter = false;
// end of modification 


if(!debugMode) DWREngine.setErrorHandler(function(e) { alert(GENERAL_ERROR); });
// Array "dealerAssets" contains all the resource bundle properties we have in our application.
/*
	The below method makes a DWR call to DealerLocatorImpl.java class "getMappedDealers()" to get the search results for the given information
	Then it will pass on those results to call back function "displayDealerSearchResults()" which renders the results on page
*/
//alert("here"); -- commented out alert
var str = location.href;
			  if(str.indexOf('espanol') > -1) {
                crmSetCookie("org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE","es_US","","/","www.nissanusa.com","");
              }else{
                crmSetCookie("org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE","en_US","","/apps","www.nissanusa.com","");
              }
              

function searchDealers(searchText, radius,gtr){
	
	//alert("In search Dealers"+ searchText+ "---" + radius);
	if(debugMode){
		alert("Entered function searchDealers()");
		alert("Search Text: "+searchText +", Distance: "+radius);
	}
	
	
	//store the present searchText and radius in global variables. 
	searchTextGlobal=searchText;
	radiusGlobal=radius;


    /** added by kartik for GTR **/
    gtrFilter = gtr;
	/** end of modification **/


	if(gtr){
		if($("gtrCheckBox")){
			document.getElementById("gtrCheckBox").checked=true;
		}
	}else{
		
		
		if($("gtrCheckBox")){
			searchingStatus();
			clearDivs();
			document.getElementById("gtrCheckBox").checked=false;
			eventGTR=false;
			
		}
	}
	
	if($("noGtrFoundDiv")){
		document.getElementById("noGtrFoundDiv").style.display="none";
	//	document.getElementById("noGtrMsgDiv_2").style.display="none";
	//	document.getElementById("GTRCertDealersDiv").style.display="none";
		document.getElementById("dealer_countDiv").style.display="none";
	}
	// Th following is the division to display errors
	document.getElementById('dwrErrorRegion').innerHTML ="";
	document.getElementById("dwrErrorRegion").style.display="block";
	// The following code displayes a "wait" message to the user during the search process - Commented out as it is not required
	
	if($("resultsDiv"))
	{
		document.getElementById('resultsDiv').innerHTML="";
	}
	
	// DWRUtil.useLoadingMessage(LOADING_MESSAGE);
	if(debugMode) alert("Before DealerLocatorFacade -> getMappedDealerCall");

	// The following mthod call validated the given search text & returns "true" if there is any problem with the text
	var dealerLocator = validateSearchText(searchText, radius,gtr);
	
	if(dealerLocator!=null){
		if(dealerLocator!=true){
			if(debugMode){
				alert("Entered zipcode : "+dealerLocator["zipCode"]);
				alert("Entered city : "+dealerLocator["city"]);
				alert("Entered state : "+dealerLocator["state"]);
			}
			
			
			// AJAX call to get the dealers to the given search information
			DealerLocatorFacade.getMappedDealers(dealerLocator, displayDealerSearchResults);
			stateMgr.changeState(stateMgr.states.SEARCHINPROGRESS);
		}
	}

	if(debugMode){
		alert("Leaving function searchDealers()");
	}
	
}

/*
 *	The following method validates the search text and splits in to zipcode or city, state
 *	In case the text is improper, it will display an error on the page.
 *	This function first checks if a number is entered in the field. If a number is entered it checks for the valid zipCode.
 *	Else it returns a error message.
 *	If number is not entered it divides the search Text into city and state which is then passed to search for dealers.
*/
function validateSearchText(searchText, radius,gtr){
	if(debugMode){
		alert("Entered function validateSearchText()");
		alert("Search text:"+searchText);
		alert("Radius:"+radius);
	}

	var dealerLocator;
	searchText = trimDE(searchText);
	//alert("Trimmed string:*Start*"+searchText+"*END*");
	// If the searchText is a number check if it is a valid zipCode or not.
	if(searchText == null || searchText ==''){
		document.getElementById("topbar").className="topbar";
		showDiv();
		//document.getElementById('dwrErrorRegion').innerHTML = 'Please enter a "zip code" v or "city, state" to search dealers.';
	}else if(!isNaN(searchText)){
		 // The following regular expression is used to check whether the zipcode is all number with a length of 5
		 var validZip = /^[0-9]{5}$/;
		 // The following condition checks for blank and all "0" value zipcode. These two cases are not valid
		 if((searchText && searchText != '') && (!validZip.test(searchText)  || searchText=='00000')) {
			  closebar();
			  // document.getElementById('dwrErrorRegion').innerHTML = 'Please enter a valid zip code.';
			  document.getElementById("topbar").className="topbarZip";
			  showDiv();

			  return true;
	     }
	     else{
			  // This loop is executed if the entered search text is a zipcode. The code creates a "dealerLocator" object out of 								  			  // the passed search text and the radius/distance that was provided.
			  closebar();
			  dealerLocator = { zipCode:searchText, radius:radius,gtr:gtr};
			  updateMeta('zipcode', searchText);
			  return dealerLocator;
	     }
	}else{
		// Any string can be added to searchString as the parseaddress() Method of findService of Map Point places city and state correctly
		// only if there is a street mentioned in the search string.
		var searchString="street,";
		searchString +=searchText;
		//alert('radius'+radius);
		//alert('radiusGlobal'+radiusGlobal);
		//alert('searchString'+searchString);

		// Ajax call to parse the given search text to a valid address. There is a "inline" call back function which takes the parsed address
		// to get the mapped dealers around that address
		DealerLocatorFacade.validateAddress(searchString, 'true', function(addressList){
			var addressObj = addressList[0];
			var zipCode = addressObj["zipCode"];
	 		var city = addressObj["city"];
			var state = addressObj["state"];

			//alert(zipCode+"-"+city+"-"+state);

             // start of SR 15499
		    var regexString =  new RegExp("[\\d-<>@;:/|'`!#%\+\*\?\.]");
 
 			if(searchString.match(regexString))
             {                        
			    document.getElementById('dwrErrorRegion').innerHTML = 'Please enter a valid "zipcode" or "city, state" combination.';
                         return false;
			 }
            // end of SR 15499

			//alert("State: "+state);
			if(zipCode!= null && zipCode != ""){
				//alert("In Zipcode:"+zipCode);
				closebar();
				dealerLocator = { zipCode:zipCode, radius:radius,gtr:gtr};
				updateMeta('zipcode', zipCode);
				DealerLocatorFacade.getMappedDealers(dealerLocator, displayDealerSearchResults);
			}else if(state==null||state==""){
				//alert("In state");
				//alert("Search text length:"+searchString.length);
				//alert("Substring - first 5 letters:"+searchString.substring(7,12));
				if(trimDE(searchString).length==12 && (trimDE(searchString.substring(7,12)).length == 5) && !isNaN(searchString.substring(7,12))){
					//alert("In zipcode section");
					// The following regular expression is used to check whether the zipcode is all number with a length of 5
					 var validZip = /^[0-9]{5}$/;
					 // The following condition checks for blank and all "0" value zipcode. These two cases are not valid
					 if(!validZip.test(searchString.substring(7,12)) || searchString.substring(7,12)=='00000') {
						   //alert("In Illegal zipcode");
						   document.getElementById("topbar").className="topbarZip";
						   showDiv();
						  //document.getElementById('dwrErrorRegion').innerHTML = 'Please enter a valid zip code.';
						  return true;
					 }
					 else{
						  //alert("In legal zipcode");
						  // This loop is executed if the entered search text is a zipcode. The code creates a "dealerLocator" object out of 								  			  // the passed search text and the radius/distance that was provided.
						  closebar();
						  dealerLocator = { zipCode:searchString.substring(7,12), radius:radius,gtr:gtr};
						  updateMeta('zipcode', searchString.substring(7,12));
						  DealerLocatorFacade.getMappedDealers(dealerLocator, displayDealerSearchResults);
					 }
				}else{
					//alert("In no information");
					 closebar();
					document.getElementById('dwrErrorRegion').innerHTML = 'Please enter a valid "zipcode" or "city, state" combination.';
					//showDiv();
					return true;
				}
			}else{
				// The following code makes a dealerLocator object with the parsed city, state and radius info.
				// Which in turn passed to an AJAX call to get the dealers around that address
				closebar();
				//alert("Pass..city&state");
				var dealerLocator = { city:city, state:state, radius:radius,gtr:gtr};
				updateMeta('cityState', city+', '+state);
				DealerLocatorFacade.getMappedDealers(dealerLocator, displayDealerSearchResults);
			}
 		 }); // end of call back function.
	} // end of else

	if(debugMode){
		alert("Leaving function validateSearchText()");
	}
} // end of validateSearchText function


/*
	The following method is the call back function which renders the dealer search results to the dealerSearch.jsp page
	The function basically does the following tasks
	1. Update the <div> 'searchResultsCount" to show the number of dealers found in the search and the pagination functionality if required(i.e if the no of dealers >10)
	2. Call to 'renderDealersInfo" to render the dealer information on the page
*/
function displayDealerSearchResults(dealerResultsObject){
	if(debugMode){
		alert("Entered function displayDealerSearchResults()");
		alert(DWRUtil.toDescriptiveString(dealerResultsObject, 2));
	}

	try {
		// The following loop conditions checked whether any dealers returned in the search
		//alert("In to try for displayDealers");
		if(dealerResultsObject != null && dealerResultsObject["numberOfDealers"] > 0){
			// Setting up the results in the global parameter
			
			//checks whether GT-R filter checkbox is present or not,if not create's the filter check box.
			if (!$("gtrSelectDiv"))
			{
				//alert("Creating div's for GTR");
				var gtrSelectDiv=document.createElement("div");
				gtrSelectDiv.id="gtrSelectDiv";
				
				var checkBoxDiv=document.createElement("div");
				checkBoxDiv.id="checkBoxDiv";
				var gtrCheckBox=document.createElement("input");
				gtrCheckBox.type="checkbox";
				gtrCheckBox.id="gtrCheckBox";

				// added by kartik for GTR
                if(gtrFilter==true)
				{
                  gtrCheckBox.checked = true;
                }
                // end of modification

				gtrCheckBox.onclick=selectGTR;
				
				checkBoxDiv.appendChild(gtrCheckBox);
				gtrSelectDiv.appendChild(checkBoxDiv);
			
				
				var gtrText = document.createElement("div");
				gtrText.id = "gtrText";
				gtrText.className = "gtr_filter";
				
				var gtrCondition=dealerAssets["dealerLocator.searchResults.GTRCondition"];
				/*if(document.dealerLocatorForm.hdnLocaleLanguage.value=='es'){
					var gtrCondition=dealerAssets["dealerLocator_es.searchResults.GTRCondition"];
				}
				else{
					var gtrCondition=dealerAssets["dealerLocator.searchResults.GTRCondition"];
				}*/

				gtrText.appendChild(document.createTextNode(gtrCondition));
				gtrSelectDiv.appendChild(gtrText);			
				
				
				jQuery(gtrSelectDiv).css("position","absolute");
				jQuery(gtrSelectDiv).css("top","12px");
				jQuery(gtrSelectDiv).css("font-size","9px");
				jQuery(gtrSelectDiv).css("font-weight","bold");
				jQuery(gtrSelectDiv).css("vertical-align","top"); 
				document.getElementById("searchResultsCount").appendChild(gtrSelectDiv);
			}

			if($("searchProgressDiv"))
			{
				document.getElementById("searchProgressDiv").style.display="none";
			}


			dealerResultsGlobal = dealerResultsObject["dealers"];
			var positionDealersArray = dealerResultsObject["dealers"];
			
			var centerPoint = new VELatLong(dealerResultsObject["centerLatitude"],dealerResultsObject["centerLongitude"]);
			if(positionDealersArray.length > 1){
				document.getElementById("dwrErrorRegion").innerHTML=positionDealersArray.length + ' '+dealerAssets["dealerLocator.searchResults.results"] + ' '+DWRUtil.getValue('searchText');
			}else{
				document.getElementById("dwrErrorRegion").innerHTML=positionDealersArray.length + ' '+dealerAssets["dealerLocator.searchResults.singleResult"] + ' '+DWRUtil.getValue('searchText');
			}
			var paginationCode;
			
			if(positionDealersArray.length >10){
				/* Math.ceil is used so that the ceiling is returned */
				var pages = Math.ceil(positionDealersArray.length/10);

			
				if(debugMode){
					alert("Number of pages:"+pages);
				}

				if (!$("resultsDiv")) {
					resultsDivEle = document.createElement("div");
					resultsDivEle.id = "resultsDiv";
					resultsDivEle.setAttribute("class","resultsDiv");
					
					document.getElementById("searchResultsCount").appendChild(resultsDivEle);
				}else{
					resultsDivEle = $("resultsDiv");
					document.getElementById("resultsDiv").style.visibility="visible";
				}

				paginationCode = '<table style="text-align:right;#margin-top:10px;font-size:8pt"><tr><td width="139px;"></td><td style="width:10px; vertical-align:middle"><a href="javascript:navigation(\'left\')"><img src="/img/global/icon/left-arrow.gif" alt="previous" class="paginationArrows"/></a></td><td style="font-size:8pt">'+dealerAssets["dealerLocator.searchResults.page"]+' <select id="pageNumber" onChange="navigation(\'center\')">';
				
				for(var index=0; index<pages; index++){
					paginationCode += '<option value="'+(index+1)+'">'+(index+1)+'</option>';
					//("The pagination code so far is: "+paginationCode);
				}
				paginationCode += '</select> '+dealerAssets["dealerLocator.searchResults.of"]+' '+pages+'</td><td style="width:10px;vertical-align:middle"><a href="javascript:navigation(\'right\')"><img src="/img/global/icon/right-arrow.gif" alt="next" class="paginationArrows" /></a></td></tr></table>';
				resultsDivEle.innerHTML = paginationCode;

			}else{
				//document.getElementById("searchResultsCount").innerHTML="";
			}
			
			
			// clear previous dealers from the array of dealers found
			dealersFound = new Array();
			// Rendering the dealer results

			renderDealersInfo(positionDealersArray, '1');
			stateMgr.changeState(stateMgr.states.SEARCHRESULTS);

			if(debugMode){
				alert("Results rendered. Before displaying map");
			}

			// The below call displays the map of the page
			//GetMap();
			/* If you do not set this value then if the give address is ambiguous, MSN will display a dislogue box with all possible
			 * addresses and promot the user to select one. Which is not part of requirement. This particular code by-pass that activity
			 * and MSN by default takes the closest addess that matches with the given information
			 */
			map.ShowDisambiguationDialog(0);



			if(debugMode){
					alert("Results rendered. Map displayed");
			}
		}else{
			
			if(eventGTR)
			{
					displayNoGTR();
					return;	
			}
			document.getElementById("searchResultsCount").innerHTML="";
			stateMgr.changeState(stateMgr.states.NORESULTS);
			// This loop is executed if there are not dealers found.
			document.getElementById('dwrErrorRegion').innerHTML = ""; // dealerAssets["dealerLocator.searchValidation.noResults"]; // 'No dealers returned for the given information. Please try again.';
			document.getElementById('dwrErrorRegion').innerHTML = '0 '+dealerAssets["dealerLocator.searchResults.results"]+' '+DWRUtil.getValue('searchText');
			document.getElementById('searchResults').innerHTML = "<div style='padding:10px;'>"+dealerAssets["dealerLocator.searchValidation.noResults"]+"</div>";
			document.getElementById('dealerInformation').innerHTML =  "";
			document.getElementById('inputBox').innerHTML =  "";
			/* hide the dealer information panel, since there are no accessible dealers */
			//************** Map also has to be refreshed to the default one ***************
		}
	
		
	
	} catch(err) {
		alert(GENERAL_ERROR);
	}

	if(debugMode){
			alert("Leaving function displayDealerSearchResults()");
	}

}

/*
	The following method renders the actual dealers on the page. The function basically loops through the "positionDealersArray" that was
	returned from the search and displays only 10 dealers at a time(max).
	The index from which it has to take the dealers in the array is decided based on the paramer "pageIndex"
	Ex: if "pageIndex" = 2, then the function displays the dealers in page 2. Which is nothing but dealer from 11 to 20(as per the requirement
	each page contains a maximu of "10" dealer and pagination is being used to traverse through the complete results
*/
function renderDealersInfo(positionDealersArray, pageIndex, direction){
	if(debugMode){
		alert("Entered function renderDealersInfo()");
		alert("Page index:"+pageIndex);
	}
	stateMgr.changeState(stateMgr.states.NEWPAGE);

	// Counter is being used to count the number of dealers displayed at any point of time
	var counter = 0;
	var languagevalue=document.dealerLocatorForm.hdnLocaleLanguage.value;
	var lang_difference='';
	if(languagevalue=='es')
	{
		lang_difference='/espanol';
	}
	// Division "searchResults" is the one that contains the dealer results(left hand side of the page)
	//document.getElementById('searchResults').innerHTML =  '';
	var strContent = "";
	
	//alert("checking GTR while rendering:"+eventGTR);
		// The following code loops through the "positionDealersArray" and displas them on the page
		// The dealer with which the loop starts depends on the "paeIndex" provided to the function
		// The loop breack either when the counter reaches 10 or in current index(i) is > the length
		// of "positionDealersArray"

		for(var i = (pageIndex-1)*10; i < positionDealersArray.length && counter < 10; i++) {
			counter++;
			var safeName = positionDealersArray[i]["name"].replace("'","\\'");
			var currentURI = window.location.href;
			var isStageEnv = (currentURI.search('www.stage') > -1) ? true : false;
			var isQAEnv = (currentURI.search('www.qa') > -1) ? true : false;
			var isIntegEnv = (currentURI.search('www.integ') > -1) ? true : false;
			
			var search_inventory_url ='/Locate.jsp?make=nissan&year=null&flow=browse&dealer='+positionDealersArray[i]["id"]+			    			  '&nextInInventory=dealer_inventory&rpl=false&x=&zip='+positionDealersArray[i]["postalCode"]+'&Site=&lang=en';
			
			if (isStageEnv || isQAEnv || isIntegEnv)
				search_inventory_url = 'http://www.config.stage.nissanusa.com'+search_inventory_url;
			else
			search_inventory_url = 'http://www.config.nissanusa.com'+search_inventory_url;
	
			var dealerURL ='<a href="javascript:viewDealerDetails(\''+i+'\')" name="dealer'+i+'" onClick="crmEvent3(\'Listing\');">'+positionDealersArray[i]["name"]+'</a>'; 
			//var dealerURL = '<a href="'+positionDealersArray[i]["url"]+'" name="dealer'+i+'" target="_blank" onClick="crmEvent2({\'STATE\':\''+positionDealersArray[i]["state"]+'\',\'DlrCode\':\''+positionDealersArray[i]["id"]+'\',\'Method\':\'Listing\',\'DlrName\':\''+safeName+'\'})">'+positionDealersArray[i]["name"]+'</a>';
			
			
			
			if (positionDealersArray[i]["url"] == ""){
				//var dealerURL = positionDealersArray[i]["name"];
			}

			//End of Changes

			//document.getElementById('searchResults').innerHTML = document.getElementById('searchResults').innerHTML
			strContent += '<div class="resBox" id="resBox'+i+'"><div class="resName"><img height="20" width="27" class="searchResultIcon" src="/img/dealer_locator/icons/searchresult'
				+(i+1)
				+'.png" title="'+(i+1)+'"/>'
				+((positionDealersArray[i]["awardSet"] || positionDealersArray[i]["excellencecode"]==1 || positionDealersArray[i]["gtr"]) ? '<img height="23" width="18" class="searchResultAwardIcon" src="/img/dealer_locator/icons/award_ribbon.png" />':'')
				+dealerURL
				+'</div><div class="resAdd"><p>'
				+positionDealersArray[i]["line1"]
				+'</p><p>'
				+positionDealersArray[i]["city"]
				+', '
				+positionDealersArray[i]["state"]
				+' '
				+positionDealersArray[i]["postalCode"]
				+' ('
				+(Math.round(positionDealersArray[i]["distance"]*10)/10)
				+' '+dealerAssets["dealerLocator.unit.miles"]+')</p></p>'+dealerAssets["dealerLocator.searchResults.telephone"]+' '
				+positionDealersArray[i]["defaultPhone"]
				+'</p></div>';

				if(positionDealersArray[i]["contactable"] == true){
					//window.console.log(positionDealersArray[i]["contactable"]);
					//document.getElementById('searchResults').innerHTML = document.getElementById('searchResults').innerHTML
					strContent += '<div class="resCont" style="display:block;float:left"><a href="javascript:contactDealer(\''
					+positionDealersArray[i]["id"]
					+'\', \'noActionState\',\''
					+formatStringForQuote(positionDealersArray[i]["name"])
					+'\',\''
					+positionDealersArray[i]["postalCode"]
					+'\',\''
					+formatStringForQuote(positionDealersArray[i]["city"])
					+'\',\''
					+positionDealersArray[i]["state"]
					+'\',\''
					+formatStringForQuote(positionDealersArray[i]["line1"])
					+'\',\''
					+positionDealersArray[i]["defaultPhone"]
					+'\',\''
					+positionDealersArray[i]["defaultEmail"]
					+'\',\''
					+positionDealersArray[i]["distance"]
					+'\',\''
					+formatStringForQuote(positionDealersArray[i]["url"])
					+'\',\'Locate.Contact_Dealer_Detail\');"  style="display:block" page="ContactDealer"><img class="CTAbutton" style="cursor:pointer" src="/img/dealer_locator/buttons'+lang_difference+'/contact_dealer_grey_off.png"/></a></div>';
				}

				//document.getElementById('searchResults').innerHTML = document.getElementById('searchResults').innerHTML
				
				
				//Changes made by CTS

				/*var search_inventory_url = '/Locate.jsp?make=nissan&flow=browse&dealer='+positionDealersArray[i]["id"]+'&nextInInventory=dealer_inventory&rpl=false&x=&zip='+positionDealersArray[i]["postalCode"]+'&Site=&lang=en';*/
				
			if(eventGTR){
				
				strContent += '<div class="resDet"><a href="http://www.GTRNISSAN.com?site=nissanusa.dealer_loc" target="_blank" onClick="crmEvent15(\'Listing\');"><img 			       						            src="/img/dealer_locator/buttons'+lang_difference+'/viewGTRSite_off.png" class="CTAbutton" style="padding-left:0px"/></a></div>'
						+'</div>';
			}
			else{
					
					strContent += '<div class="resDet"><a href="'+search_inventory_url+'&next=Locate.SearchInventory"><img 			       						            src="/img/dealer_locator/buttons'+lang_difference+'/search_inv_red_off.png" class="CTAbutton" style="padding-left:0px"/></a></div>'
						+'</div>';
			}
				
				
				/*strContent += '<div class="resDet"><a id='+positionDealersArray[i]["id"]+' href="javascript:viewDealerDetails(\''+i+'\')" onClick="crmEvent3(\'Listing\');"><img height="15" width="132" border="0" alt="" class="CTAbutton" src="/img/dealer_locator/buttons'+lang_difference+'/view_dealer_details_grey_off.png"></img></a></div>'
				+'</div>';*/
				
				//End of changes
			

			//document.getElementById('searchResults').innerHTML = strContent;
			// The "excellencecode" is "1" for dealers who are excellent in the business. The code displays an "image" when the dealer has such privilege
			if(positionDealersArray[i]["excellencecode"] == 1){
				//document.getElementById('searchResults').innerHTML  = document.getElementById('searchResults').innerHTML + '<div class="resExc"><img src="http://www.nissanusa.com/img/dealer_locator/nissan_certified.jpg"/></div>';
			}

		//document.getElementById('searchResults').innerHTML  =  document.getElementById('searchResults').innerHTML + '</div><div class="first"></div>';

			if (debugMode) alert("is it the addDealer?");
            // The following code adds the dealer to the MAP on the page
			addDealer(i+1,positionDealersArray[i]["name"],positionDealersArray[i]["line1"]+","+""+positionDealersArray[i]["city"]+","+positionDealersArray[i]["state"],positionDealersArray[i]["latitude"],positionDealersArray[i]["longitude"]);

		}
		//alert(strContent);
		document.getElementById('searchResults').innerHTML = strContent;
		if(map != null){
			map.Clear();
		}
		GetMap();
		// zoom out and add new set of dealers if necessary
		if ((positionDealersArray.length>10) && (direction!="back")) {

			addDealers();
		}

		if (debugMode) alert("or setting the innerHTML?");
		document.getElementById('searchResults').innerHTML  =  document.getElementById('searchResults').innerHTML + '</div>';
		jQuery(".searchResultIcon").ifixpng();
		jQuery(".searchResultAwardIcon").ifixpng();
		jQuery("#searchResults img.CTAbutton").ifixpng().hover(imgSwitch,imgSwitch);

		if(debugMode){
			alert("Leaving function renderDealersInfo()");
		}
		//document.getElementById('searchResults').innerHTML = strContent;
}


/*
	The following method is called when the pagination feature is used (Cases: click on left arrow, drop down change and click on right arrow)
	The parameter "side" tells from which place this finction is being called.
	If the function is called when the user clicks the "left arrow" then the value of "side" is "left"
	If the function is called when the user clicks the "right arrow" then the value of "side" is "right"
	If the function is called when the user changes the "pagination drop down" then the value of "side" is "center"
*/
function navigation(side){
	if(debugMode){
		alert("Entered function navigation()");
		alert("Navigation:"+side);
	}
	document.getElementById("searchResults").style.display="block";

	// get rid of the driving directions results div if it exists
	if ($("drivingDirectionsResults")){
	$("cdpageContent").removeChild(document.getElementById("drivingDirectionsResults"));
	}

	// document.getElementById('dwrErrorRegion').innerHTML = '';
	if(document.getElementById('pageNumber') != null){
		// The following variable contains the "drop down" value when the user clicks the pagination functionality
		var currentPage = parseInt(DWRUtil.getValue('pageNumber'));

		// The following variable contains the total number of pages to which the results spreads
		var noOfPages = Math.ceil((dealerResultsGlobal.length/10));

		// The following box refers the pagination drop down
		var selectBox = document.getElementById('pageNumber');

		if(debugMode){
			alert("Current page number:"+currentPage);
			alert("Current index in the pagination dropdown:"+selectBox.selectedIndex);
		}

		if(side == 'left'){
			if(debugMode){
				alert("Navigation: In left now");
			}

			// Not action will happen if the user is already in page 1 and clicks left arrow
			if(currentPage != '1'){
				// The following code changes the "selected" value in the drop down to the previous page
				selectBox.selectedIndex -= 1;
				// Call to function "rederDealersInfo" to render the new set of dealer on the page
				renderDealersInfo(dealerResultsGlobal, (currentPage-1), "back")
			}
		}else if(side == 'right'){
			if(debugMode){
				alert("Navigation: In right now");
			}

			// Not action will happen if the user is already in the last page and clicks right arrow
			if(currentPage != noOfPages){
				// The following code changes the "selected" value in the drop down to the next page
				selectBox.selectedIndex += 1;
				// Call to function "rederDealersInfo" to render the new set of dealer on the page
				renderDealersInfo(dealerResultsGlobal, (currentPage+1))
			}
		}else if(side == 'center'){
			if(debugMode){
				alert("Navigation: In center now");
			}

			if(!isNaN(DWRUtil.getValue('searchText'))){
				updateMeta('zipcode', DWRUtil.getValue('searchText'));
			}else{
				updateMeta('cityState', DWRUtil.getValue('searchText'));
			}

			renderDealersInfo(dealerResultsGlobal, currentPage)

		}
	}else{
		/* This loop is being executed if there are less than 10 dealers returned in the search and the user clicks the
		 * "back to search results" button in the driving directions page.
		 */
		 if(!isNaN(DWRUtil.getValue('searchText'))){
			updateMeta('zipcode', DWRUtil.getValue('searchText'));
		 }else{
			updateMeta('cityState', DWRUtil.getValue('searchText'));
		 }
		 renderDealersInfo(dealerResultsGlobal, '1')
	}

	if(debugMode){
		alert("Final index in the pagination dropdown:"+selectBox.selectedIndex);
		alert("Leaving function navigation()");
	}

}

function showAllPointsOnMap(layer){
    map.SetMapView(getLatLongPointsFromLayer(layer))
}

//gets an array of VELatLong from points in a layer
function getLatLongPointsFromLayer(layer){
    var points = new Array();
    //loop points in layer
    for(i=0;i<layer.GetShapeCount();i++){
        //add to array
        points[i] = layer.GetShapeByIndex(i).GetPoints()[0];
    }
    return points;
}

function showAll(){
	showAllPointsOnMap(map.GetShapeLayerByIndex(0));
}



function selectGTR(){
	
	
	searchingStatus();
	clearDivs();
	eventGTR=true;
	
	if(document.getElementById("gtrCheckBox").checked==true)
	{
		
		searchDealers(searchTextGlobal,radiusGlobal,true);
		document.getElementById("dwrErrorRegion").style.display="block";
		
	}
	else
	{
		
		/*if($("dealer_countDiv"))
		{
			document.getElementById("dealer_countDiv").style.display="none";
			document.getElementById("noGtrMsgDiv_1").style.display="none";
			document.getElementById("noGtrMsgDiv_2").style.display="none";
			document.getElementById("GTRCertDealersDiv").style.display="none";
		}*/
		eventGTR=false;
		searchDealers(searchTextGlobal,radiusGlobal,false);
		document.getElementById("dwrErrorRegion").style.display="block";
		
	}
	crmEvent9();

}

/**
This function is called when we select or deselect the check box.
This function makes a call to searchDealers with GT-R filter var
If we have GT-R dealers we dipaly then or else
this function will display information saying No GT-R dalers found.

**/

function displayNoGTR(){

	//alert("In Display No GTR");
	eventGTR=false;
	clearDivs();
	if($("searchProgressDiv"))
	{
		document.getElementById("searchProgressDiv").style.display="none";
	}		
	
	createNoGTRMessage();
}


function clearDivs(){

	document.getElementById("searchResults").innerHTML="";
	document.getElementById("searchResults").style.display="none";
	document.getElementById("dwrErrorRegion").innerHTML="";
	document.getElementById("dwrErrorRegion").style.display="none";
	if ($("resultsDiv")){
		
		document.getElementById("resultsDiv").innerHTML="";
		document.getElementById("resultsDiv").style.visibility="hidden";
	}
}


function searchingStatus(){

	if(!$("searchProgressDiv"))
	{
		var searchProgressDiv=document.createElement("div");
		searchProgressDiv.id="searchProgressDiv";
		var searchImgDiv=document.createElement("div");
		searchImgDiv.id="searchImgDiv";
		searchImgDiv.innerHTML="Searching...";
		searchProgressDiv.appendChild(searchImgDiv);
		document.getElementById("cdpageContent").appendChild(searchProgressDiv);
		jQuery(searchProgressDiv).css("height","353px");
		jQuery(searchImgDiv).css("position","absolute");
		jQuery(searchImgDiv).css("top","178px");
		jQuery(searchImgDiv).css("padding-left","30px");
		jQuery(searchImgDiv).css("font-weight","bold");
		jQuery(searchImgDiv).css("font-size","12pt");

	}
	else
	{
		document.getElementById("searchProgressDiv").style.display="block";
	}
}

function createNoGTRMessage(){

	//alert("In createnoGTR");
	if (!$("noGtrFoundDiv"))
	{
		
		var dealerL=document.getElementById("dealerL");
		var dealer_countDiv=document.createElement("div");
		dealer_countDiv.id="dealer_countDiv";
		dealerL.appendChild(dealer_countDiv);
		document.getElementById("dealer_countDiv").innerHTML="Use the fields to the right to find dealers";
			
		var cdPageContent=document.getElementById("cdpageContent");
				
		var noGtrFoundDiv=document.createElement("div");
		noGtrFoundDiv.id="noGtrFoundDiv";
		var noGtrMsgDiv_1=document.createElement("div");
		noGtrMsgDiv_1.id="noGtrMsgDiv_1";
		noGtrFoundDiv.appendChild(noGtrMsgDiv_1);		
		cdPageContent.appendChild(noGtrFoundDiv);

		document.getElementById("noGtrMsgDiv_1").innerHTML=dealerAssets["dealerLocator.searchValidation.GTR.noResults"];
				
	/*	var noGtrMsgDiv_2=document.createElement("div");
		noGtrMsgDiv_2.id="noGtrMsgDiv_2";
				
		cdPageContent.appendChild(noGtrMsgDiv_2);

		//document.getElementById("noGtrMsgDiv_2").innerHTML=dealerAssets["dealerLocator.searchValidation.GTR.noResultsMessage2"];;
				
				
				
		var GTRCertDealersDiv = document.createElement("div");
		GTRCertDealersDiv.id="GTRCertDealersDiv";
		GTRCertDealersDiv.style.padding="25px";
		var GTRCertDealersButton = document.createElement("input");
		GTRCertDealersButton.type="button";
		GTRCertDealersDiv.style.textAlign="left";
		GTRCertDealersButton.value="FIND GTR CERTIFIED DEALERS";
		GTRCertDealersButton.name="FIND GTR CERTIFIED DEALERS";
		//GTRCertDealersDiv.appendChild(GTRCertDealersButton);
		cdPageContent.appendChild(GTRCertDealersDiv); */
				
	}
	
	else
	{
		
		document.getElementById("noGtrFoundDiv").style.display="block";
	//	document.getElementById("noGtrMsgDiv_2").style.display="block";
	//	document.getElementById("GTRCertDealersDiv").style.display="block";
		document.getElementById("dealer_countDiv").style.display="block";
	}
}

