allPoints = new Object();
pointsPassage = [];
nbGeocodageSuite = 0;
redPointer = "common/img/mm_20_red.png";
greenPointer = "common/img/mm_20_green.png";
bluePointer = "common/img/mm_20_blue.png";
yellowPointer = "common/img/mm_20_yellow.png";
whitePointer = "common/img/mm_20_white.png";
nodePointer = 'common/img/node.gif';
var lrvCartographie;

// //////////::
var map, allpointstab = [];

function replaceRue(rue) {
	var rueMin = rue.toLowerCase();
	if (rueMin == 'centre' || rueMin == 'centre ' || rueMin == ' centre'
			|| rueMin == 'mairie' || rueMin == 'centre-ville'
			|| rueMin == 'centre ville' || rueMin == 'gare'
			|| rueMin == 'bourg' || rueMin == 'eglise'
			|| rueMin == 'rue principale' || rueMin == 'village'
			|| rueMin == 'aucun')
		return "";
	else
		return rue;
}


// TODO: not used anymore, kept just in case rollback needed
function inscriptionreAdrOK(addressDep, adresseArr){
	if (GBrowserIsCompatible()) {
	document.getElementById('confirm').disabled=true;
	var geocoder = new GClientGeocoder();
		 geocoder.getLatLng(
		    addressDep,
		    function(pointa) {
		    if(document.adressesCorrectionConfirmForm.latitudeDepart.value!="0.0"&&document.adressesCorrectionConfirmForm.longitudeDepart.value!="0.0"&&document.adressesCorrectionConfirmForm.spotedPointDepart.value!=""){
	
		    	// copy
		      		var pays = addressDep.substring(addressDep.lastIndexOf(","));
				    var nopays =addressDep.substring(0, addressDep.lastIndexOf(","));
				    var ville = nopays.substring(nopays.lastIndexOf(","));
				    var finalAdress=ville+", "+pays;
			      	var geocoder9 = new GClientGeocoder();
			  		geocoder9.getLatLng(
			    	finalAdress,
			    	function(pointk) {
		      		if (!pointk) {
		      			// do nothing
						
		      		} else {
		      		
		      		document.adressesCorrectionConfirmForm.adresseDepOK.value="";
		    		var pointDep = getPoint(parseFloat(document.adressesCorrectionConfirmForm.latitudeDepart.value), parseFloat(document.adressesCorrectionConfirmForm.longitudeDepart.value));
					var map = new GMap2(document.getElementById('carteDepart'));
					map.setCenter(pointDep, 12);
					map.addControl(new GSmallMapControl());
					var marker = new GMarker(pointDep, {icon:getIcon(redPointer),draggable: true});
	
	        
					GEvent.addListener(marker, "dragend", function() {
	  	  				var pointb = marker.getPoint();
						document.adressesCorrectionConfirmForm.latitudeDepart.value=parseFloat(pointb.lat());
						document.adressesCorrectionConfirmForm.longitudeDepart.value=parseFloat(pointb.lng());
						document.adressesCorrectionConfirmForm.adresseDepOK.value="";
					});
					
					document.getElementById('confirm').disabled=false;  
					map.addOverlay(marker);	 								
		      		}
			    }
			  	);
			  	// copy
			  	
	
		    }
		    else
		    {
		      if (!pointa) {
		      var pays = addressDep.substring(addressDep.lastIndexOf(","));
		      var nopays = addressDep.substring(0, addressDep.lastIndexOf(","));
		      var ville = nopays.substring(nopays.lastIndexOf(","));
		      var finalAdress=ville+", "+pays;
		      	var geocoder2 = new GClientGeocoder();
		  		geocoder2.getLatLng(
		    	finalAdress,
		    	function(pointb) {
		      		if (!pointb) {
		      			document.adressesCorrectionConfirmForm.adresseDepOK.value="no";
		      			document.getElementById('carteDepart').innerHTML="Adresse de depart non reconnue ! <br> Corrigez la dans le formulaire ci contre <br> puis cliquez sur \"Voir sur la carte\" !";
		      			document.adressesCorrectionConfirmForm.latitudeDepart.value=0;
						document.adressesCorrectionConfirmForm.longitudeDepart.value=0;
		      		} else {
	
						document.adressesCorrectionConfirmForm.latitudeDepart.value=parseFloat(pointb.lat());
						document.adressesCorrectionConfirmForm.longitudeDepart.value=parseFloat(pointb.lng());
						document.adressesCorrectionConfirmForm.adresseDepOK.value="";
						
						var pointDep = getPoint(document.adressesCorrectionConfirmForm.latitudeDepart.value, document.adressesCorrectionConfirmForm.longitudeDepart.value);
							var map = new GMap2(document.getElementById('carteDepart'));
							map.setCenter(pointDep, 12);
							map.addControl(new GSmallMapControl());
							var marker = new GMarker(pointDep, {icon:getIcon(redPointer),draggable: true});
	
							GEvent.addListener(marker, "dragend", function() {
	  	  					var pointc = marker.getPoint();
								document.adressesCorrectionConfirmForm.latitudeDepart.value=parseFloat(pointc.lat());
								document.adressesCorrectionConfirmForm.longitudeDepart.value=parseFloat(pointc.lng());
								document.adressesCorrectionConfirmForm.adresseDepOK.value="";
				
											
	  						});
							map.addOverlay(marker);	      			
		      		}
			    }
			  	);
		      
		      
		      } else {     
				// geocoding depart
		      	
				document.adressesCorrectionConfirmForm.latitudeDepart.value=parseFloat(pointa.lat());
				document.adressesCorrectionConfirmForm.longitudeDepart.value=parseFloat(pointa.lng());
				document.adressesCorrectionConfirmForm.adresseDepOK.value="";
				var pointDep = getPoint(document.adressesCorrectionConfirmForm.latitudeDepart.value, document.adressesCorrectionConfirmForm.longitudeDepart.value);
					var map = new GMap2(document.getElementById('carteDepart'));
					map.setCenter(pointDep, 12);
					map.addControl(new GSmallMapControl());
					
					var marker = new GMarker(pointDep, {icon:getIcon(redPointer),draggable: true});
	
						GEvent.addListener(marker, "dragend", function() {
					  	var pointd = marker.getPoint();
					  	
						document.adressesCorrectionConfirmForm.latitudeDepart.value=parseFloat(pointd.lat());
						document.adressesCorrectionConfirmForm.longitudeDepart.value=parseFloat(pointd.lng());
						document.adressesCorrectionConfirmForm.adresseDepOK.value="";
						reverseGeocodeMovedMarker(pointd, document.adressesCorrectionConfirmForm.villeDepart, document.adressesCorrectionConfirmForm.adresseDepart);
			  		});
			  		
					map.addOverlay(marker);
				
				// geocoding arrivee
				}}
				if(document.adressesCorrectionConfirmForm.latitudeArrivee.value!="0.0"&&document.adressesCorrectionConfirmForm.longitudeArrivee.value!="0.0"&&document.adressesCorrectionConfirmForm.spotedPointArrivee.value!=""){
					// copy
		      		var pays = adresseArr.substring(adresseArr.lastIndexOf(","));
				    var nopays =adresseArr.substring(0, adresseArr.lastIndexOf(","));
				    var ville = nopays.substring(nopays.lastIndexOf(","));
				    var finalAdress=ville+", "+pays;
			      	var geocoder8 = new GClientGeocoder();
			  		geocoder8.getLatLng(
			    	finalAdress,
			    	function(pointj) {
		      		if (!pointj) {
		      			// do nothing
						
		      		} else {
		      				document.adressesCorrectionConfirmForm.adresseArrOK.value="";	
							var pointArr= getPoint(parseFloat(document.adressesCorrectionConfirmForm.latitudeArrivee.value), parseFloat(document.adressesCorrectionConfirmForm.longitudeArrivee.value));
							var map2 = new GMap2(document.getElementById('carteArrivee'));
							map2.setCenter(pointArr, 12);
							map2.addControl(new GSmallMapControl());
							var marker = new GMarker(pointArr, {icon:getIcon(redPointer),draggable: true});
						
							GEvent.addListener(marker, "dragend", function() {
								  	var pointe = marker.getPoint();
									document.adressesCorrectionConfirmForm.latitudeArrivee.value=parseFloat(pointe.lat());
									document.adressesCorrectionConfirmForm.longitudeArrivee.value=parseFloat(pointe.lng());
									document.adressesCorrectionConfirmForm.adresseArrOK.value="";
									
						  		});
	
							map2.addOverlay(marker); 
							document.getElementById('confirm').disabled=false;  		
		      		}
			    }
			  	);
			  	// copy
	
				}else{
				var geocoder3 = new GClientGeocoder();
		  		geocoder3.getLatLng(
		    	adresseArr,
		    	function(pointf) {
		      	 if (!pointf) {
		      		var pays = adresseArr.substring(adresseArr.lastIndexOf(","));
				    var nopays =adresseArr.substring(0, adresseArr.lastIndexOf(","));
				    var ville = nopays.substring(nopays.lastIndexOf(","));
				    var finalAdress=ville+", "+pays;
			      	var geocoder4 = new GClientGeocoder();
			  		geocoder4.getLatLng(
			    	finalAdress,
			    	function(pointg) {
		      		if (!pointg) {
		      			document.adressesCorrectionConfirmForm.adresseArrOK.value="no";
		      			document.getElementById('carteArrivee').innerHTML="Adresse d'arriv&eacute;e non reconnue ! <br> Corrigez-la dans le formulaire ci-contre <br> puis cliquez sur \"Voir sur la carte\" !";
		      			document.adressesCorrectionConfirmForm.latitudeArrivee.value=0;
						document.adressesCorrectionConfirmForm.longitudeArrivee.value=0;
						
		      		} else {
				      	
						document.adressesCorrectionConfirmForm.latitudeArrivee.value=parseFloat(pointg.lat());
						document.adressesCorrectionConfirmForm.longitudeArrivee.value=parseFloat(pointg.lng());
						
						
						//submit
						
						document.adressesCorrectionConfirmForm.adresseArrOK.value="";	
						var pointArr= getPoint(document.adressesCorrectionConfirmForm.latitudeArrivee.value, document.adressesCorrectionConfirmForm.longitudeArrivee.value);
						var map2 = new GMap2(document.getElementById('carteArrivee'));
						map2.setCenter(pointArr, 12);
						map2.addControl(new GSmallMapControl());
						var marker = new GMarker(pointArr, {icon:getIcon(redPointer),draggable: true});
				
							GEvent.addListener(marker, "dragend", function() {
						  	  	var pointh = marker.getPoint();
						  	
							document.adressesCorrectionConfirmForm.latitudeArrivee.value=parseFloat(pointh.lat());
							document.adressesCorrectionConfirmForm.longitudeArrivee.value=parseFloat(pointh.lng());
							document.adressesCorrectionConfirmForm.adresseArrOK.value="";
							
													
				  		});
	
						map2.addOverlay(marker); 
						document.getElementById('confirm').disabled=false;     			
		      		}
			    }
			  	);
		      
		      
		      } else {
		      	
				document.adressesCorrectionConfirmForm.latitudeArrivee.value=parseFloat(pointf.lat());
				document.adressesCorrectionConfirmForm.longitudeArrivee.value=parseFloat(pointf.lng());
				
				//submit
				document.adressesCorrectionConfirmForm.adresseArrOK.value="";
	
					var pointArr= getPoint(document.adressesCorrectionConfirmForm.latitudeArrivee.value, document.adressesCorrectionConfirmForm.longitudeArrivee.value);
					var map2 = new GMap2(document.getElementById('carteArrivee'));
					map2.setCenter(pointArr, 12);
					map2.addControl(new GSmallMapControl());
					var marker = new GMarker(pointArr, {icon:getIcon(redPointer),draggable: true});
	
					GEvent.addListener(marker, "dragend", function() {
				  	  	var pointi = marker.getPoint();
	
							document.adressesCorrectionConfirmForm.latitudeArrivee.value=parseFloat(pointi.lat());
							document.adressesCorrectionConfirmForm.longitudeArrivee.value=parseFloat(pointi.lng());
							document.adressesCorrectionConfirmForm.adresseArrOK.value="";
							
							reverseGeocodeMovedMarker(pointi, document.adressesCorrectionConfirmForm.villeArrivee, document.adressesCorrectionConfirmForm.adresseArrivee);
													
				  		});
	
					map2.addOverlay(marker);
					document.getElementById('confirm').disabled=false;
	
		      }
		    }
		  );
				
		     } 
		    }
		  );  
	}else{
		alert("Votre navigateur ne supporte pas la cartographie. Utilisez plutot Firefox, IE, Safari, Opera 8.02 ou Netscape 7.1");
	}
}

function getPoint(latitude, longitude) {
	var point = new GLatLng(latitude, longitude);
	return point;
}

function checkComplementValid() {
	var tempdep = allPoints[document.adressesCorrectionConfirmForm.spotedPointDepart.value];
	var temparr = allPoints[document.adressesCorrectionConfirmForm.spotedPointArrivee.value];
	if (tempdep == undefined) {
		document.adressesCorrectionConfirmForm.spotedPointDepart.value == "0.0";
		document.adressesCorrectionConfirmForm.spotedPointDepart.value == "";
	} else {
		setAdresseDepart($('spotedPointDepart').value);
	}
	if (temparr == undefined) {
		document.adressesCorrectionConfirmForm.spotedPointArrivee.value == "0.0";
		document.adressesCorrectionConfirmForm.spotedPointArrivee.value == "";
	} else {
		setAdresseArrivee($('spotedPointArrivee').value);
	}
}

function setAdresseArrivee(id) {
	var ptDetail = allPoints[id];
	if (ptDetail.villeA() != '') {
		document.adressesCorrectionConfirmForm.numArrivee.value = ptDetail
				.numA();
		document.adressesCorrectionConfirmForm.adresseArrivee.value = ptDetail
				.rueA();
		document.adressesCorrectionConfirmForm.villeArrivee.value = ptDetail
				.villeA();
		document.adressesCorrectionConfirmForm.paysArrivee.value = ptDetail
				.paysA();
		document.adressesCorrectionConfirmForm.numArriveeHidden.value = ptDetail
				.numA();
		document.adressesCorrectionConfirmForm.adresseArriveeHidden.value = ptDetail
				.rueA();
		document.adressesCorrectionConfirmForm.villeArriveeHidden.value = ptDetail
				.villeA();
		document.adressesCorrectionConfirmForm.latitudeArrivee.value = ptDetail
				.latitudeA();
		document.adressesCorrectionConfirmForm.longitudeArrivee.value = ptDetail
				.longitudeA();
		document.adressesCorrectionConfirmForm.spotedPointArrivee.value = id;
//		correctArriveeMap();
		trajetMapLocatorArrivee.addSpotedPointOnMap();
	}
}

function setAdresseDepart(id) {
	var ptDetail = allPoints[id];
	if (ptDetail.villeA() != '') {
		document.adressesCorrectionConfirmForm.numDepart.value = ptDetail
				.numA();
		document.adressesCorrectionConfirmForm.adresseDepart.value = ptDetail
				.rueA();
		document.adressesCorrectionConfirmForm.villeDepart.value = ptDetail
				.villeA();
		document.adressesCorrectionConfirmForm.paysDepart.value = ptDetail
				.paysA();
		document.adressesCorrectionConfirmForm.latitudeDepart.value = ptDetail
				.latitudeA();
		document.adressesCorrectionConfirmForm.longitudeDepart.value = ptDetail
				.longitudeA();
		// document.adressesCorrectionConfirmForm.spotedPointDepart.value=id;
//		correctDepartMap();
		trajetMapLocatorDepart.addSpotedPointOnMap();
	}
}

function loadPointDep(elemId, id, level) {
	loadKids(elemId, id, level, 'spotedPointDepart', 'loadPointDep');
	if (id != "") {
		setAdresseDepart(id);
	} else {
		if (!$(elemId).attributes['changeFromInput']) {
			document.adressesCorrectionConfirmForm.numDepart.value = "";
			document.adressesCorrectionConfirmForm.adresseDepart.value = "";
			document.adressesCorrectionConfirmForm.villeDepart.value = "";
			document.adressesCorrectionConfirmForm.paysDepart.value = "France";
			// document.adressesCorrectionConfirmForm.spotedPointDepart.value="";
		}
	}
}

function loadPointArr(elemId, id, level) {
	loadKids(elemId, id, level, 'spotedPointArrivee', 'loadPointArr');
	if (id != "") {
		setAdresseArrivee(id);
	} else {
		if (!$(elemId).attributes['changeFromInput']) {
			document.adressesCorrectionConfirmForm.numArrivee.value = "";
			document.adressesCorrectionConfirmForm.adresseArrivee.value = "";
			document.adressesCorrectionConfirmForm.villeArrivee.value = "";
			document.adressesCorrectionConfirmForm.paysArrivee.value = "France";
			document.adressesCorrectionConfirmForm.numArriveeHidden.value = "";
			document.adressesCorrectionConfirmForm.adresseArriveeHidden.value = "";
			document.adressesCorrectionConfirmForm.villeArriveeHidden.value = "";
			// document.adressesCorrectionConfirmForm.spotedPointArrivee.value="";
		}
	}
}

var delayed = 0;

function savePointsAndSubmit() {
	// Si on est en train de calculer des choses, on timeout et on revient
	if (lrvCartographie.isDragged != 0) {
		window.setTimeout("savePointsAndSubmit()", 200);
	} else {
		savePoints();
		document.adressesCorrectionConfirmForm.submit();
	}
}

function savePoints() {

	var pointsConcat = "";
	for ( var i = 0; i < lrvCartographie.pointsPassage.length; i++) {
		var marker = lrvCartographie.pointsPassage[i];
		var pointsConcat = pointsConcat + marker.getPoint().lat() + ","
				+ marker.getPoint().lng() + ";";
	}
	document.adressesCorrectionConfirmForm.pointsPassage.value = pointsConcat;
	// document.adressesCorrectionConfirmForm.pointsPassage.value=document.adressesCorrectionConfirmForm.itineraireLineString.value;

}

function reinitTrajetMap() {
	document.getElementById("trajetMap").innerHTML = "";
	document.adressesCorrectionConfirmForm.pointsPassage.value = "";

	document.adressesCorrectionConfirmForm.itineraireLineString.value = "";
	setTimeout("writeTrajetMap()", 500)
}

function writeTrajetMap() {
	var latDep = parseFloat(document.adressesCorrectionConfirmForm.latitudeDepart.value);
	var latArr = parseFloat(document.adressesCorrectionConfirmForm.latitudeArrivee.value);
	var longDep = parseFloat(document.adressesCorrectionConfirmForm.longitudeDepart.value);
	var longArr = parseFloat(document.adressesCorrectionConfirmForm.longitudeArrivee.value);

	lrvCartographie = new LrvCartographie("RW");
	var ptPassageLineString = document.adressesCorrectionConfirmForm.pointsPassage.value;
	lrvCartographie.setWaypointsFromCoordinates(latDep, longDep, latArr,
			longArr, ptPassageLineString)
	lrvCartographie.onloadFromPolyLine = onGDirectionsLoadFromPolyline;
	lrvCartographie.showMapInside(document.getElementById("trajetMap"));
}

function setIconPointerData(gIcon) {
	gIcon.shadow = '';
	gIcon.image = contextPath + "/" + nodePointer;
	gIcon.iconSize = new GSize(10, 10);
	gIcon.shadowSize = new GSize(0, 0);
	gIcon.iconAnchor = new GPoint(5, 5);
	gIcon.infoWindowAnchor = new GPoint(5, 5);
	gIcon.dragCrossImage = 'empty.gif'; // undocumented String: indicates an
										// image to be used as the drag cross.
										// If you set it to the null string, you
										// get the default drag_cross_67_16.png
										// image.
	gIcon.dragCrossSize = GSize(1, 1); // undocumented GSize(): indicates the
										// size of the drag cross.
	gIcon.maxHeight = 1; // undocumented integer: The maximum difference in
							// height between the marker anchor and the drag
							// cross anchor during dragging. Setting the
							// maxHeight to zero causes it to use the default
							// 13.
}

function map_click(marker, point) {
	window.alert("click ?")
	if (marker) {
		/*
		 * if(marker.genre!='rouge'){ rmvArray(pointsPassage,
		 * marker.marker_num); map.removeOverlay(marker); }
		 */
	} else {
		if (pointsPassage.length >= 2)
			alert("Attention, vous ne pouvez donner que 2 points de passage ! Si le trajet n'est pas correct, reinitialisez le pour recommencer.");
		else {
			var mark = new GMarker(
					point,
					{
						title : 'Cliquez-moi dessus pour me supprimer, ou faites moi glisser ou vous le souhaitez !',
						icon : getIcon('common/img/mm_20_green.png'),
						draggable : true
					});
			var marker_num = pointsPassage.length;
			mark.marker_num = marker_num;
			mark.genre = 'vert';
			pointsPassage[marker_num] = mark;
			GEvent.addListener(mark, "dragend", function() {
				pointsPassage[mark.marker_num] = mark;
			});

			// map.addOverlay(mark);
			var allpointstab = [];
			allpointstab[0] = markerDep.getPoint();
			for ( var i = 0; i < pointsPassage.length; i++) {
				allpointstab[allpointstab.length] = pointsPassage[i].getPoint();
			}
			allpointstab[allpointstab.length] = markerArr.getPoint();
			gdir.clear();
			gdir = new GDirections(map);
			GEvent.addListener(gdir, "load", onGDirectionsLoad);
			GEvent.addListener(gdir, "error", handleErrorsMark);

			gdir.loadFromWaypoints(allpointstab);

		}
	}
}

function getIcon(style) {
	var gIcon = new GIcon();
	setIconData(style, gIcon);
	return gIcon;
}

function setIconData(style, gIcon) {
	gIcon.image = contextPath + "/" + style;
	gIcon.iconSize = new GSize(12, 20);
	gIcon.shadowSize = new GSize(22, 20);
	gIcon.iconAnchor = new GPoint(6, 20);
	gIcon.infoWindowAnchor = new GPoint(5, 1);
	return gIcon;
}

function rmvArray(tab, obj) {
	for (i = obj; i < tab.length; i++) {
		tab[i] = tab[i + 1];
	}
	tab.pop();
}

function changeDep() {
	document.adressesCorrectionConfirmForm.spotedPointDepart.value = "";
}

function changeArr() {
	document.adressesCorrectionConfirmForm.spotedPointArrivee.value = "";
}

function handleErrorCode(code) {
	if (code == G_GEO_UNKNOWN_ADDRESS)
		alert("Cette adresse n est pas reconnue.\nCode erreur: " + code);
	else if (code == G_GEO_SERVER_ERROR)
		alert("Itineraire impossible a determiner.\n Error code: " + code);

	else if (code == G_GEO_MISSING_QUERY)
		alert("Pour tracer un itineraire, il faut un point de depart et d arrivee.\n Error code: "
				+ code);

	// else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS) <--- Doc bug...
	// this is either not defined, or Doc is wrong
	// alert("The geocode for the given address or the route for the given
	// directions query cannot be returned due to legal or contractual
	// reasons.\n Error code: " + gdir.getStatus().code);

	else if (code == G_GEO_BAD_KEY)
		alert("La clef google map est incorrecte. \n Error code: " + code);

	else if (code == G_GEO_BAD_REQUEST)
		alert("Par d itineraire possible.\n Error code: " + code);

	else {
	   if (serverLog) {
		   var errorMsg = '';
		   try {
			   errorMsg = gdir.getStatus().code;
			   errorMsg = 'Requested directions for: ['+gdir.D.name+'], geocode status code: ['+gdir.getStatus().code+']';
		   } catch (err) {
			   errorMsg += ', InternalCode [003]';
		   }
		   serverLog('gdir', 'error', errorMsg);
	   }
		document.getElementById("trajetMap").innerHTML = "<h1>Votre trajet ne peut &ecirc;tre calcul&eacute; car votre d&eacute;part ou votre arriv&eacute;e n'est pas un lieu terrestre ! <br> <a href=\"javascript:history.back();\">Cliquez ici pour corriger votre trajet.</a></h1>";
	}
	document.adressesCorrectionConfirmForm.pointsPassage.value = "";
	pointsPassage = [];
	document.adressesCorrectionConfirmForm.itineraireLineString.value = "";
}

function handleErrors() {
	handleErrorCode(gdir.getStatus().code);
}

function handleErrorsMark() {
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("Cette adresse n est pas reconnue.\nCode erreur: "
				+ gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		alert("Itineraire impossible a determiner.\n Error code: "
				+ gdir.getStatus().code);

	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		alert("Pour tracer un itineraire, il faut un point de depart et d arrivee.\n Error code: "
				+ gdir.getStatus().code);

	// else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS) <--- Doc bug...
	// this is either not defined, or Doc is wrong
	// alert("The geocode for the given address or the route for the given
	// directions query cannot be returned due to legal or contractual
	// reasons.\n Error code: " + gdir.getStatus().code);

	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		alert("La clef google map est incorrecte. \n Error code: "
				+ gdir.getStatus().code);

	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("Par d itineraire possible.\n Error code: "
				+ gdir.getStatus().code);

	else {
	   if (serverLog) {
		   var errorMsg = gdir.getStatus().code;
		   try {
			   errorMsg = 'Requested directions for: ['+gdir.D.name+'], geocode status code: ['+gdir.getStatus().code+']';
		   } catch (err) {
			   errorMsg += ', InternalCode [004]';
		   }
		   serverLog('gdir', 'error', errorMsg);
	   }
		document.getElementById("trajetMap").innerHTML = "<h1>Votre trajet ne peut &ecirc;tre calcul&eacute; car un de vos lieux de passage n'est pas un lieu terrestre ! <br> <a href=\"javascript:reinitTrajetMap();\">Cliquez ici pour corriger.</a></h1>";
	}
	document.adressesCorrectionConfirmForm.pointsPassage.value = "";
	pointsPassage = [];
	document.adressesCorrectionConfirmForm.itineraireLineString.value = "";
}

// Cette méthode est simplement copié du onGDirectionsLoad pour éviter probleme
// de regression
// les gdir et allsteps ont été remplacé par l'objet fullPolyline qui concatène
// le tout
var firstTime = true;
function onGDirectionsLoadFromPolyline(fullPolyline) {
	var itineraire = [];

	var nbreptsmax = Math.round((Math
			.round(fullPolyline.getDistance().meters / 1000)) / 40) + 5;
	if (nbreptsmax > 21)
		nbreptsmax = 21;
	var nmpoint = fullPolyline.getVertexCount();
	var modulodist = Math.round(nmpoint / nbreptsmax);

	for (i = 0; i < nbreptsmax - 1; i++) {
		itineraire[i] = fullPolyline.getVertex(Math.abs((i) * modulodist));
	}

	var concatiti = "";
	for ( var i = 0; i < itineraire.length; i++) {
		var pts = itineraire[i];
		concatiti = concatiti + pts.lat() + "," + pts.lng() + ";";
	}
	concatiti = concatiti + fullPolyline.getVertex(nmpoint - 1).lat() + ","
			+ fullPolyline.getVertex(nmpoint - 1).lng() + ",";
	document.adressesCorrectionConfirmForm.itineraireLineString.value = concatiti;
	document.adressesCorrectionConfirmForm.distanceTotale.value = parseInt(fullPolyline
			.getDistance().meters);
	document.adressesCorrectionConfirmForm.tempsTrajet.value = parseInt(fullPolyline
			.getDuration().seconds);

	if (firstTime) {
		p = lrvCartographie.gdir.getPolyline();
		c = p.getVertexCount();
		i = Math.round(c / 2);
		middle = p.getVertex(i);
		lrvCartographie.map
				.openInfoWindowHtml(
						middle,
						"<p style=\"margin:10px 0;width:230px;font-size:12px\">Cliquez sur l'itinéraire et faites le glisser pour ajouter un point de passage</p>");
		firstTime = false;
	} else {
		lrvCartographie.map.closeInfoWindow();
	}
}

function onGDirectionsLoad() {
	var itineraire = [];

	var allsteps = gdir.getPolyline();
	var nbreptsmax = Math
			.round((Math.round(gdir.getDistance().meters / 1000)) / 40) + 5;
	if (nbreptsmax > 21)
		nbreptsmax = 21;
	var nmpoint = allsteps.getVertexCount();
	var modulodist = Math.round(nmpoint / nbreptsmax);

	for (i = 0; i < nbreptsmax - 1; i++) {
		itineraire[i] = allsteps.getVertex(Math.abs((i) * modulodist));
	}

	var concatiti = "";
	for ( var i = 0; i < itineraire.length; i++) {
		var pts = itineraire[i];
		concatiti = concatiti + pts.lat() + "," + pts.lng() + ";";
	}
	concatiti = concatiti + allsteps.getVertex(nmpoint - 1).lat() + ","
			+ allsteps.getVertex(nmpoint - 1).lng() + ",";
	document.adressesCorrectionConfirmForm.itineraireLineString.value = concatiti;
	document.adressesCorrectionConfirmForm.distanceTotale.value = gdir
			.getDistance().meters;
	document.adressesCorrectionConfirmForm.tempsTrajet.value = gdir
			.getDuration().seconds;
}

function addPopup(map) {
	function popup() {
	}
	popup.prototype = new GControl();

	popup.prototype.initialize = function(map) {
		var popupcontainer = document.createElement("div");
		popupcontainer.setAttribute('id', 'container');
		var popupcontent = document.createElement("div");
		popupcontent.setAttribute('id', 'popup');
		this.setStyle_(popupcontent);
		popupcontainer.appendChild(popupcontent);
		popupcontent.innerHTML = "<p style=\"text-align:center;margin-right:0px;\"><strong>Mode d'emploi de la carte</strong></p><p style=\"margin-right:0px;color:red;font-weight:bold;\">Votre itin&eacute;raire par d&eacute;faut est affich&eacute;. S'il est correct, cliquez sur <strong>\"Je valide mon itin&eacute;raire\"</strong>. <br>Si vous souhaitez le modifier, cliquez sur l'endroit ou vous souhaitez passer, puis validez.</p><div id='fermaide'><p style=\"text-align:center;margin-right:0px;\"><u><b>Cliquez ici pour fermer ce mode d'emploi</b></u></p></div>";

		listener1 = GEvent.addDomListener(popupcontent, "click", function(
				point, map) {
			popupcontent.style.visibility = "hidden";
			document.getElementById('popup').setAttribute('style',
					'display:none;');
		});

		map.getContainer().appendChild(popupcontainer);
		return popupcontainer;
	}

	popup.prototype.getDefaultPosition = function() {
		return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(85, 50));
	}

	popup.prototype.setStyle_ = function(button) {
		button.style.textAlign = "center";
		button.style.backgroundColor = "white";
		button.style.padding = "8px";
		button.style.border = "2px solid green";
		button.style.cursor = "pointer";
		button.style.width = "300px";
		button.style.filter = "alpha(opacity=90)";
	}

	map.addControl(new popup());
	document
			.getElementById('popup')
			.setAttribute(
					'style',
					'color:black;text-align:center;border:2px solid green;padding:8px 8px 8px 8px;cursor:pointer;heigth:280px;width:300px;background-color:white;filter:alpha(opacity=90);-moz-opacity:0.90;opacity: 0.90;');
}
