/*
 * The following method displays a division on the dealerSearch.jsp page where the user can enter the "Start Address" to fetch the
 * driving directions.
 */
function displayDrivingDirections(el,index){

	// Delete contents of any existing Driving Directions forms to eliminate overlap
	$("inputBox").innerHTML = "";
	$("inputBox").style.display = "none";
	if ($("infoInputBox")) {
		$("infoInputBox").innerHTML = "";
		$("infoInputBox").style.display = "none";
	}

	positionedDealer = dealerResultsGlobal[index];
	if (typeof(el) == 'undefined') el = 'inputBox';
	if(debugMode){
		alert("Entered function displayDrivingDirections()");
	}

	updateMeta('drivingDirections', '');

	var inputBox = document.getElementById(el);
	inputBox.className="inputBox";
	inputBox.innerHTML = "";
	inputBox.style.display="block";
//	inputBox.style.width="300px";
//	inputBox.style.width="400px";

	var inputWidth1 = 0, inputWidth2 = 0, inputWidth3 = 0;
	var buttonMarginT = 0, buttonMarginB = 0;
	switch (el) {
		case "inputBox":
			var heading = document.createElement("h2");
			heading.innerHTML = dealerAssets["dealerLocator.drivingDirectionsInput.heading"]+' <a href="javascript:void(null)" onclick="closePopUp(\''+('inputBox')+'\'); return false;"><img src="/img/dealer_locator/close.jpg" width="12" height="12" id="close_image" /></a>';
			inputBox.appendChild(heading);
			inputWidth1 = 153;
			inputWidth2 = 315;
			inputWidth3 = 133;
			buttonMarginT = 18;
			break;
		case "infoInputBox":
			var heading = document.createElement("h2");
			heading.innerHTML = dealerAssets["dealerLocator.drivingDirectionsInput.heading"];
			inputBox.appendChild(heading);
			inputWidth1 = 84;
			inputWidth2 = 157;
			inputWidth3 = 66;
			buttonMarginT = 8;
			buttonMarginB = 8;
			jQuery(".customInfoBox-noBeak, .customInfoBox-with-rightBeak, .customInfoBox-with-leftBeak").each(function () {
				if (jQuery(this).offset().top > 344) { this.style.top="344px";}
			});
			break;
	}

	var inputBoxInner = document.createElement("div");
	inputBox.appendChild(inputBoxInner);

	var errMsg = document.createElement("div");
	errMsg.innerHTML = dealerAssets["dealerLocator.drivingDirectionsInput.instructions"];
	
	//SR 17501
	errMsg.id = "dwrErrorRegion";
	//errMsg.height = "10px";
	//jQuery(errMsg).css({"color": "#d00000"});
	inputBoxInner.appendChild(errMsg);

	var address = document.createElement("div");
	address.innerHTML = dealerAssets["dealerLocator.drivingDirectionsInput.streetAddress"]+'<br/>';
	var addressInput = document.createElement("input");
	addressInput.type="text";
	addressInput.id="dstreetaddress";
	addressInput.name="dstreetaddress";
	addressInput.value= stateMgr.formfieldvalues["dstreetaddress"]?stateMgr.formfieldvalues["dstreetaddress"]:"";
	addressInput.style.width=inputWidth2 + "px";
	address.appendChild(addressInput);
	inputBoxInner.appendChild(address);
	addressInput.focus();

	var city = document.createElement("div");
	city.innerHTML = dealerAssets["dealerLocator.city"]+"<br/>";
	var cityInput = document.createElement("input");
	cityInput.type="text";
	cityInput.id="dcity";
	cityInput.name="dcity";
	cityInput.value=stateMgr.formfieldvalues["dcity"]?stateMgr.formfieldvalues["dcity"]:"";
	cityInput.style.width=inputWidth1+"px";
	cityInput.style.marginRight="3px";
	city.appendChild(cityInput);
	jQuery(city).css("float","left");
	inputBoxInner.appendChild(city);

	var state = document.createElement("div");
	state.innerHTML = dealerAssets["dealerLocator.state"] + "<br/>";
	var stateSelect = document.createElement("select");
	stateSelect.id="dstate";
	stateSelect.name="dstate";
	stateSelect.style.width=inputWidth3+"px";
	if(navigator.appName=="Microsoft Internet Explorer"){
		state.style.marginRight="10px";
		stateSelect.style.height="17px";
	}
	else{
		state.style.marginRight="16px";
	}
	state.appendChild(stateSelect);
	jQuery(state).css({"float": "right"});
	inputBoxInner.appendChild(state);

	var zip = document.createElement("div");
	zip.innerHTML = dealerAssets["dealerLocator.zipCode"] + "<br/>";
	var zipInput = document.createElement("input");
	zipInput.type="text";
	zipInput.id="dzipcode";
	zipInput.name="dzipcode";
	zipInput.value=stateMgr.formfieldvalues["dzipcode"]?stateMgr.formfieldvalues["dzipcode"]:"";
	zipInput.style.width=inputWidth1+"px";
//	zipInput.style.marginRight="27px";
	zipInput.style.marginLeft="0px";
	zip.appendChild(zipInput);
	jQuery(zip).css({"float": "left"});
	inputBoxInner.appendChild(zip);

	var button = document.createElement("div");
	var buttonInput = document.createElement("input");
	buttonInput.type="image";
	buttonInput.name="drivingdirections";
	buttonInput.value="Get Directions";
	buttonInput.onclick=validateDrivingDirections;
	buttonInput.src="/img/dealer_locator/buttons/get_directions_off.png";
	var languagevalue=document.dealerLocatorForm.hdnLocaleLanguage.value;
	if(languagevalue=='es')
	{
		buttonInput.src="/img/dealer_locator/buttons/espanol/get_directions_off.png";
	}
	button.appendChild(buttonInput);
	jQuery(buttonInput).ifixpng().css({"border": "0px", "height": "23px", "width": "113px"}).hover(imgSwitch,imgSwitch);

/*	Enhancements made for driving directions window to work in Mozilla.
	Following lines have been commented.  */

//	jQuery(button).css({"float": "right", marginTop: buttonMarginT+"px", marginBottom: buttonMarginB+"px" });
//	jQuery(button).css({ marginTop: buttonMarginT+"px", marginBottom: buttonMarginB+"px" });
//	jQuery(button).css({"float": "left"});

	if(el=="inputBox"){
		jQuery(button).css({"float": "right"});
	}

	if(navigator.appName=="Microsoft Internet Explorer"){
		buttonInput.style.marginRight="18px";
	}
	else{
		buttonInput.style.marginRight="14px";
	}
	/*Commented this to Fix SR 17336*/
	//buttonInput.style.marginTop="9px";
	inputBoxInner.appendChild(button);

	addStateOption('dstate',stateMgr.formfieldvalues["dstate"]?stateMgr.formfieldvalues["dstate"]:"");
	if(debugMode){
		alert("Leaving function displayDrivingDirections()");
	}

	jQuery("#"+el+" input,#"+el+" select").change(function () {
		stateMgr.formfieldvalues[this.name]=jQuery(this).val();
	});
}
function closePopUp(id){
	//alert("id: "+id);
	$(id).style.display = 'none';
	jQuery("#inputBox").css({"height":"169px","top": "225px"});
	jQuery("#save_dealer_err_msg").css({"display":"none"}).html("");
}

/*
 * The following method validates the information provided to get the driving directions
 */
function validateDrivingDirections(){

	//CRM Event Call - are we validating from the inputBox or the infoInputBox?
	if (document.getElementById("inputBox").style.display == "block") {
		crmEvent12({'Method':'Detail'});
	} else {
		crmEvent12({'Method':'Popup'});
	}

	debugMode = false;
	if(debugMode){
		alert("Entered function validateDrivingDirections()");
	}

    // SR 17501
    
	document.getElementById('dwrErrorRegion').innerHTML = '';
	jQuery("#infoInputBox #dwrErrorRegion").css("color","#d00000");
	jQuery("#inputBox #dwrErrorRegion").css("text-decoration","underline");
	var errorFlag=false;
	var zipErrorFlag=false;

    // SR 17501
   
	// Validation for zipcode or city, state
	if(document.getElementById("dzipcode").value != null && document.getElementById("dzipcode").value != '')
	{
      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(document.getElementById("dzipcode").value)  || document.getElementById("dzipcode").value=='00000') {
			errorFlag = true;
			zipErrorFlag = true;
		} 
	}

	// change done for SR 15507

	else
	{
	  errorFlag = true;      
         zipErrorFlag = true; 
	}


  	
	 if((document.getElementById("dcity").value == null || document.getElementById("dcity").value == '') || (document.getElementById("dstate").value == null || document.getElementById("dstate").value == '') || 
		(document.getElementById("dstreetaddress").value == null || document.getElementById("dstreetaddress").value == ''))	
		{           
 		   errorFlag = true;
		}
	
     var specialChars="[\\s\\(\\)<>@,;:/|'`!#%^\{\}\+\*\?\$\\\\\\\"\\.\\[\\]]";
     var rex =  new RegExp(specialChars);

    if(!document.getElementById("dstreetaddress").value.match(rex)  && (document.getElementById("dstreetaddress").value.match(rex)!=null))
 	  errorFlag = true;

     var specialCharsForCity="[\\s\\(\\)<>@,;:/|'`!#%^\{\}\+\*\?\$\\\\\\\"\\.\\[\\]\\d]";
     var rexCity =  new RegExp(specialCharsForCity);

	if((!document.getElementById("dcity").value.match(rexCity)) && document.getElementById("dcity").value.match(rexCity )!=null)  
	  errorFlag = true;

	// state , city , streeet error = errorFlag 
	// zipcode error = ziperrorflag 



	if(errorFlag){
		if(zipErrorFlag){
			document.getElementById('dwrErrorRegion').innerHTML = dealerAssets["dealerLocator.validation.incorrectZip"];
					if (dealerAssets["dealerLocator.validation.incorrectZip"].length > 0) {
						jQuery("#inputBox").css({"height":"199px","top": "195px"});
						jQuery("#save_dealer_err_msg").css({"display":"block","height":"25px","margin-top":"8px"}).html(dealerAssets["dealerLocator.validation.incorrectZip"]);
					} else {
						jQuery("#inputBox").css({"height":"169px","top": "225px"});
						jQuery("#save_dealer_err_msg").css({"display":"none"}).html("");
					}
		}else{
			document.getElementById('dwrErrorRegion').innerHTML = dealerAssets["dealerLocator.validation.incorrectAddress"];
					if (dealerAssets["dealerLocator.validation.incorrectZip"].length > 0) {
						jQuery("#inputBox").css({"height":"199px","top": "195px"});
						jQuery("#save_dealer_err_msg").css({"display":"block","height":"25px","margin-top":"8px"}).html(dealerAssets["dealerLocator.validation.incorrectZip"]);
					} else {
						jQuery("#inputBox").css({"height":"169px","top": "225px"});
						jQuery("#save_dealer_err_msg").css({"display":"none"}).html("");
					}
		}
		return false;
	}else{
		var address='street$'+document.getElementById("dstreetaddress").value+'city$'+document.getElementById("dcity").value+'state$'+document.getElementById("dstate").value+'zipcode$'+document.getElementById("dzipcode").value;
		// The following line has been commented as loading message is not required
		// DWRUtil.useLoadingMessage(LOADING_MESSAGE);

		// This method call is executed if all entred information provided by client is validated and there are no errors.
		// If the front end validation is completed, that doesn't mean that the address is correct. It only means that the user entered al required fields
		// The following call is an "AJAX/DWR" call, which validates the actual adress infromation exists or not.
		// If the address entered is valid then an "address" object is created out of it and call back method "setStartAddress" is being called.
		// else it will return an error message, which will be rendered in the same "setStartAddress" method call
		DealerLocatorFacade.validateAddress(address, 'false', setStartAddress);
	}

	if(debugMode){
		alert("Leaving function validateDrivingDirections()");
	}
}

/*
 * The following method fetched the directions from the given start adress to the selected dealer. The information is directly fetched from
 * MSN Virtual earth. It will not make any DWR/AJAX calls to the server
 */
function getdirections(){
		//debugMode = true;
		if(debugMode){
			alert("Entered function getdirections()");
		}

		var dstreetaddress;
		var dcity;
		var dstate;
		var dzipcode;

		// Call t update title of the page and meta info
		updateMeta('drivingDirectionResults', '');

		// The "If" loop is executed when first time the user trying to fetch the driving directions. From the second time onwards
		// "else" loop will be called
		if(document.dealerLocatorForm.hdnNewDrivingDirections.value != 'true'){
			if(debugMode)
				alert("In the loop -> Find driving directions: "+document.dealerLocatorForm.hdnNewDrivingDirections.value);
            // The following code fetched the start address from the driving direction input boxes
			dstreetaddress = DWRUtil.getValue('dstreetaddress');
			dcity = DWRUtil.getValue('dcity');
			dstate =DWRUtil.getValue('dstate');
			dzipcode =DWRUtil.getValue('dzipcode');

			// The following code set the extracted informatio in the previous step to some hidden fields
			document.dealerLocatorForm.hdnAddressLine.value = dstreetaddress;
			document.dealerLocatorForm.hdnCity.value = dcity;
			document.dealerLocatorForm.hdnState.value = dstate;
			document.dealerLocatorForm.hdnZipcode.value = dzipcode;
			hidePanel();
		}else{
			if(debugMode)
				alert("In the loop -> Find new driving directions: "+document.dealerLocatorForm.hdnNewDrivingDirections.value);
            // Fetching the start address from the hidden fields
			dstreetaddress = document.dealerLocatorForm.hdnAddressLine.value;
			dcity = document.dealerLocatorForm.hdnCity.value;
			dstate = document.dealerLocatorForm.hdnState.value;
			dzipcode = document.dealerLocatorForm.hdnZipcode.value;
		}

		//alert('dstreetaddress'+dstreetaddress+'dcity'+dcity+'dstate'+dstate+'dzipcode'+dzipcode);

		var startaddress='';

		if(dstreetaddress!= null && dstreetaddress != ''){
			startaddress += dstreetaddress+', ';
		}
		if(dcity!= null && dcity != ''){
			startaddress += dcity+', ';
		}
		if(dstate!= null && dstate != ''){
			startaddress += dstate+', ';
		}
		if(dzipcode!= null && dzipcode != ''){
			startaddress += dzipcode+', ';
		}
		startaddress += 'US';
        // Start addreess created as a single string
		//alert(startaddress);

		// The following code fetches the end address, which is nothing but the selected dealer address.
		var dealerstreet = positionedDealer["street"];
		var dealerCity = positionedDealer["city"];
		var dealerState = positionedDealer["state"];
		var dealerPostalCode = positionedDealer["postalCode"];
		var dealerCountry = positionedDealer["country"];
		var dealerAddress = dealerstreet+','+dealerCity+','+dealerState+','+dealerPostalCode+','+dealerCountry;
		//alert(dealerAddress);

		// The follwing method draws a route on the map from the starting address and returns details about the route in a VERoute Class object.
		// 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 (document.getElementById("pageNumber")) { jQuery("#pageNumber").css("visibility","hidden"); }

		// The method call fetches the driving directions and pass them to call back function "onGotRoute"
		stateMgr.changeState(stateMgr.states.DRIVINGDIRECTIONS);
		orthoView();
		map.GetRoute(startaddress,dealerAddress,VEDistanceUnit.Miles,VERouteType.Quickest,onGotRoute);
		document.dealerLocatorForm.hdnNewDrivingDirections.value = false;


		if(debugMode){
			alert("Leaving function getdirections()");
		}
}

/*
 * The following method renders the driving directios on the map. The direction are being provided by the earlier method call "getdirections"
 */
 var startAddress = '',len,printRouteContainer,total_estimate_time_div, total_distance_div;
 function onGotRoute(route)
 {
    if(debugMode){
		alert("Entered function onGotRoute()");
	}


	// The "if" loop is executed if the addres is entered through the text area inthe driving directions page
	// Otherwise the "else" loop is executed where it fetched the start address from the four hidden fields in the JSP page
	if(document.getElementById('startAddress') != null){
		//alert("Old text area:"+document.getElementById('startAddress').value);
		startAddress = document.getElementById('startAddress').value;
	}else{
		startAddress = "";
		var dstreetaddress = document.dealerLocatorForm.hdnAddressLine.value;
		var dcity = document.dealerLocatorForm.hdnCity.value;
		var dstate = document.dealerLocatorForm.hdnState.value;
		var dzipcode = document.dealerLocatorForm.hdnZipcode.value;

		var previousFlag = false;
		if(dstreetaddress!= null && dstreetaddress != ''){
			startAddress += dstreetaddress;
			previousFlag = true;
		}
		if(dcity!= null && dcity != ''){
			if(previousFlag){
				startAddress += ', ';
			}else{
				previousFlag = true;
			}
			startAddress += dcity;
		}
		if(dstate!= null && dstate != ''){
			if(previousFlag){
				startAddress += ', ';
			}else{
				previousFlag = true;
			}
			startAddress += dstate;
		}
		if(dzipcode!= null && dzipcode != ''){
			if(previousFlag){
				startAddress += ' ';
			}
			startAddress += dzipcode;
		}
	}

	// remove the driving directions div if present so we don't double up
	if ($("drivingDirectionsResults")){
	$("cdpageContent").removeChild(document.getElementById("drivingDirectionsResults"));
	}

	var dd = document.createElement("div");
	dd.id="drivingDirectionsResults";

	var sr = document.getElementById("searchResults");
	sr.style.display="none";
	stateMgr.visibles.push("searchResults");
	document.getElementById('dealerInformation').style.display="none";

	var back_print_container_div = document.createElement("div");
	back_print_container_div.id = "back_print_container_div";

	var back_results_div = document.createElement("div");
	var buttonInput = document.createElement("input");
	buttonInput.type="image";
	buttonInput.name="back_to_results";
	buttonInput.value="BACK TO RESULTS";

	var onbackClick='deleteMapRoute();backToSearchResults();';
	buttonInput.onclick=new Function(onbackClick);

	buttonInput.src="/img/dealer_locator/buttons"+langFolder+"/back_to_results_off.png";
	back_results_div.appendChild(buttonInput);
	jQuery(buttonInput).ifixpng().css({border: "0px",height: "15px"});//.hover('/img/dealer_locator/buttons/back_to_results_off.png','/img/dealer_locator/buttons/back_to_results_on.png');

	try {
		if(document.dealerLocatorForm.hdnDrivingDirectionsDeepLink.value == 'true'){
			jQuery(back_results_div).css("display","none");
			document.dealerLocatorForm.hdnDrivingDirectionsDeepLink.value = 'false';
		}else{
			jQuery(back_results_div).css({"float": "left", "padding-top": "14px", "padding-left": "20px"});
		}
	} catch (e) {
		jQuery(back_results_div).css({"float":"left","padding-top":"14px","padding-left":"20px"});
	}

	back_print_container_div.appendChild(back_results_div);

	var print_results_div = document.createElement("div");
	var printInput = document.createElement("input");
	printInput.type="image";
	printInput.name="print_results";
	printInput.value="PRINT";
	jQuery(printInput).mouseover(function() {
		previewPopup(this,"/img/dealer_locator/print_preview.jpg");
	}).mouseout(function(){jQuery("#previewPop").remove();});

	var onPrintClick='printDrivingDirectionsInfo()';
	printInput.onclick=new Function(onPrintClick);

	printInput.src="/img/dealer_locator/buttons"+langFolder+"/print_off.png";
	print_results_div.appendChild(printInput);
	jQuery(printInput).ifixpng().css({border: "0px",height: "23px"});//.hover(imgSwitch,imgSwitch);
	jQuery(print_results_div).css({"padding-top": "10px" , "padding-left": "170px" });
	back_print_container_div.appendChild(print_results_div);

	jQuery(back_print_container_div).css({"position": "relative", "background-color": "#ffffff","width": "278px","height":"40px","overflow":"hidden"});
	dd.appendChild(back_print_container_div);

	var address_div = document.createElement("div");
	address_div.id="address_div";
	address_div.style.paddingLeft="4px";

	start_add = document.createElement("h2");
	start_add.innerHTML = '<br />STARTING ADDRESS';
	address_div.appendChild(start_add);

	//put the textarea
	//var text_area_div = document.createElement("div");
	var text_area_input = document.createElement("textarea");
	text_area_input.id = "startAddress";
	text_area_input.name = "startAddress";
	text_area_input.setAttribute('cols','35');
	text_area_input.setAttribute('rows','5');
	text_area_input.style.width="250px";

	//text_area_input.keydown = textCounter('startAddress', 100);
	//text_area_input.keyup = textCounter('startAddress', 100);
	text_area_input.innerHTML = startAddress;
	address_div.appendChild(text_area_input);



	end_add = document.createElement("h2");
	end_add.innerHTML = '<br />ENDING ADDRESS';
	address_div.appendChild(end_add);


	var street_address = document.createElement("div");
	street_address.innerHTML = positionedDealer["street"]+' '+positionedDealer["city"]+' '+positionedDealer["state"]+' '+positionedDealer["postalCode"];
	address_div.appendChild(street_address);

	var get_button = document.createElement("div");
	var get_buttonInput = document.createElement("input");
	get_buttonInput.type="image";
	get_buttonInput.name="drivingdirections";
	get_buttonInput.value="Get Directions";
	get_buttonInput.onclick=getNewDirections;
	get_buttonInput.src="/img/dealer_locator/buttons/get_directions_off.png"
	// uncomment after fixing css bug
	get_button.appendChild(get_buttonInput);

	jQuery(get_buttonInput).ifixpng().css({border: "0px", height: "23px", width: "113px","position":"static"}).hover(imgSwitch,imgSwitch);
	jQuery(get_button).css({"margin-top": "15px", "margin-left": "120px"});
	address_div.appendChild(get_button);

	var distance_details_div = document.createElement("div");
	distance_details_div.id = "distance_details_div";

	var hr_div = document.createElement("div");
	jQuery(hr_div).css({"padding-top": "0px","border-bottom":"solid 1px #999999","width":"253px","line-height":"0px"});
	distance_details_div.appendChild(hr_div);

	var distance_details = document.createElement("h1");
	distance_details.innerHTML = '<br />Driving Directions';
	distance_details_div.appendChild(distance_details);
	jQuery(distance_details_div).css({"margin-top":"5px","padding-left":"6px"})

	var total_distance = document.createElement("div");
	total_distance.innerHTML = dealerAssets["dealerLocator.drivingDirectionsResults.totalDistance"]+': '+route.Itinerary.Distance+' '+dealerAssets["dealerLocator.unit.miles"];
	distance_details_div.appendChild(total_distance);

	var est_time = document.createElement("div");
	est_time.innerHTML = dealerAssets["dealerLocator.drivingDirectionsResults.estimatedTime"]+': '+route.Itinerary.Time;
	distance_details_div.appendChild(est_time);

	/*for printing */
	var total_estimate_time_div_container = document.createElement("div");
	total_estimate_time_div = document.createElement("div");
	total_estimate_time_div.id ="total_estimate_time_div";
	var tetd_innerH_div = document.createElement("div");
	tetd_innerH_div.innerHTML =  dealerAssets["dealerLocator.drivingDirectionsResults.totalDistance"];

	var tetd_inner_div = document.createElement("div");
	tetd_inner_div.innerHTML =  route.Itinerary.Distance+' '+dealerAssets["dealerLocator.unit.miles"];

	jQuery(tetd_innerH_div).css({"font-weight":"bold", "width":"140px"});
	jQuery(tetd_innerH_div).css({"width":"140px"});

	total_estimate_time_div.appendChild(tetd_innerH_div);
	total_estimate_time_div.appendChild(tetd_inner_div);
	total_estimate_time_div_container.appendChild(total_estimate_time_div);
	jQuery(total_estimate_time_div_container).css({"display": "none"});
	$("pageBg").appendChild(total_estimate_time_div_container);


	var total_distance_div_container = document.createElement("div");
	total_distance_div = document.createElement("div");
	total_distance_div.id = "total_distance_div";
	var tdd_innerH_div = document.createElement("div");
	tdd_innerH_div.innerHTML = dealerAssets["dealerLocator.drivingDirectionsResults.estimatedTime"];

	var tdd_inner_div = document.createElement("div");
	tdd_inner_div.innerHTML = route.Itinerary.Time;

	jQuery(tdd_innerH_div).css({"font-weight":"bold", "width":"140px"});
	jQuery(tdd_inner_div).css({"width":"140px"});

	total_distance_div.appendChild(tdd_innerH_div);
	total_distance_div.appendChild(tdd_inner_div);
	total_distance_div_container.appendChild(total_distance_div);
	jQuery(total_distance_div_container).css({"display": "none"});
	$("pageBg").appendChild(total_distance_div_container);


	/* ends here */


	// The variable "route" contains the detail directions. So we loop though all the directions and display them on the page
	// The route.Itineray.Segments[] represents the directions. each element in this array represents on significant place in the overall route

	var len = route.Itinerary.Segments.length;
	var route_div;

	if(len >0){
		route_div = document.createElement("div");
		jQuery(route_div).css("padding-top","10px");
		route_div.innerHTML = '<h4 style="padding-left: 6px; padding-bottom: 6px">'+route.Itinerary.Segments[0].Instruction+'</h4>';
		printRouteContainer = document.createElement("div");
		var printRouteContainerContainer = document.createElement("div");
		printRouteContainer.id = "printRouteContainer";
		jQuery(printRouteContainerContainer).css({"display": "none"});
		$("pageBg").appendChild(printRouteContainerContainer);
		printRouteContainerContainer.appendChild(printRouteContainer);
		var print_route_div = route_div.cloneNode(true);
		printRouteContainer.appendChild(print_route_div);
	}

	for(var i = 1; i < len ;i++)
	{
		var item = "item_" + i;
		item = document.createElement("div");
		item.id = "item_" + i;
		jQuery(item).css({"clear":"left","background-color": i%2==0?"#dddddd":"#ffffff","padding-left":"10px"});
		var directionStep = document.createElement("img");

		if((i!=1) && (i!=len-1)){
			directionStep.src="/img/dealer_locator/icons/DR_index_"+(i-1)+".gif"
		}else if(i==1){
			directionStep.src="/img/dealer_locator/icons/mapicon_start.gif"
		}else{
			directionStep.src="/img/dealer_locator/icons/mapicon_end.gif"
		}

		jQuery(directionStep).css({"float": "left","border": "0px","padding-right": "5px","padding-top": "3px"});
		item.appendChild(directionStep);

		data = document.createElement("div");
		data.innerHTML = '  '+route.Itinerary.Segments[i].Instruction +' ('+route.Itinerary.Segments[i].Distance+' '+dealerAssets["dealerLocator.unit.miles"]+')';

		br_div = document.createElement("br");
		data.appendChild(br_div);

		br_div1 = document.createElement("br");
		data.appendChild(br_div1);

		jQuery(data).css({"padding-top":"2px","padding-left":"25px"});

		item.appendChild(data);

		route_div.appendChild(item);

		var cloneItem = item.cloneNode(true);
		printRouteContainer.appendChild(cloneItem);
	}

	var address_container_div = document.createElement("div");
	address_container_div.id = "address_container_div";
	jQuery(address_container_div).css({"border-top":"solid 1px #999","overflow": "auto", "width": "278px", "height": "354px"});
	dd.appendChild(address_container_div);

	// jQuery(address_div).css({});
	address_container_div.appendChild(address_div);
	address_container_div.appendChild(distance_details_div);
	address_container_div.appendChild(route_div);

	sr.parentNode.appendChild(dd);
	jQuery(dd).css({"overflow": "hidden"});
	jQuery("#drivingDirectionsResults input").ifixpng().hover(imgSwitch,imgSwitch);

	if(debugMode){
		alert("Leaving function onGotRoute()");
	}
}

function validateSaveDealerInfo1(){
	alert("in validateSaveDealerInfo1");
}

/*
 * This method is called when user trying to fetch driving directions for a new start address
 */
function getNewDirections(){
	debugMode = false;
	if(debugMode){
		alert("Entered function getNewDirections()");
	}

	document.getElementById('dwrErrorRegion').innerHTML = '';
	var address = document.getElementById('startAddress').value;

	if(address == null || address == ''){
		document.getElementById('dwrErrorRegion').innerHTML = 'Please enter a valid address to get the driving directions.';

	}else{
		// If we pass any "text" to MSN virtual earth it will try to make some address out of it.
		// But it can recognise only some formats like 1. street, city, state, zipcode 2. Street, city, State 3. Street, zipcode 4. Zipcode 5. City, State
		// By observing the option you can find that it is expecting "street" in the given text. If that is not provided some time it will not recognize the
		// address properly. Hence for all cases we are adding a text "street" before the give address by the user. This additional "street" will not
		// show any side effects, but helps MSN in parsing the address in a better way.
		// **** DON'T REMOVE THE 'street' TEXT ADDED BELOW. IT IS VERY IMPORTANT ****
		address ='street,'+ address;
		// AJAX/DWR call to validate the user given address in the text area. After parsing the address will be passed to call back method "setStartAddress"
		DealerLocatorFacade.validateAddress(address, 'true', setStartAddress);
	}

	if(debugMode){
		alert("Leaving function getNewDirections()");
	}
}

/*
 * The function is used to set the start address provided by the user to some hidden fields
 * The object that is being passed to this function will have a maximum length of 2
 * If the length is "1" the it contains only the "address" object which represents the start adress
 * If the length is "2" then the first object at index "0" is the address object and at index "1"
 * an error message key will be stored.
 */
function setStartAddress(addressObj){
	if(debugMode){
		alert("Entered function setStartAddress()");
	}
	//alert("Length of array:"+addressObj.length)

	// If length is 2, that means that the address provided is not proper
	if(addressObj.length == 2){
		document.getElementById('dwrErrorRegion').innerHTML = dealerAssets[addressObj[1]];
	}else{
		// The following code clears the previous start address
		document.dealerLocatorForm.hdnAddressLine.value = '';
		document.dealerLocatorForm.hdnCity.value = '';
		document.dealerLocatorForm.hdnState.value = '';
		document.dealerLocatorForm.hdnZipcode.value = '';

		// For each address provided by user we are adding text "street" which will enable the
		// MSN virtual earth to decode the corresct city, state and zipcode information from the given text
		// So, if the returned address contains "stree" as actual "street" field value the we need to make it to blank as
		// it is the one we added intentionally. But if the user also provides the steet information then we no need to do that.
		if(addressObj[0]["address"] == 'street' || addressObj[0]["address"]  == null || addressObj[0]["address"] == ''){
			document.dealerLocatorForm.hdnAddressLine.value = '';
		}else{
			document.dealerLocatorForm.hdnAddressLine.value = addressObj[0]["address"];
		}

		if(addressObj[0]["city"] != null && addressObj[0]["city"] != ''){
			document.dealerLocatorForm.hdnCity.value = addressObj[0]["city"];
		}
		if(addressObj[0]["state"] != null && addressObj[0]["state"] != ''){
			document.dealerLocatorForm.hdnState.value = addressObj[0]["state"];
		}
		if(addressObj[0]["zipCode"] != null && addressObj[0]["zipCode"] != ''){
			document.dealerLocatorForm.hdnZipcode.value = addressObj[0]["zipCode"];
		}
		// The following flag is used to identify whether the user getting driving directions for the first time or not.
		document.dealerLocatorForm.hdnNewDrivingDirections.value = true;

		// Call to getch the directions. The below method will get the start address from the hidden fields which were set before this line
		getdirections();
	}
	if(debugMode){
		alert("Leaving function setStartAddress()");
	}
}

function backToSearchResults() {
	stateMgr.restoreState();
	document.getElementById("drivingDirectionsResults").style.display="none";
	return false;
}

function deleteMapRoute(){
if (document.getElementById("pageNumber")) { jQuery("#pageNumber").css("visibility","visible"); }
map.DeleteRoute();
showAll();
}

/*
MAP FUNCTIONALITY FOR DRIVING DIRECTIONS
*/

function printDrivingDirectionsFrame(addEls) {

	this.addHead = function(str,overwrite) {
		if (overwrite) window.frames['printframe_ifr'].document.getElementsByTagName("head")[0].innerHTML="";
		if (typeof(str) == 'string') {
			window.frames['printframe_ifr'].document.getElementsByTagName("head")[0].innerHTML+=str;
		} else {
			window.frames['printframe_ifr'].document.getElementsByTagName("head")[0].appendChild(str);
		}
	}
	this.addBody = function(str,overwrite) {
		if (overwrite) window.frames['printframe_ifr'].document.body.innerHTML="";
		if (typeof(str) == 'string') {
			window.frames['printframe_ifr'].document.body.innerHTML+=str;
		} else {
			if (typeof(str.outerHTML) == 'string') {
				window.frames['printframe_ifr'].document.body.innerHTML+=str.outerHTML;

				//Code for changing the title
				window.frames['printframe_ifr'].document.title = "Dealer Driving Directions";

				$("printRouteContainer").style.display="block";
				$("total_estimate_time_div").style.display="block";
				$("total_distance_div").style.display="block";

			} else {
				window.frames['printframe_ifr'].document.body.appendChild(str);
				window.frames['printframe_ifr'].document.title = "Dealer Driving Directions";

				$("printRouteContainer").style.display="block";
				$("total_estimate_time_div").style.display="block";
				$("total_distance_div").style.display="block";
			}
		}
	}
	this.removeBody = function(elid) {
		with (window.frames['printframe_ifr'].document) {
			body.removeChild(getElementById(elid));
		}
	}
	this.showBody = function(elid) {
		with (window.frames['printframe_ifr'].document) {
			getElementById(elid).style.display="block";
		}
	}
	this.addBody("",true);
	for (var i = 0, ae = addEls.length; i < ae; i++) {
		this.addBody(addEls[i]);
	}
	setTimeout("printDrivingDirectionsFrameCallback()",500);
	return true;
}

function printDrivingDirectionsFrameCallback() {
	//alert('printing');


		window.frames['printframe_ifr'].focus();
		window.frames['printframe_ifr'].print();
		window.focus();


}

function printDrivingDirectionsInfoCallback(dealermap) {
	dealermap["dealerMapUrl"]=dealermap["dealerMapUrl"].replace("https://","http://");
	dealermap["routeMapUrl"]=dealermap["routeMapUrl"].replace("https://","http://");
	var positionedDealerObj = positionedDealer;
	var total_Drivng_Direction_div = document.createElement("div");

	var dph = document.createElement("h1");
	jQuery(dph).css({"height": "30px", "padding-top": "20px", "margin-left":"20px"});
	dph.innerHTML = "<img src=\"/img/global/header_nissan_logo.gif\" alt=\"NISSAN\" style=\"float: left; margin-right: 30px; margin-top: -15px;\" />" + dealerAssets["dealerLocator.mainHeading"];

	total_Drivng_Direction_div.appendChild(dph);

	//First Div
	var dealer_div = document.createElement("div");

	ddContent1 = document.createElement("div");
	ddContent1.setAttribute("class","ddContent");
	var innerHTML="";
	innerHTML += '<div><b>'+positionedDealerObj["name"]+'</b></div>';
	innerHTML += '<div style="width:200px">'+positionedDealerObj["line1"];
	innerHTML += positionedDealerObj["city"] + ", " + positionedDealerObj["state"] + " " + positionedDealerObj["postalCode"]+"</div>";
	innerHTML += '<div><div class="dealerHeadingFormat">'+dealerAssets["dealerLocator.viewDealer.mainLine"]+'</div>';
	innerHTML += '<div class="dealerDataFormat">'+positionedDealerObj["defaultPhone"]+'</div></div><br/>';
	innerHTML += '<div><div class="dealerHeadingFormat">'+dealerAssets["dealerLocator.viewDealer.internetSales"]+'</div>';
	innerHTML += '<div class="dealerDataFormat">'+positionedDealerObj["internetSalesPhone"]+'</div></div><br/>';
	innerHTML += '<div><div class="dealerHeadingFormat">'+dealerAssets["dealerLocator.viewDealer.serviceDepartment"]+'</div>';
	innerHTML += '<div class="dealerDataFormat">'+positionedDealerObj["servicePhone"]+'</div></div><br/>';
	ddContent1.innerHTML = innerHTML;

	dealer_div.appendChild(ddContent1);

	var salesHr_div = document.createElement("div");
	salesHr_div.id = "salesHR_div";
	var innerHTML1 = '<div><b>'+dealerAssets["dealerLocator.viewDealer.salesHours"]+'</b></div>';
	for(var i = 0; i < positionedDealerObj["completeSalesHours"].length; i++)
	{
		innerHTML1 += '<div><div class="dealerHeadingFormat" style="font-weight:normal">'+positionedDealerObj["completeSalesHours"][i]+'</div><div class="dealerDataFormat" style="width:125px;left:95px">'+positionedDealerObj["completeSalesHours"][++i]+'</div></div><br/>';
	}
	salesHr_div.innerHTML = innerHTML1;

	jQuery(salesHr_div).css({"position": "absolute", "left": "265px", "top": "58px"});
	dealer_div.appendChild(salesHr_div);


	var service_div = document.createElement("div");
	service_div.id = "service_div";
	var innerHTML2 = '<div><b>'+dealerAssets["dealerLocator.viewDealer.serviceHours"]+'</b></div>';
	for(var i = 0; i < positionedDealerObj["completeSalesHours"].length; i++)
	{
		innerHTML2 += '<div><div class="dealerHeadingFormat" style="font-weight:normal">'+positionedDealerObj["completeServiceHours"][i]+'</div><div class="dealerDataFormat" style="width:125px; left:95px">'+positionedDealerObj["completeServiceHours"][++i]+'</div></div><br/>';
	}
	service_div.innerHTML = innerHTML2;

	jQuery(service_div).css({"position": "absolute", "left": "500px", "top": "58px"});
	dealer_div.appendChild(service_div);

	var language_div = document.createElement("div");
	var innerHTML3 = '<div><b>'+dealerAssets["dealerLocator.viewDealer.languagesSpoken"]+'</b></div>';
	innerHTML3 += '<div class="dealerDataFormat" style="left:0px; width:145px">'+positionedDealerObj["languagesCode"]+'</div>';
	language_div.innerHTML = innerHTML3;

	jQuery(language_div).css({"position": "absolute", "left": "740px", "top": "58px"});
	dealer_div.appendChild(language_div);


	total_Drivng_Direction_div.appendChild(dealer_div);
	// END OF First Div

	//SECOND DIV

	var address_route_estTime_totalDistance_div = document.createElement("div");
	address_route_estTime_totalDistance_div.id = "address_route_estTime_totalDistance_div";
	var startAddress_div = document.createElement("div");
	start_add_heading = document.createElement("h2");
	start_add_heading.innerHTML = 'STARTING ADDRESS';
	startAddress_div.appendChild(start_add_heading);
	jQuery(start_add_heading).css({"width":"145px"});

	var start_add = document.createElement("div");
	start_add.innerHTML = startAddress;
	startAddress_div.appendChild(start_add);
	jQuery(startAddress_div).css({"width":"145px"});

	jQuery(startAddress_div).css({"position": "absolute", "left": "0px", "top": "10px"});
	address_route_estTime_totalDistance_div.appendChild(startAddress_div);


	var endingAddress_div = document.createElement("div");
	end_add_heading = document.createElement("h2");
	end_add_heading.innerHTML = 'ENDING ADDRESS';
	endingAddress_div.appendChild(end_add_heading);
	jQuery(end_add_heading).css({"width":"145px"});

	var street_address = document.createElement("div");
	street_address.innerHTML = positionedDealer["street"]+' '+positionedDealer["city"]+' '+positionedDealer["state"]+' '+positionedDealer["postalCode"];
	endingAddress_div.appendChild(street_address);
	jQuery(endingAddress_div).css({"width":"145px"});

	jQuery(endingAddress_div).css({"position": "absolute", "left": "245px", "top": "10px"});
	address_route_estTime_totalDistance_div.appendChild(endingAddress_div);

	var prc = $("printRouteContainer");
	//prc.style.height
	var cloneprc = prc.cloneNode(true);
	jQuery(cloneprc).css({"position": "relative", "top": "0px","padding-top":"50px"});
	cloneprc.getElementsByTagName("h4")[0].style.paddingLeft="0px";

	address_route_estTime_totalDistance_div.appendChild(cloneprc);



	//----------------
	var tet_div = $("total_estimate_time_div");
	var clone_tet_div = tet_div.cloneNode(true);
	jQuery(clone_tet_div).css({"clear":"left","float":"left","margin-top":"6px"});
	address_route_estTime_totalDistance_div.appendChild(clone_tet_div);

	var td_div = $("total_distance_div");
	var clone_td_div = td_div.cloneNode(true);
	jQuery(clone_td_div).css({"float":"left","margin-top":"6px"});
	address_route_estTime_totalDistance_div.appendChild(clone_td_div);
	//----------------

	jQuery(address_route_estTime_totalDistance_div).css({"position": "relative", "left": "18px", "top": "0px","height":"auto"});

	var maps_div = document.createElement("div");
	maps_div.id = "maps_div";
	jQuery(maps_div).css({"clear":"left","margin-top":"10px","page-break-before":"always"});

	var img1_div = document.createElement("div");
	img1_div.id = "img1_div";

	var mg1 = document.createElement("img");
	mg1.alt="dealer map";
	mg1.src=dealermap['routeMapUrl'];
	mg1.style.width="532px";
	mg1.style.height="352px";
	img1_div.appendChild(mg1);

	var img2_div = document.createElement("div");
	img2_div.id = "img2_div";
	var mg2 = document.createElement("img");
	mg2.alt="dealer map";
	mg2.src=dealermap['dealerMapUrl'];
	mg2.style.width="532px";
	mg2.style.height="352px";
	jQuery(img2_div).css({"margin-top": "20px"});
	img2_div.appendChild(mg2);
	maps_div.appendChild(img1_div);
	maps_div.appendChild(img2_div);

	address_route_estTime_totalDistance_div.appendChild(maps_div);

	total_Drivng_Direction_div.appendChild(address_route_estTime_totalDistance_div);

	printDrivingDirectionsFrame([total_Drivng_Direction_div]);
	return true;
}

function printDrivingDirectionsInfo(){
	crmEvent14();
	if(debugMode){
			alert("Entered function printDealerInfo()");
	}
	var ifr;
	if (document.getElementById("printframe_ifr")) {
		ifr = document.getElementById("printframe_ifr");
		ifr.src="/js/dealer_locator/printframe.html";
	} else {
		ifr = document.createElement("iframe");
		ifr.style.position="absolute";
		ifr.style.width="900px";
		ifr.style.height="3000px";

		ifr.style.top="-3000px";
		ifr.style.left="0px";

		ifr.id="printframe_ifr";
		ifr.name="printframe_ifr";
		ifr.src="/js/dealer_locator/printframe.html";
		document.body.appendChild(ifr)
	}

	// Get all the hidden variables from the form to get the driving directions Map;
	var localeLanguage = document.dealerLocatorForm.hdnLocaleLanguage.value;
	var localeCountry = document.dealerLocatorForm.hdnLocaleCountry.value;
	var drivingDirFld = document.dealerLocatorForm.hdnNewDrivingDirections.value;
	var addressLine = document.dealerLocatorForm.hdnAddressLine.value;
	var city = document.dealerLocatorForm.hdnCity.value;
	var state = document.dealerLocatorForm.hdnState.value;
	var zipCode = document.dealerLocatorForm.hdnZipcode.value;
	//var positionedDealerObj = dealerResultsGlobal[dealerIndex];
	var positionedDealerObj = positionedDealer;
	var country ='US';
	var mapflag = true;
	positionedDealerPrint = { id:positionedDealerObj["id"], line1:positionedDealerObj["line1"],city:positionedDealerObj["city"],state:positionedDealerObj["state"],postalCode:positionedDealerObj["postalCode"]};

	DealerLocatorFacade.getMapDirectionsCustomized(addressLine,city,state,zipCode,country,positionedDealerPrint,localeLanguage,localeCountry,mapflag,printDrivingDirectionsInfoCallback);

	if(debugMode){
			alert("Leaving function printDealerInfo()");
	}
}

function drivingDirectionsDeepLink(dealer){
	positionedDealer =dealer;
	document.dealerLocatorForm.hdnNewDrivingDirections.value = 'true';
	// Call to getch the directions. The below method will get the start address from the hidden fields which were set before this line
	getInitialMap();
	getdirections();
   	document.dealerLocatorForm.hdnDrivingDirectionsDeepLink.value='true';
}