var registermap;
var registermarker;
var geocoder = new GClientGeocoder();


var accessIconSt="/images/maptools/accesIcon.png";
var clienticonSt ="/images/icon_homme.png";
var clienteiconSt ="/images/icon_femme.png";
var restoiconSt="/images/maptools/restaurant_vert.png";

var clienticon = new GIcon(G_DEFAULT_ICON,clienticonSt);
clienticon.iconSize = new GSize(30, 20);
clienticon.iconAnchor= new GPoint(15,20);// x=1/2xIcon y=yIcon
clienticon.infoWindowAnchor= new GPoint(20,0);// x=2/3xIcon y=0
clienticon.shadow ="";
var clienteicon = new GIcon(G_DEFAULT_ICON,clienteiconSt);
clienteicon.iconSize = new GSize(30, 20);
clienteicon.iconAnchor= new GPoint(15,20);// x=1/2xIcon y=yIcon
clienteicon.infoWindowAnchor= new GPoint(20,0);// x=2/3xIcon y=0
clienteicon.shadow ="";
var accessIcon=new GIcon(G_DEFAULT_ICON,accessIconSt);
accessIcon.iconSize = new GSize(10, 10);
accessIcon.iconAnchor= new GPoint(5,5);
accessIcon.shadow ="";
var restoicon=new GIcon(G_DEFAULT_ICON,restoiconSt);
restoicon.iconSize = new GSize(30, 30);
var quartierPoly = null;

function loadRegisterMap(changed) {
	if ($('ville').value != "" && $('cp').value != ""
			&& $('adresse_detail').value != "") {
		if (GBrowserIsCompatible()) {
			
			registermap = new GMap2($("register_map"));
			address = $('adresse_detail').value + ", " + $('ville').value
					+ ", " + $('cp').value + ", France";
			if (changed == undefined || changed == false)
				geocoder.getLocations(address, showRegisterLocation);
			else
				restoreRegisterLocation();
			registermap.addControl(new GSmallZoomControl3D());
			var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5,5));
			registermap.addControl(new GMenuMapTypeControl(),topRight);

		}
	} else {
		$('register_map').innerHTML = "<div class='importanterr' style='text-align:center;padding:100px 0 0 10px;'>Veuillez completer les informations de votre adresse</div>";
	
	}

}

function setQuartierOnMap(gmap, poly) {
	// if (quartierPoly != null)
	// gmap.removeOverlay(quartierPoly);
	// gmap.addOverlay(poly);
	// poly.show();
	quartierPoly = poly;

}

function restoreRegisterLocation() {
	var point = new GLatLng($('lat').value, $('lng').value);
	accuracy = 8;
	addRegisterOverlay(point, accuracy, true,true);
}

function showRegisterLocation(response) {
	if (response.Placemark != null && response.Placemark.length > 0) {
		place = response.Placemark[0];
		point = new GLatLng(place.Point.coordinates[1],
				place.Point.coordinates[0]);
		
		accuracy = place.AddressDetails.Accuracy;
		if (accuracy < 6) {
			
			new Ajax.Request(
					'/registration/getVilleCoords?id='
							+ $('villeid').value + "&ville=" + $('ville').value
							+ "&cp=" + $('cp').value, {
						onComplete : function(transport) {
							eval(transport.responseText);
						},
						asynchronous :false
					});
			accuracy = 5;
			$('lat').value = "";
			$('lng').value = "";
			
			
		} else {
			$('lat').value = point.lat();
			$('lng').value = point.lng();
			
		}
		addRegisterOverlay(point, accuracy, true,false);
	} else {
		new Ajax.Request('/registration/getVilleCoords?id='
				+ $('villeid').value + "&ville=" + $('ville').value + "&cp="
				+ $('cp').value, {
			onComplete : function(transport) {
				eval(transport.responseText);
			},
			asynchronous :false
		});
		accuracy = 5;
		
		// $('register_map').innerHTML = "<div class='importanterr'
		// style='text-align:center;padding:100px 0 0 10px;'>Veuillez corriger
		// les informations de votre adresse</div>";
	}


}

function addRegisterOverlay(point, accuracy, clearOthers,isRestoration) {
	infotext = "Vous pouvez me déplacer pour indiquer plus précisément votre emplacement.";
	infotextnotac = "Veuillez me déplacer pour indiquer plus précisément votre emplacement.";

	registermap.setCenter(point, 15);
	if (($('civilite') && ($('civilite').value == "2" || $('civilite').value == "3")) || ($('civ_client') && ($('civ_client').value == "2" || $('civ_client').value == "3")))
		registermarker = new GMarker(point, {
			icon :clienteicon,
			draggable :true
		});
	else
		registermarker = new GMarker(point, {
			icon :clienticon,
			draggable :true
		});

	GEvent
			.addListener(
					registermarker,
					"dragend",
					function(latlng) {			
						$('lat').value = latlng.lat();
						$('lng').value = latlng.lng();
						registermap.clearOverlays();
						registermap.addOverlay(registermarker);
/////////////////////////////////////////////////
						addAccesPointOnRegisterMap(registermap,registermarker,10,false);
/////////////////////////////////////////////////

						$('register_map_error').hide();
						registermarker
								.bindInfoWindowHtml("<div style='width:150px' id='map_info_window'>Votre emplacement est enregistré.<br/>Déplacez-moi pour indiquer plus précisément votre emplacement.</div>");
						registermarker
								.openInfoWindowHtml("<div style='width:150px' id='map_info_window'>Votre emplacement est enregistré.<br/>Déplacez-moi pour indiquer plus précisément votre emplacement.</div>");
						new Ajax.Updater('jscripts',
								'/registration/showQuartier?lat='
										+ latlng.lat() + '&lng=' + latlng.lng()
										+ '&ville=' + $('villeid').value
										+ '&villename=' + $('ville').value
										+ '&cp=' + $("cp").value, {
									evalScripts :true
								});

					});
	new Ajax.Updater('jscripts', '/registration/showQuartier?lat='
			+ point.lat() + '&lng=' + point.lng() + '&ville='
			+ $('villeid').value + '&villename=' + $('ville').value + '&cp='
			+ $("cp").value, {
		evalScripts :true
	});
	if (clearOthers == undefined || clearOthers == null || clearOthers == true || accessMarker!=null)
		registermap.clearOverlays();
	
/////////////////////////////////////////////////

		addAccesPointOnRegisterMap(registermap,registermarker,accuracy,isRestoration);

/////////////////////////////////////////////////

	registermap.addOverlay(registermarker);
	if (accuracy < 8) {

		registermarker
				.bindInfoWindowHtml("<div class='importanterr' style='width:150px' id='map_info_window'>Votre adresse n'est pas reconnu par notre système. "
						+ infotextnotac + "</div>");
		registermarker
				.openInfoWindowHtml("<div class='importanterr' style='width:150px' id='map_info_window'>Votre adresse n'est pas reconnu par notre système. "
						+ infotextnotac + "</div>");
		$('register_map_error').show();
	} else {
		registermarker
				.bindInfoWindowHtml("<div style='width:150px' id='map_info_window'>"
						+ infotext + "</div>");
		registermarker
				.openInfoWindowHtml("<div style='width:150px' id='map_info_window'>"
						+ infotext + "</div>");
		$('register_map_error').hide();
	}

	

	return false;
	
}


var addressmap = null;
var addressmarkers = new Array();

function loadAddressMap(aid) {
	if (GBrowserIsCompatible()) {
		if (aid != undefined && $("adresse_client_" + aid + "_map"))
			addressmap = new GMap2($("adresse_client_" + aid + "_map"));
		else
			addressmap = new GMap2("adresses_client_map");
		addressmap.addControl(new GSmallZoomControl3D());
		var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5,5));
		addressmap.addControl(new GMenuMapTypeControl(),topRight);
		
	}
}

function showClientAddress(latlngs, civ) {
	latlngs.each( function(latlng, id) {
		addClientAddressOnMap(latlng, civ, id); // Manque le paramètre latlng_road
	});
}

function addClientAddressOnMap(latlng,latlng_road, civ, id) {
	if (civ == undefined || civ == 1)
		var admarker = new GMarker(latlng, {
			icon :clienticon,
			draggable :false
		});
	else
		var admarker = new GMarker(latlng, {
			icon :clienteicon,
			draggable :false
		});
	addressmap.setCenter(latlng,17);
	addressmap.addOverlay(admarker);
	addressmarkers[id] = admarker;
	//////////////////////////////////////////
	var accessM = new GMarker(latlng_road,accessIcon);
	addressmap.addOverlay(accessM);
	showAccesPolylineOnMap(addressmap,admarker,accessM);
	
	/////////////////////////////////////////////
}
/////////////////////////////////////////////////////////////////////////////
/////////////////KEVIN
////////////////////////////////////////////////////////////////////////////
var searchmap =null;
var clientLoc=null;
var tab = new Array();
var mapContent=null;
function initialiazeSearchMap() {

	mapContent = $("map_search");
	if (mapContent.style.display == "none") {
		slideSearchMap(true);
		if (searchmap == null){
			showLoading();
			setTimeout('init()', 550);
		}else {
			init();
		}
	} else {
		slideSearchMap(false);
		searchmap.closeInfoWindow();
	}
	return false;
}

function init(){
	if (searchmap == null) {
		searchmap = new GMap2(mapContent);
		
		searchmap.addControl(new GSmallZoomControl3D());
		searchmap.disableScrollWheelZoom() ;
		clientLoc=new GLatLng($('c_lat').value,$('c_lng').value);

		afficheResultSearch();
		afficheClientMarker();
		tab.push(clientLoc);
		endLoading();
	}	
	searchmap.setCenter(clientLoc,18);
	setRightBounds(searchmap,tab);//définie le bon zoom pour que tous les points de tab soient visibles
}

function slideSearchMap(open){
	if (open){
	new Effect.SlideDown('map_search', {
		queue :'end',
		duration :0.5
	});

	}else {
		new Effect.SlideUp('map_search', {
			queue :'end',
			duration :0.5
		});
	}
}

function afficheClientMarker(){
	var marker;
	if (($('civilite') && ($('civilite').value == "2" || $('civilite').value == "3"))
			|| ($('civ_client') && ($('civ_client').value == "2" || $('civ_client').value == "3")))
		marker = new GMarker(clientLoc, clienteicon);
	else
		marker = new GMarker(clientLoc, clienticon);
	
    GEvent.addListener(marker, "click", function() {
    	marker.openInfoWindow("Vous êtes ici !");
    });
	displayMarkerOnMap(searchmap,marker);
    
}

function afficheResultSearch() {
	//Position Client : c_lat et c_lng
	//Position Resto : 'r_'+id+'_lat'
	var temp = $$('.restaurant_search_div');
	if (temp != null) {
		var id;
		
		for (i = 0; i < temp.length; i++) {
			id = temp[i].id.substring(11);
			var marker = createMarkerSearch(id,$('restaurant_name_'+id).innerHTML ,$('r_'+id+'_lat').value, $('r_'+id+'_lng').value,createRestoIcon(i+1));
			displayMarkerOnMap(searchmap,marker);
	
		}
	
	} 
	
	return false;
}

function createMarkerSearch(id, nom,lat, lng,icon){
	//Création d'un marque de type resto pour la recherche
	//Position Client : c_lat et c_lng
	//Position Resto : 'r_'+id+'_lat'
	var point =new GLatLng(lat,lng);
	tab.push(point);
	markerOp = { icon:icon };
	var marker= new GMarker(point,markerOp);
	var client =new GLatLng($('c_lat').value,$('c_lng').value);
	
	
	var html ='<div><a href="#" onclick=\"onMarkerClick(\'restaurant_header_\','+id+');return false;\"><h3>'+nom+'</h3></a><br/>'+
			"Distance : " +$('restaurant_distance_'+id).innerHTML+"</div>";
	marker.bindInfoWindowHtml(html) ;
	GEvent.addListener(marker, "click", function() {
	    marker.openInfoWindowHtml(html);
    });
	return marker;
}

function onMarkerClick(st,id){
	
	if ($('restaurant_detail_'+id).style.display == "none"){
		showHideAjaxInformation(id.toString(),'/restaurant/getRestaurantDetail','restaurant_detail');
	}
	else{
		scrollToRestoId(st,id);
	}
}

function scrollToRestoId(slideId,idAf){
	new Effect.ScrollTo(""+slideId+idAf+"",{
		duration : 1
	});
}

function displayMarkerOnMap(map,marker){
	map.addOverlay(marker);
}

function createRestoIcon(index){
		return new GIcon(G_DEFAULT_ICON,"/images/maptools/yellownumbers/marker"+index+".png");
			
}

//////////////////////ITINERAIRE///////////////////
var directions=null;
var checkpoint=null;
var checkpoint_reverse=null;
var clientLocation =null;
var fournLocation=null;
var directionMap=null;
var directionPanel=null;
var dirOpts=null;
var infoWindowResto=null;
function itineraireLoad(id){
	directions=null;
	checkpoint=null;
	checkpoint_reverse=null;
	clientLocation =null;
	fournLocation=null;
	directionMap=null;	
	dirOpts={};
	dirOpts.travelMode = G_TRAVEL_MODE_DRIVING;
	dirOpts.avoidHighways =false;
	dirOpts.locale=$('language_selected').value;
	infoWindowResto ="<div id=\"info_window_content\" class=\"info_window_content\">";
	clientLocation =new GLatLng($('client_lat').value,$('client_lng').value);
	fournLocation = new GLatLng ($('r_'+id+'_lat').value,$('r_'+id+'_lng').value);
	var fournStLoc = ($('rs_'+id+'_lat').value).toString().substring(0,9)+","+($('rs_'+id+'_lng').value).toString().substring(0,9);
	
	var dirMap = $('directionMap_'+id);
	directionPanel = $('directionPanel_'+id);
	$('directionHeader_'+id).innerHTML+=($('restaurant_name_'+id).innerHTML);
	infoWindowResto += $('restaurant_name_'+id).innerHTML;
	var temp =new GMap2(dirMap);
	temp.addControl(new GSmallZoomControl3D());
	directionMap=temp;
 
	directions = new GDirections(temp, directionPanel);

	GEvent.addListener(directions, "error", handleErrors);
	GEvent.addListener(directions, "addoverlay", onDirectionLoad);


	if ($('client_s_lat').value==null || $('client_s_lng').value==null || $('client_s_lat').value=="" || $('client_s_lng').value==""){
		var dir = new GDirections();
		dir.loadFromWaypoints([(clientLocation).toUrlValue(6),(clientLocation).toUrlValue(6)],{getPolyline:true});
		
		 GEvent.addListener(dir,"load", function() {
			 var p=dir.getPolyline().getVertex(0);
			 clientStLoc = (p.lat()).toString().substring(0,9)+","+(p.lng()).toString().substring(0,9);
			 checkpoint = [clientStLoc, fournStLoc];
			directions.loadFromWaypoints(checkpoint,dirOpts);
			
		 });
	}else{
		var clientStLoc =($('client_s_lat').value).toString().substring(0,9)+","+($('client_s_lng').value).toString().substring(0,9);
		checkpoint = [clientStLoc, fournStLoc];
		directions.loadFromWaypoints(checkpoint,dirOpts);
	
	}
	return false;
}

function onDirectionLoad(){
	var i= null;
	if (checkpoint_reverse==null)i=0;
	else i=1;
	
	var civ;
	if (($('civilite') && ($('civilite').value == "2" || $('civilite').value == "3"))
			|| ($('civ_client') && ($('civ_client').value == "2" || $('civ_client').value == "3")))
		civ = 1;
	else
		civ = 0;
	
	directions.getMarker(0).hide();
	directions.getMarker(1).hide();
	var mark;
	if (civ)
		mark = new GMarker(clientLocation,clienteicon);
	else
		mark = new GMarker(clientLocation,clienticon);
	var accessM = new GMarker(directions.getMarker(i).getLatLng(),accessIcon);
	showAccesPolylineOnMap(directionMap,mark,accessM);
	mark.bindInfoWindowHtml("<div id=\"info_window_content\" class=\"info_window_content\"><h2>Vous êtes ici !</h2></div>");
	
	directionMap.addOverlay(mark);
	
	i=(i+1)%2;
	mark = new GMarker(fournLocation,restoicon);
	mark.bindInfoWindowHtml(infoWindowResto);
	accessM = new GMarker(directions.getMarker(i).getLatLng(),accessIcon);
	showAccesPolylineOnMap(directionMap,mark,accessM);
	directionMap.addOverlay(mark);

	
	
customPanel(directionMap, "directionMap", directions,directionPanel, !i, civ);


	
	return false;
	
}

function handleErrors(){
	 if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS){
		   //alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + directions.getStatus().code);
		 	//Cas normalement impossible avec les points "onRoad" utilisés pr les iti
		   ($$('.directionMap'))[0].innerHTML = "<div class='importanterr' style='text-align:center;padding:100px 0 0 10px;'>Votre adresse n'est pas reconnue par notre système !</div>";
	 }else if (directions.getStatus().code == G_GEO_SERVER_ERROR){
	//	   alert("G_GEO_SERVER_ERROR");
		 ($$('.directionMap'))[0].innerHTML = "<div class='importanterr' style='text-align:center;padding:100px 0 0 10px;'>Ce service est momentanément indisponible. Veuillez nous excuser pour la gêne occasionnée.</div>";
	 }
		 else if (directions.getStatus().code == G_GEO_MISSING_QUERY)
		   alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + directions.getStatus().code);

		 else if (directions.getStatus().code == G_GEO_BAD_KEY)
		   alert("G_GEO_BAD_KEY");

		 else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
		   alert("G_GEO_BAD_REQUEST");
		  
		 else {
			 //alert("An unknown error occurred.");
			 ($$('.directionMap'))[0].innerHTML = "<div class='importanterr' style='text-align:center;padding:100px 0 0 10px;'>Cet itinéraire est impossible !</div>";
		 }
	 
	 directions=null;
}

function showMapOptions(id){
if (directions!=null){	
	if ($('optionMode_' + id).style.display == "none") {
		if ($('directionType_'+id).value== "G_TRAVEL_MODE_DRIVING"){
		new Effect.SlideDown('optionMode_' + id, {
			queue :'end',
			duration :0.5
		});
		new Effect.SlideDown('optionMap_' + id, {
			queue :'end',
			duration :0.5
		});
		}else{
			new Effect.SlideDown('optionMode_' + id, {
				queue :'end',
				duration :0.5
			});	
		}

	} else if ($('optionMap_' + id).style.display == "none") {
		new Effect.SlideUp('optionMode_' + id, {
			queue :'end',
			duration :0.5
		});
	}else{
		new Effect.SlideUp('optionMap_' + id, {
			queue :'end',
			duration :0.5
		});
		new Effect.SlideUp('optionMode_' + id, {
			queue :'end',
			duration :0.5
		});

	}
}
}

function HighWayDirection(ob,id) {
	if (directions != null) {
		$('directionType_'+id).value= G_TRAVEL_MODE_DRIVING;
		directionMap.clearOverlays();
		dirOpts.travelMode = G_TRAVEL_MODE_DRIVING;
		dirOpts.avoidHighways = ob;

		if (checkpoint_reverse == null)
			directions.loadFromWaypoints(checkpoint, dirOpts);
		else
			directions.loadFromWaypoints(checkpoint_reverse, dirOpts);

	}
}

function directionMode(ob,id){
	if (directions != null) {
		dirOpts.avoidHighways = false;
		if (ob == "G_TRAVEL_MODE_WALKING") {
			dirOpts.travelMode = G_TRAVEL_MODE_WALKING;
			$('checkHighWay_' + id).checked = false;
			new Effect.SlideUp('optionMap_' + id, {
				queue :'end',
				duration :0.5
			});
		} else {
			dirOpts.travelMode = G_TRAVEL_MODE_DRIVING;
			new Effect.SlideDown('optionMap_' + id, {
				queue :'end',
				duration :0.5
			});
		}
		directionMap.clearOverlays();
		if (checkpoint_reverse == null)
			directions.loadFromWaypoints(checkpoint, dirOpts);
		else
			directions.loadFromWaypoints(checkpoint_reverse, dirOpts);
	}
}

function returnDirection(id){
	//itinéraire inverse 
	
	if (directions != null) {
		directionMap.clearOverlays();
		if (checkpoint_reverse == null) {
			checkpoint_reverse = [ checkpoint[1], checkpoint[0] ];

			directions.loadFromWaypoints(checkpoint_reverse, dirOpts);
		} else {
			checkpoint_reverse = null;

			directions.loadFromWaypoints(checkpoint, dirOpts);
		}
	}
}


//============ custom direction panel ===============
var html = "";
//=== waypoint banner ===
function waypoint(point, type, address,mapname,returnDir,civ) {
  var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';

			html += '<table style="border: 1px solid silver; margin: 10px 0px; background-color: rgb(238, 238, 238); border-collapse: collapse; color: rgb(0, 0, 0);">';
			html += '  <tr style="cursor: pointer;" onclick=' + target + '>';
			html += '    <td style="padding: 4px 15px 0px 5px; vertical-align: middle; width: 20px;">';
		    if (type == "play" && !returnDir) {
		    	if (civ)
		    		html += '      <img src="' + clienteiconSt + '">'
		    	else 
		    		html += '      <img src="' + clienticonSt + '">'
		    }else if (type == "stop" && returnDir) {
		    	if (civ)
		    		html += '      <img src="' + clienteiconSt + '">'
		    	else 
		    		html += '      <img src="' + clienticonSt + '">'
			
			} else{
				html += '      <img src="'+restoiconSt+'">'
			}
			
			
			html += '    <\/td>';
			html += '    <td style="vertical-align: middle; width: 100%;">';
			html += address;
			html += '    <\/td>';
			html += '  <\/tr>';
			html += '<\/table>';
  
}

//=== route distance ===
function routeDistance(dist) {
html += '<div style="text-align: right; padding-bottom: 0.3em;">' + dist + '<\/div>';
}      

//=== step detail ===
function detail(point, num, description, dist,mapname) {
var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
html += '<table style="margin: 0px; padding: 0px; border-collapse: collapse;">';
html += '  <tr style="cursor: pointer;" onclick='+target+'>';
html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px; vertical-align: top; text-align: right;">';
html += '      <a href="javascript:void(0)"> '+num+'. <\/a>';
html += '    <\/td>';
html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px; vertical-align: top; width: 100%;">';
html +=        description;
html += '    <\/td>';
html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px 0.3em 0.5em; vertical-align: top; text-align: right;">';
html +=        dist;
html += '    <\/td>';
html += '  <\/tr>';
html += '<\/table>';
}

//=== Copyright tag ===
function copyright(text) {
html += '<div style="font-size: 0.86em;">' + text + "<\/div>";
}

function customPanel(map,mapname,dirn,div,returnDir,civ) {
 // === read through the GRoutes and GSteps ===
	html = "";
	
for ( var i = 0; i < dirn.getNumRoutes(); i++) {
		var type;
		if (i == 0) {
			type = "play";
		} else {
			type = "pause";
		}
		var route = dirn.getRoute(i);
		var geocode = route.getStartGeocode();
		var point = route.getStep(0).getLatLng();
		// === Waypoint at the start of each GRoute
		waypoint(point, type, geocode.address, mapname, returnDir,civ);
		routeDistance(route.getDistance().html + " ("
				+ route.getDuration().html + ")");

		for ( var j = 0; j < route.getNumSteps(); j++) {
			var step = route.getStep(j);
			// === detail lines for each step ===
			detail(step.getLatLng(), j + 1, step.getDescriptionHtml(), step
					.getDistance().html, mapname);
		}
	}

	// === the final destination waypoint ===
	var geoCode = route.getEndGeocode();
	var p = route.getEndLatLng();
	waypoint(p, "stop", geoCode.address, mapname, returnDir,civ);

	// === the copyright text ===
	copyright(dirn.getCopyrightsHtml());

	// === drop the whole thing into the target div
	div.innerHTML = "";
//	html+='<div class="warning_for_direction">Cet itinéraire est fourni à titre indicatif. Il est possible que vous deviez suivre un itinéraire différent de celui indiqué en raison de travaux, de bouchons, des conditions météorologiques, de déviations ou d\'autres perturbations. Veuillez en tenir compte lors de la préparation de votre trajet. Veillez en outre à respecter le code la route et toutes les signalisations sur votre trajet.</div>';
	div.innerHTML = html;

} // ============ end of customPanel function ===========


////////////////////////////ACCES POLYLINE///////////////////////////////////////////////////////
var accessMarker=null;

var poly=null;

function addAccesPointOnRegisterMap(map,marker,precision,isRestoration){

	/*if (accessMarker != null) {
		map.clearOverlays() ;
		map.removeOverlay(accessMarker);
		map.removeOverlay(poly);
		accessMarker=null;
		
	}*/
	
	if (isRestoration) {
		var p = new GLatLng($('lat_street').value, $('lng_street').value);
		accessMarker = new GMarker(p, {
			draggable :true,
			icon :accessIcon
		});

		GEvent.addListener(accessMarker, "dragend", function(latlng) {

			var dirn2 = new GDirections();
			dirn2.loadFromWaypoints( [ latlng.toUrlValue(6),
					latlng.toUrlValue(6) ], {
				getPolyline :true
			});
			GEvent.addListener(dirn2, "load", function() {
				var p2 = dirn2.getPolyline().getVertex(0);
				accessMarker.setLatLng(p2);
				map.removeOverlay(poly);
				poly = new GPolyline( [ p2, (marker.getLatLng()) ], "blue");
				map.addOverlay(poly);

				$('lat_street').value = p2.lat();
				$('lng_street').value = p2.lng();

			});
		});
		poly = new GPolyline( [ p, (marker.getLatLng()) ], "blue");
		map.addOverlay(accessMarker);
		map.addOverlay(poly);
	} else {
		// if (!isRestoration || $('lat_street').value == "" ||
		// $('lat_street').value == null || $('lng_street').value == "" ||
		// $('lng_street').value == null) {

		var dirn1 = new GDirections();
		dirn1.loadFromWaypoints( [ (marker.getLatLng()).toUrlValue(6),
				(marker.getLatLng()).toUrlValue(6) ], {
			getPolyline :true
		});

		GEvent.addListener(dirn1, "load", function() {
			var p = dirn1.getPolyline().getVertex(0);
			accessMarker = new GMarker(p, {
				draggable :true,
				icon :accessIcon
			});

			GEvent.addListener(accessMarker, "dragend", function(latlng) {

				var dirn2 = new GDirections();
				dirn2.loadFromWaypoints( [ latlng.toUrlValue(6),
						latlng.toUrlValue(6) ], {
					getPolyline :true
				});
				GEvent.addListener(dirn2, "load",
						function() {
							var p2 = dirn2.getPolyline().getVertex(0);
							accessMarker.setLatLng(p2);
							map.removeOverlay(poly);
							poly = new GPolyline( [ p2, (marker.getLatLng()) ],
									"blue");
							map.addOverlay(poly);

							$('lat_street').value = p2.lat();
							$('lng_street').value = p2.lng();

						});
			});

			poly = new GPolyline( [ p, (marker.getLatLng()) ], "blue");
			map.addOverlay(accessMarker);
			map.addOverlay(poly);

			if (precision > 7) {
				$('lat_street').value = p.lat();
				$('lng_street').value = p.lng();
			}
			return false;
		});
	} 
    return false;
	
}

function showAccesPolylineOnMap(map,marker,accessM){
	//affiche le polyline entre le marker et son point d'acces sur la route
	//sur la map "map"
	
	var pol = new GPolyline([accessM.getLatLng(),marker.getLatLng()], "blue") ;
    if (pol.getVertexCount()>0){
    	map.addOverlay(pol);
    }
    
	return false;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////

function printCommand(id){
	
	
	
	
	
	
	
	
	
	
	
	
}

//////////////////////////////////////////////////////////////////////////////////////////////////////
function isStreetViewData(point) {
	//Renvoi un booléen qui signifie si Google peut afficher le streetview de ce point !
		
	var temp = new GStreetviewClient(); 
	temp.getNearestPanorama(point, function(data){
			//if (data.code==200)
		alert (data.code);
	}); 
	return false;
}