var map = null;
var geocoder = null;
var brand	= "BFGoodrich";
var country	= "United States";
var language	= "";
var latitude;
var longitude;
var zip;
var showSearchOrResult;
var searchedAddress = '';	
var current_sort_order = '';			// Default sort order
var dealerTopvolume = '';					// 
var markerArr = [];	
var points = [];							// Markers that will be added to the Marker Manager all at once
var directions = null;							// Directions To Store
var user_address = '';
var default_lat;
var default_lng;
var current_view = 'dealer_list';
var infowindow = null;
var directionsDisplay;
var directionsService;
var startLocation = null;
var endLocation = null;
var gmarkers = [];
var selected_dealer = '';
var dealersJSON;
var marker = null;
var dealerships;
var dealership;
var locmarkers = [];
var startMarker;
var endMarker;
var polyline;
var resContentMessage;
var totalDistanceText;
var directionsFromText;
var directionsToText;
var moreDealerDetailsText;
var hourText;
var topVolumeText;
var startingLocation;
var backToSearchText;
var backToDealerLocationResultsText;
var infoForDealerText;
var googleMapsKey;
var selRange;
var nationalAccountPromoMessage;
var dealerPromoMessage;
var dealerPromoMessageImageUrl;
var dealerPromoMessagePage;
var dealerWebsiteLink;
var validationSearchAddressMessage;
var info_content;
var mapLatlng = null;
var current_bounds = null;
var replaceText = null;
var timeVar;
function disableFormSubmit(event){
	$("#search_address_error_message").hide();
	if ( event.keyCode == 13 ){	
		getLatLaong('search_address', null, 'latitude', 'longitude', 'searchForm', 'dealer locator');
		event.returnValue=false; 
		return false;
	}
}


function setSelectedRange(locale){
	searchedAddress = document.getElementById("search_address").value;
	selRange = document.getElementById("selectedValue").value;
	var rangeOptions = document.getElementById("range");
	var optLen = rangeOptions.length;
	if(locale=='en_CA' || locale=='fr_CA')
	{
		var option=document.createElement("option");
		option.text='100';
		option.value='100';
		if(selRange==100){
		option.selected=true;
		}
		rangeOptions.options.add(option);
	}
	for( i = 0; i < optLen; i++ ){ 
		if(rangeOptions[i].text == selRange){
		rangeOptions[i].selected=true;
	}
   } 
}

/*
*	sort_dealerships
*
*	Sorts dealerships.
*	
*/
function sort_dealerships(order){
	if(order == current_sort_order) return 0;
	if(order == 'distance') {
		dealerships.sort(function(a, b) {
			return (a.distance - b.distance);
		});
		current_sort_order = 'distance';
		return 1;
	}
	else if(order == 'volume') {
		dealerships.sort(function(a, b) {
			var distDiff = b.distance - a.distance;
			if(distDiff > 0){
				return -1;
			}else if(distDiff < 0){
				return 1;
			}else{
				return 0;
			}			
		});
		dealerships.sort(function(a, b) {
			if(b.tier==null)
			{
				b.tier=2;
			}
			if(a.tier==null)
			{
				a.tier=2;
			}
			var tierDiff = b.newTier - a.newTier;
			if(tierDiff > 0){
				return 1;
			}else if(tierDiff < 0){
				return -1;
			}else{
				return 0;
			}		    
		});
		current_sort_order = 'volume';
		return 1;

	}
	else if(order == 'name')
	{	
		dealerships.sort(function(a, b) {
			var aa = a.name.toLowerCase();
			var bb = b.name.toLowerCase();
			if(aa > bb) return 1;
			if(aa < bb) return -1;
			return 0;
		});
		current_sort_order = 'name';
		return 1;
	}
	return -1;
}


function createFilterArr(){
	var filterArr = new Array();
	if( null != document.getElementById('weekends')){
		if( document.getElementById('weekends').checked == true ){
			filterArr[0] = 1;
		}else{
			filterArr[0] = 0;
		}
	}
	
	if( null != document.getElementById('pax')){
		if( document.getElementById('pax').checked == true ){
			filterArr[1] = 1;
		}else{
			filterArr[1] = 0;
		}
	}
	if( null != document.getElementById('national')){
		if( document.getElementById('national').checked == true ){
			filterArr[2] = 1;
		}else{
			filterArr[2] = 0;
		}
	}
	
	filter_results(false, true, filterArr);
	
	$("#total_dealer_results ul.result_content > li:odd").addClass("odd_row");
	$("#total_dealer_results ul.result_content > li:even").addClass("even_row");
}

function setJSONData(){
	$.getJSON('/iwov-resources/jsp/dealerlocatorJSON.jsp', function(dealershipsJSON){
		dealerships = dealershipsJSON;
		sort_dealerships('volume');
		filter_results(false, true, false);
	});
}

function fatchServicesData(dealID){
	var CompleteUrl = uri_service+"?dealerShipto="+dealership.shipTo+"&Action_Value=true&isAjax=false";
	$.ajax({
			type: "GET",
				async: false,
				cache: false,
				timeout: 30000,
				url: CompleteUrl ,
			dataType: "xml",
			success: function(xml)
			{ 	
				$.ajax({
					async: false,
					url: "/iwov-resources/jsp/dealerlocatorJSON.jsp",
					dataType: "json",
					success:  function(dealershipsJSON) {
						dealerships = dealershipsJSON;						
						var oldorder = current_sort_order;
						current_sort_order = "";
						sort_dealerships(oldorder);
						filter_results(false, true, false);
						dealership = getSelectedDealerShip(dealID);
					}
				});
			} 			
		});
}

function initialize() {
	$.ajaxSetup({ cache: false });  
	mapLatlng = new google.maps.LatLng(default_lat,default_lng);
    var myOptions = {
      zoom: 11,
      center: mapLatlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
	map = new google.maps.Map(document.getElementById("google_map_wrapper"), myOptions);
	map.setCenter(mapLatlng);
	var marker = new google.maps.Marker({
        position: mapLatlng, 
        map: map      
    });	
	setJSONData();
	
	$("#total_dealer_results ul.result_content > li:odd").addClass("odd_row");
	$("#total_dealer_results ul.result_content > li:even").addClass("even_row");
}

function filter_results(show_dealer_id, build_side_item, filterArr){
	var show_dealership = false;					
	var open_marker = false;						
	var show_counter = 1;						
	var filterpassed = false;
	var show_alert_message = false;
	var i = 0;
	clean_map();
	if(directionsDisplay!=null){
		directionsDisplay.setMap(null);
    } 	
	if(polyline!=null){
		polyline.setMap(null);
    } 
	clean_map_markers(startMarker);
	clean_map_markers(endMarker);
	if (infowindow) infowindow.close();
	for(var x = 0 ; x < dealerships.length ; x ++){	
		
		dealership = dealerships[x];
		show_dealership = true;
		$.each( filterArr, function(f_index,val){ if ( val == 1 && (dealership.filters[f_index] != 1 || dealership.filters[f_index] != true)) show_dealership = false; });
					
		if ( show_dealership ){		
			var side_bar_item,opts,point,icon_label,myLatLng = null;
			icon_label = show_counter++;
			info_content = null;
			info_content = build_info_window(dealership,icon_label);
			myLatLng = new google.maps.LatLng(parseFloat(dealership.coor[0]), parseFloat(dealership.coor[1]));
			marker = createMark(myLatLng, icon_label, info_content, map, dealership);
			if(build_side_item){
				// Create the Item that will appear in the side bar and append it 
				var show_alert_message = document.getElementById('isYMMOSearch').value;
				if(show_alert_message == "false"){
					$('.results_block').css('height', '500px');
				} 
				if( i == 0 ){
					$("#selected_dealer_details").hide();
					$('#total_dealer_results').show();
					$('.result_content').empty();
					i = 1;
				}
				side_bar_item = build_side_bar_item(dealership,icon_label);
				$('.result_content').append(side_bar_item);
			}			
		if ( show_dealer_id !== false && dealership.id == show_dealer_id ){open_marker = marker;}
		points.push(myLatLng);
		}
	}
	$("#results_count").empty();
	$("#results_count").append(show_counter - 1 + " " + resContentMessage);
	if ( (show_counter - 1) == 0 ) {
		show_no_results_message();
	}
	points.push( mapLatlng );
	center_map_on_points();
	toolTipMichelin(jQuery);
}

/*
*	center_map_on_points
*
*	Find the zoom level and bounding box to include all points on the map and center map on that box
*	
*/
function center_map_on_points(){
	var bounds = new google.maps.LatLngBounds ();
	for (var i = 0, LtLgLen = points.length; i < LtLgLen; i++) {
	  bounds.extend (points[i]);
	}
	map.fitBounds (bounds);
	
}

function display_dealer_info(dealID,marker,history, remMarkers, dealershipPosition){
		$('#map_directions').hide();
		$(".dealer_conviniences").show();
		$(".dealer_conviniences").empty();
		
		if(dealerDetailsSrcID != "" && dealerDetailsTypeID != "" && dealerDetailsCatID !=""){
			var printaxel = Math.random() + "";
			var printa = printaxel * 10000000000000;
			$(".dealer_conviniences").append('<iframe src="http://fls.doubleclick.net/activityi;src='+dealerDetailsSrcID+';type='+dealerDetailsTypeID+';cat='+dealerDetailsCatID+';ord=' + printa + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>'); 	
		}

		if(dealershipPosition=="")
		{
			dealershipPosition = getDealerNumber(dealID);
		}
		
		marker = markerArr[dealershipPosition-1 ];
		dealership = getSelectedDealerShip(dealID);
	
		if(dealership['info']=="")
		{
			fatchServicesData(dealID);
		}	

		current_view = 'dealer_details';
		selected_dealer = build_location_selected(dealership,false, true);
		$('#total_dealer_results').hide();
		$("#selected_dealer_details").show();
		$("#dealer_info").empty();
		$("#dealer_info").append(selected_dealer);
		$('#filters').hide();
		$('#directionsMessage').show();
		$('#directionsMessage').empty();
		if(infoForDealerText.indexOf("$dealerName") != -1){
			replaceText = "$dealerName";
		}	
		infoForDealerText = infoForDealerText.replace(replaceText, dealership.name);
		replaceText = dealership.name;
		$('#directionsMessage').append('<p><b>'+infoForDealerText+'</b><br /><a href="Javascript:void(0);" id="back_to_search" >'+ backToDealerLocationResultsText +'</a></p>');
		$('#back_to_search').click(function(){			
			removeInfoWrapper();
			createFilterArr();
			$('#directionsMessage').hide();
			$('#filters').show();
			toolTipMichelin(jQuery);
			scrollPosition(dealershipPosition);
		});
		if(remMarkers){
			clean_map_markers(startMarker);
			clean_map_markers(endMarker);
		}
	
		var infoService = createInfoServices(dealership);
		$(".dealer_conviniences").append(infoService);	
		$("#back_to_results_link").click(function(){ 
			removeInfoWrapper();
			createFilterArr();
			$('#directionsMessage').hide();$('#filters').show();
			toolTipMichelin(jQuery);
			scrollPosition(dealershipPosition)
		});
		google.maps.event.trigger(marker, "click"); 		
		timeVar =setTimeout("hideMoreDetailLink(" + dealership.id + ")",200);

}


function getSelectedDealerShip(dealID){
	for(var d = 0 ; d < dealerships.length ; d ++){
		if(dealerships[d].id == dealID){
			dealership = dealerships[d];
			return dealership;
		}
	}
}

function getDealerNumber(dealID){
	for(var d = 0 ; d < dealerships.length ; d ++){
		if(dealerships[d].id == dealID){
			return (d+1);
		}
	}
}

function triggerEvent(dealID, marker, map_label){
	marker = markerArr[map_label-1];		
	google.maps.event.trigger(marker, "click"); 	
}

function display_directions(map,dealID,address, dealershipPosition){

	$(".dealer_conviniences").hide();
	dealership = getSelectedDealerShip(dealID);
    $('#get_directions').unbind('click');
	
	var from;
	if(dealershipPosition > 0)
	{
		from = $('#info_wrapper #info_directions .txtbox').val();		
		from = ( address == false ) ? from : address;
	}else{
		from = $('.directions_input #directions_address').val();
		from = ( address == false ) ? from : address;
	}
	
	user_address = from;
	var to = '';
	var html_directions = '';
	var selected_dealer = '';
	clean_map();	
	$('#total_dealer_results').hide();
	selected_dealer = build_location_selected(dealership,true, false);
	$("#selected_dealer_details").show();
	$("#dealer_info").empty();
	$("#dealer_info").append(selected_dealer);
	$('#more_dealer_details_' + dealership.id).click(function(){ 
		if(polyline!=null){
			polyline.setMap(null);
		} 
		clean_map_markers(startMarker);
		clean_map_markers(endMarker);
		removeInfoWrapper();
		filter_results(false, true, false);
		dealership = getSelectedDealerShip(dealID);
		display_dealer_info(dealership.id,false,false,false,""); 
	});
	$('#filters').hide();
	$('#directionsMessage').show();
	$('#directionsMessage').empty();
	if(infoForDealerText.indexOf("$dealerName") != -1){
		replaceText = "$dealerName";
	}
	infoForDealerText = infoForDealerText.replace(replaceText, dealership.name);
	replaceText = dealership.name;
	$('#directionsMessage').append('<p><b>'+infoForDealerText+'</b><br /><a href="Javascript:void(0);" id="back_to_search" >'+ backToDealerLocationResultsText +'</a></p>');
	$('#back_to_search').click(function(){	
		removeInfoWrapper();
		createFilterArr();
		$('#filters').show();
		$('#directionsMessage').hide();
		toolTipMichelin(jQuery);
	});
	
	to = dealership.address + ' ' + dealership.city  + ', ' + dealership.state  + ' ' + dealership.zip;
	if (infowindow) infowindow.close();
	directionsDisplay = new google.maps.DirectionsRenderer();
	
	directionsDisplay.setMap(null);
	if(polyline!=null){
		polyline.setMap(null);
    } 
	clean_map_markers(startMarker);
	
	directionsDisplay.setPanel(document.getElementById("google_map_wrapper"));
	directionsService = new google.maps.DirectionsService(); 
	
	var request = { 
		origin: from, 
		destination: to, 
		provideRouteAlternatives:true,
		travelMode: google.maps.DirectionsTravelMode.DRIVING 
	}; 
      polyline = new google.maps.Polyline({
		path: [],
		strokeColor: '#FF0000',
		strokeWeight: 3
	});
	 
	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			directionsDisplay.setDirections(response);
			var bounds = new google.maps.LatLngBounds();
			var route = response.routes[0];
			$('#map_directions').html(build_directions(route,dealership,from,polyline,bounds));
			$('#map_directions').show();
			$('#get_directions').click(function(){
				clean_map_markers(endMarker);
				display_directions(map, dealership.id,false);
			});		
			$('.print_direction_button').click(function(){
				var print_url = new String();
					print_url+= "http://maps.google.com/maps?hl=fr";	
					print_url+= "&q=" + from + "+to+" + to;
					print_url+= "&ie=UTF8";
					print_url+= "&z=12";
					print_url+= "&saddr="+from;
					print_url+= "&daddr="+dealership.address+"+"+dealership.city+",+"+dealership.state+"+"+dealership.zip+"+("+dealership.name+")";
					print_url+= "&layer=c";
					print_url+= "&pw=2";	
					print_url = print_url.replace(/\s/g, "+");					
					window.open(print_url,'mywin','left=20,top=20,width=800,height=500,toolbar=1,menubar=1,resizable=1,scrollbars=1');			
				});
			current_view = 'dealer_directions';
		}else if(status == google.maps.DirectionsStatus.ZERO_RESULTS){
			$("#map_directions").empty();
			$('#map_directions').show();
			var zeroResults = 	'<div class="directions">';
			zeroResults+= build_dir_header(dealership, from);			
			zeroResults+= '<p class="did_you_mean"> <b>The address you provided did not return any results.</b></p>';
			zeroResults+= '	<ol id="direction_options">';	
			zeroResults+= '	</ol>';
			zeroResults+= '	</div>';
			$("#map_directions").append(zeroResults);
			$('#get_directions').click(function(){
				clean_map_markers(endMarker);				
				display_directions(map, dealership.id,false);
			});
		}else{
			$("#map_directions").empty();
			$('#map_directions').show();
			var no_directions = 	'<div class="directions">';
			no_directions+= build_dir_header(dealership, from);
			no_directions+= 'The address you provided did not return any results.';
			no_directions+= '	</div>';

			$("#map_directions").append(no_directions);
			$('#get_directions').click(function(){ 
				clean_map_markers(endMarker);
				display_directions(map, dealership.id,false); 				
			});		
		}	
	});
	
}


function createMarker(latlng, icon_label) {
	var image = "/assets/bfg/system/images/icont_store_locator_pointer.gif";
	var marker_number = new google.maps.Point(3, 30)
	var marker = new MarkerWithLabel({
	    position: latlng,
	    map: map,
	    icon:image,
	    draggable: false,
	    raiseOnDrag: true,
	    labelContent: icon_label,
	    labelAnchor: marker_number,
	    labelClass: "markerDirections", // the CSS class for the label
	    labelInBackground: false
	});	
	return marker;
}

function clean_map(){
	for(var i = 0 ; i < markerArr.length ; i ++){
		markerArr[i].setMap(null);
	}
	markerArr = new Array();
	
}

function clean_map_markers(markerName){
	if(markerName != null){
		markerName.setMap(null);
	}
}


function clean_side_bar(){
	$('.results_block').empty();
	$('.sort_results_criteria').remove();
	$('.results_count').empty();
	
}

function createMark(latlng, icon_label, info_content, map, dealership) {
	var image = "/assets/bfg/system/images/icont_store_locator_pointer.gi";
	var marker_number;
	if(icon_label <= 9) {
		marker_number = new google.maps.Point(3, 32)
	} else if(icon_label > 9) {
		marker_number = new google.maps.Point(6, 32)
	} else{
	//	marker_number = new google.maps.Point(3, 35)
	}
	var marker = new MarkerWithLabel({
	    position: latlng,
	    map: map,
	    icon:image,
	    draggable: false,
	    raiseOnDrag: true,
	    labelContent: icon_label,
	    labelAnchor: marker_number,
	    labelClass: "marker", // the CSS class for the label
	    labelInBackground: false
	});
	markerArr[icon_label-1] = marker;	
	google.maps.event.addListener(marker, 'click', function() {
		if (infowindow) infowindow.close();
		infowindow = new InfoBubble({
			map: map,
			content: info_content,
			shadowStyle: 0,
			padding: 0,
			backgroundColor: 'rgb(255,255,255)',
			borderRadius: 0,
			arrowSize: 15,
			borderWidth: 0,
			borderColor: 'rgb(255,255,255)',
			disableAutoPan: false,
			hideCloseButton: true,
			arrowPosition: 50,
			arrowStyle: 0
		});	
		infowindow.open(map, marker);	  
		scrollPosition(marker.labelContent)
	});
	return marker;
}

function show_no_results_message(){
	$('.result_content').empty();		
	$('.result_content').append($.validator.messages.noResultOnDealerLocator);	
}

function build_info_window(dealership,map_label){
	
	var hours = '';
	$.each(dealership.hours, function(label,value){	
		if ( hours != '' ) 
			hours += '';
		hours += '<br>' + label + ' ' + value;
	});
	
	var iw ='<div id="info_wrapper">';
	iw+= '	<div id="dealer_locator_right" class="content_panel">';
	iw+= '		<a href="#" class="close-popup" title="close" onclick="infowindow.close()">close</a>';
	iw+= '		<h3>' + dealership.name + '</h3>';
	iw+= '		<div class="hours">';
	iw+= '			<p><strong>'+ hourText +'</strong>' + hours + '</p>';
	iw+= '		</div>';
	iw+= '		<p>' + dealership.address + '<br />' + dealership.city + ', ' + dealership.state + ' ' + dealership.zip + '<br />' + dealership.phone + '<br /><span class="distance">Distance: ' + dealership.formatDistance + ' </span></p>';
	iw+= '		<p class="dealer_details" id="more_dealer_details_info_window' + dealership.id + '" onclick="display_dealer_info(' + dealership.id + ', marker,false, true,'+map_label+');"><a href="Javascript:void(0);"><strong>'+ moreDealerDetailsText +'</strong></a></p>';
	iw+= '	</div>';
	iw+= '<div id="info_directions" class="content_panel">';
	iw+= '	<p>'+ startingLocation +':</p>';
	iw+= '	<input type="text" onkeypress="return display_directions_on_enter(event , '+ dealership.id + ' , '+ map_label +');" id="directions_address" class="txtbox" value="'+user_address+'">';
	iw+= '	<img id="get_directions" src="/assets/bfg/system/images/button_go.png" onclick="display_directions(map,'+ dealership.id + ' ,false, '+ map_label +' );';
	iw+= '_tag.dcsMultiTrack('+"'WT.z_getdir'"+','+"'1'"+');'
	iw+= '"/> </div>';
	iw+= '</div>';
		
	return iw ;	
}

function build_side_bar_item(dealership,map_label){
	var hours = '';
	$.each(dealership.hours, function(label,value){	
		if ( hours != '' ) 
			hours += '';
		hours += '<li>' + label + ' ' + value + '</li>';
	});
	
	var sbi= '';
	
	/*if((map_label%2)== 0){
		sbi+= '<li id ="listing_"'+map_label+'>';
	}
	else{*/
		
		sbi+= '<li id ="listing_'+map_label+'">';
	//}
	
	sbi+= '<div class="marker_offer_panel no_print" onclick="triggerEvent(' + dealership.id + ', marker, ' + map_label + ');">';
	sbi+= '<a href="#" title="" class="marker">' + map_label + '</a>';
	if ( dealership.newTier == 1){
        sbi+= '<a href="javascript:void(0);" title="'+topVolumeText+'" class="discount"><img src="/assets/bfg/system/images/icon_best_chance_in_stock.png" title="'+topVolumeText+'" /></a>';
    }
	sbi+= '</div>';
	sbi+= '<ul class="dealer_name_address">';
	sbi+= '		<li>';
	sbi+= '			<h4 class="dealer_name" onclick="triggerEvent(' + dealership.id + ', marker, ' + map_label + ');"><a href="Javascript:void(0);">' + dealership.name + '</a></h4>';
	sbi+= '		</li>';
	 if ((dealership.address !='') && (dealership.city != '') && (dealership.state !='') ){  
	sbi+= '		<li class="address"><p>' + dealership.address + '<br />' + dealership.city + ', '+ dealership.state + ' ' + dealership.zip + '<br />' + dealership.phone + '<br /><span class="distance">Distance: ' + dealership.formatDistance + ' </span></p></li>';
	sbi+= '		<li>';
	}else{
	sbi+='	<li class="mobile_user"><p>' +"We bring the tires to your vehicle" + '<br />' + dealership.phone + '</p></li>';
	sbi+= '		<li>';
	}	
	
	sbi+= '			<ul class="hours"><li><strong>'+ hourText +'</strong></li>' + hours + '</ul>';
	sbi+= '		</li>';
	sbi+= '		<li style="clear:both; display:block; padding:0;"></li>';
	 if ((dealership.address !='') && (dealership.city != '') && (dealership.state !='') ){  	
	sbi+= '		<li class="more_details no_print" id="more_dealer_details_sidebar' + dealership.id + '" onclick="display_dealer_info(' + dealership.id + ', marker,false, true, '+map_label+');"><a href="Javascript:void(0);"><strong>'+ moreDealerDetailsText +'</strong></a></li>';
	}else{
	}	
	sbi+= '<li class="no_print offers">';
	if ( null != dealership.promo && typeof dealership.promo != 'undefined' && dealership.promo != '' ){
		sbi+= '<a href="'+dealerPromoMessagePage+'" target="_blank" class="offer_icons" title="'+dealerPromoMessage+'"><img src="'+dealerPromoMessageImageUrl+'" title="'+ dealerPromoMessage +'" /></a>';
	}
	if ( dealership.filters[2] == true){
		sbi+= '<a href="javascript:void(0);" title="'+nationalAccountPromoMessage+'"><img src="/assets/bfg/system/images/icon_nationalacct.gif" title="'+ nationalAccountPromoMessage +'" /></a>';
	}
	sbi+= '</li>';
	sbi+= '<li style="clear:both; display:block; padding:0;"></li>';
	var dealerURLString = dealership.dealerURL;
	var newDealerURL = "";
	if( null != dealerURLString && "" != dealerURLString ){
		var indexOfHTTP = dealerURLString.indexOf("http://");
		if(indexOfHTTP < 0  ){
			
			newDealerURL = "http://";
			
		}
		/*var indexOfWWW = dealerURLString.indexOf("www");
		
		if(indexOfWWW < 0){
			var indexOfWWW1 = dealerURLString.indexOf("WWW")
			if(indexOfWWW1 < 0)
			{
				newDealerURL = newDealerURL + "www.";
			}			
		}*/
		newDealerURL ="'"+ newDealerURL + dealerURLString + "'";
		sbi+= '<li><a href="javascript:void(0);" onClick="openDealerLink(' + newDealerURL + ');_tag.dcsMultiTrack('+"'WT.z_dlclick'"+','+"'1'"+');">'+ dealerWebsiteLink +'</a></li>';	
		
		
	}
	sbi+= '	</ul>';
	sbi+= '</li>';
	return sbi;	
}

function build_location_selected(dealership,more_dealer_details, back_to_search_results){
	var hours = '';
	$.each(dealership.hours, function(label,value){	
		if ( hours != '' ) 
			hours += '';
		hours += '<li>' + label + ' ' + value + '</li>';
	});
	var	location_selected= '';	
	location_selected+= '					<li >';
	location_selected+= '						<ul class="dealer_name_address">';
	location_selected+= '							<li>';
	location_selected+= '								<h4 class="dealer_name">'+ dealership.name + '</h4>';
	location_selected+= '							</li>';
	location_selected+= '							<li class="address"><p>' + dealership.address + '<br />' + dealership.city + ', ' + dealership.state + ' ' + dealership.zip + '<br />' + dealership.phone + '<br /><span>Distance: ' + dealership.formatDistance + '</span></p></li>';
	location_selected+= '							<li>';
	location_selected+= '								<ul class="hours">';
	location_selected+= '									<li><strong>'+ hourText +'</strong></li>' + hours ;
	location_selected+= '								</ul>';
	location_selected+= '							</li>';
	if ( more_dealer_details ){
		location_selected+= '	<li class="dealer_details" id="more_dealer_details_' + dealership.id + '"><a href="Javascript:void(0);"><strong>'+ moreDealerDetailsText +'</strong></a></li>';
	}
	if(back_to_search_results){
		location_selected+= '	<li id="back_to_results_link"><a href="Javascript:void(0);">'+ backToSearchText +'</a></li>';
	}
	location_selected+= '						</ul>';
	location_selected+= '					</li>';
	
	return location_selected;
}

function build_dir_header(dealership, from){

	var dir_header = '';
	dir_header+= '	<ul>';
	dir_header+= '		<li>';
	dir_header+= '			<div class="marker_offer_panel">';
	dir_header+= '				<a class="marker" title="Mark" href="#">A</a>';
	dir_header+= '			</div>';
	dir_header+= '			<b>'+ directionsFromText +':</b><br />';
	dir_header+= '				<div class="directions_input">';
	dir_header+= '					<input type="text" id="directions_address" value="' + from + '" />';
	dir_header+= '					<img src="/assets/bfg/system/images/button_go.png" id="get_directions" class="go_button" />';
	dir_header+= '				</div>';
	dir_header+= '		</li>';
	dir_header+= '		<li>';
	dir_header+= '		<div class="marker_offer_panel">';
	dir_header+= '			<a class="marker" title="Mark" href="#">B</a>';
	dir_header+= '		</div>';
	dir_header+= '		<b>'+ directionsToText +':</b><br />' + dealership.name + '<br />' + dealership.address + ', ' + dealership.city + ', ' + dealership.state + ' ' + dealership.zip;
	dir_header+= '		</li>';
	dir_header+= '	</ul>'
	return dir_header;
	
}
function build_directions(route,dealership,from,polyline,bounds){      
	   	var path = route.overview_path;
		var legs = route.legs;
		startLocation = new Object();
        endLocation = new Object();
		var html_directions = 	'';	
		html_directions+= '	<div id="total_distance">';
		html_directions+= '	<img class="print_direction_button" src="/assets/bfg/system/images/button_print_directions.png">';		
		var totalDistance =0;
        for (var i = 0; i < route.legs.length; i++) {
		  totalDistance = route.legs[i].distance.text;
		}		
		html_directions+= '	<p><b>'+totalDistanceText+':</b> ' + totalDistance + '</p>';
		html_directions+= '	</div>';
		html_directions+= build_dir_header(dealership, from);
		html_directions+= '	<ol>';		
        for (i=0;i<legs.length;i++) {
		  if (i == 0) { 
            startLocation.latlng = legs[i].start_location;
            startMarker=createMarker(startLocation.latlng, "A");
			
          }
		  endLocation.latlng = legs[i].end_location;
          var steps = legs[i].steps;
          for (j=0;j<steps.length;j++) {
            var nextSegment = steps[j].path;
            html_directions += "<li>"+steps[j].instructions;
            var dist = "";
            if (steps[j].distance) dist += "&nbsp;"+steps[j].distance.text;
            if (dist != "") {
              html_directions += "("+dist+")<br /></li>";
            } else {
              html_directions += "</li>";

            }
			for (k=0;k<nextSegment.length;k++) {
			  polyline.getPath().push(nextSegment[k]);
              bounds.extend(nextSegment[k]);
            }
          }
        }
		html_directions+= '	</ol>';
		html_directions+= '	';
		polyline.setMap(map);
		map.fitBounds(bounds);
		endMarker = createMarker(endLocation.latlng, "B");
		return html_directions;
}

function createInfoServices(dealership){
	var details = null;
	var info = null;
	details = '';
		$.each(dealership['info'], function(title,list_items){
		info = dealership.info[title];
		var tirRelated = info["Pneus et services connexes"];
		
		if( null != tirRelated && tirRelated != "" ){
			details += '<h4>' + "Pneus et services connexes" + '</h4>';
			details += '<ul>';
			$.each(tirRelated, function(id,value){
				details+='<li>' + value + '</li>';
			});
			details+= '</ul>';
		}
		var otherProds = info["Autres produits et services"];
		if( null != otherProds && otherProds != "" ){
			details += '<h4>' + "Autres produits et services" + '</h4>';
			details += '<ul>';
			$.each(otherProds, function(id,value){
				details+='<li>' + value + '</li>';
			});
			details+= '</ul>';
		}
		var warrantyServ = info["Aide pour la garantie des pneus"];
		
		if( null != warrantyServ && warrantyServ != "" ){
			details += '<h4>' + "Aide pour la garantie des pneus" + '</h4>';
			details += '<ul>';
			$.each(warrantyServ, function(id,value){
				details+='<li>' + value + '</li>';
			});
			details+= '</ul>';
		}
		var convenience = info[$.validator.messages.DealerLocatorConveniences];
		if( null != convenience && convenience != "" ){
			details += '<h4>' + $.validator.messages.DealerLocatorConveniences + '</h4>';
			details += '<ul>';
			$.each(convenience, function(id,value){
				details+='<li>' + value + '</li>';
			});
			details+= '</ul>';
		}
	});
	return details;
}

function openPrintWindow(){
	var mywindow = window.open ('/dealer-locator/dealer-locator-print.page','mywindow','width=800,height=600,scrollbars=yes,status=no,resizable=yes');
	
}    
/* 
	scrollPst is scroller position to scroll upto
   scroll_position is the current scroll position
*/


function scrollPosition(id) {
	/*$("#location_results_information .results_block").scrollTop(0);
	if( id > 3 ){
		id = id-3;
		scrollHt = $("#listing_" + id).offset().top
		$("#location_results_information .results_block").scrollTop(scrollHt);
	}*/
	$("#location_results_information .results_block").scrollTop(0);
	var Resultcontainer = $(".result_content").offset().top;
	scrollHt = $("#listing_" + id).offset().top - Resultcontainer;
	$("#location_results_information .results_block").scrollTop(scrollHt);
}

function openDealerLink(url)
{
	if(dealerVisitWebsiteSrcID != "" && dealerVisitWebsiteTypeID != "" && dealerVisitWebsiteCatID !=""){
		var printaxel = Math.random() + "";
		var printa = printaxel * 10000000000000;
		$(".dealer_conviniences").append('<iframe src="http://fls.doubleclick.net/activityi;src='+dealerVisitWebsiteSrcID+';type='+dealerVisitWebsiteTypeID+';cat='+dealerVisitWebsiteCatID+';ord=' + printa + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>'); 	
	}	
	window.open(url);
}

/*
*	display_directions_on_enter
*
*	Click handler to submit information when enter is pressed from an input field
*	
*/
function display_directions_on_enter(event, dealership_id,  map_label){
	if ( event.keyCode == 13 ){
		display_directions(map, dealership_id , false , map_label);
		event.returnValue=false; 
		return false;
	}
}
function hideMoreDetailLink(id){
		$("p.dealer_details").css("visibility","hidden");
}

function removeInfoWrapper(){
	jQuery("[id=info_wrapper]").each(function(){	
		$(this).empty().remove();
	 });
}
