/*
 * @include "/searchfood/web/js/lib/prototype.js" @include
 * "/searchfood/web/js/lib/scriptaculous.js" @include
 * "/searchfood/web/js/lib/builder.js" @include
 * "/searchfood/web/js/lib/controls.js" @include
 * "/searchfood/web/js/lib/effects.js" @include
 * "/searchfood/web/js/lib/sound.js" @include "/searchfood/web/js/lib/slider.js"
 * @include "/searchfood/web/js/lib/dragdrop.js"
 */

/*
 * GOOGLE MAPS RESPONSE OBJECT STRUCTURE
 *  { "name": "1600 Amphitheatre Parkway, Mountain View, CA, USA", "Status": {
 * "code": 200, "request": "geocode" }, "Placemark": [ { "address": "1600
 * Amphitheatre Pkwy, Mountain View, CA 94043, USA", "AddressDetails": {
 * "Country": { "CountryNameCode": "US", "AdministrativeArea": {
 * "AdministrativeAreaName": "CA", "SubAdministrativeArea": {
 * "SubAdministrativeAreaName": "Santa Clara", "Locality": { "LocalityName":
 * "Mountain View", "Thoroughfare": { "ThoroughfareName": "1600 Amphitheatre
 * Pkwy" }, "PostalCode": { "PostalCodeNumber": "94043" } } } } }, "Accuracy": 8 },
 * "Point": { "coordinates": [-122.083739, 37.423021, 0] } } ] }
 * 
 * 
 */
var accessIconSt = "/images/maptools/accesIcon.png";
var restoiconSt = "/images/maptools/restaurant_vert.png";
var clienticonSt = "/images/icon_homme.png";

var accessIcon = new GIcon(G_DEFAULT_ICON, accessIconSt);
accessIcon.iconSize = new GSize(10, 10);
accessIcon.iconAnchor = new GPoint(5, 5);
accessIcon.shadow = "";
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 servicesmap;
var profilmap;
var profilmarker;

var registermap;
var registermarker;
var fournpoint;
var fournpointSt = null;
var geocoder = new GClientGeocoder();
var fournaddress = null;
var livricon = new GIcon(G_DEFAULT_ICON, "/images/livraison_ico.png");
var restoicon = new GIcon(G_DEFAULT_ICON, restoiconSt);
restoicon.iconSize = new GSize(30, 30);
var quartierPoly = null;
var isLoad = false;

function setFournScriptVals(a, lat, lng, lats, lngs) {
	fournaddress = a;
	if (lat != null && lng != null)
		fournpoint = new GLatLng(lat, lng);
	if (lats != null && lngs != null)
		fournpointSt = new GLatLng(lats, lngs);

}

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

}

function loadServiceMap() {
	if (GBrowserIsCompatible()) {
		// var mapOp = new GMapOptions();
		// mapOp.backgroundColor="#aaa";

		servicesmap = new GMap2($("livraison_map"));
		// var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new
		// GSize(10,10));

		/*
		 * map.addControl(new GMenuMapTypeControl(),topRight);
		 * map.addControl(new GLargeMapControl()); map.addControl(new
		 * GOverviewMapControl());
		 */
		servicesmap.addControl(new GSmallZoomControl3D());
		var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5, 5));
		servicesmap.addControl(new GMenuMapTypeControl(), topRight);

		servicesmap.setCenter(fournpoint, 13);
		var resto = new GMarker(fournpoint, restoicon);
		servicesmap.addOverlay(resto);

		// geocoder = new GClientGeocoder();

		// OverLay Controller

		// servicesmap.disableDoubleClickZoom();
		// map.enableScrollWheelZoom();

	}

}

function changeProfilPlace() {
	if ($('pays').value != "" && $('departement').value != ""
			&& $('ville').value != "" && $('cp').value != ""
			&& $('detail').value != "") {
		address = $('detail').value + ", " + $('ville').value + ", "
				+ $('cp').value + ", "
				+ $('pays').options[$('pays').selectedIndex].text;
		geocoder.getLocations(address, showProfilLocation);
	} else {
		$('profil_map').innerHTML = "<div class='importanterr' style='text-align:center;padding:100px 0 0 10px;'>Veuillez completer les informations de votre adresse</div>";
	}
}

function showProfilLocation(response) {
	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.";
	if (response.Placemark != null && response.Placemark.length > 0) {
		place = response.Placemark[0];
		point = new GLatLng(place.Point.coordinates[1],
				place.Point.coordinates[0]);
		if (place.AddressDetails.Accuracy < 6) {
			new Ajax.Request(
					'/registration/getVilleCoords?id=' + $('villeid').value,
					{
						onComplete : function(transport) {
							eval(transport.responseText);
						},
						asynchronous :false
					});
		} else {
			$('lat').value = point.lat();
			$('lng').value = point.lng();

		}
		profilmap = new GMap2($("profil_map"));
		profilmap.addControl(new GSmallZoomControl3D());
		var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5, 5));
		profilmap.addControl(new GMenuMapTypeControl(), topRight);
		profilmap.setCenter(point, 14);
		isLoad = true;
		profilmarker = new GMarker(point, {
			icon :restoicon,
			draggable :true
		});

		GEvent
				.addListener(profilmarker,
						"dragend",
						function(latlng) {
							// ///////////////////////////////////////////////
						addAccesPointOnRegisterMap(profilmap, profilmarker, 10);
						// ///////////////////////////////////////////////
						$('lat').value = latlng.lat();
						$('lng').value = latlng.lng();
						profilmarker
								.bindInfoWindowHtml("<div style='width:150px'>Votre emplacement est enregistré. <br/>Déplacez-moi pour indiquer plus précisément votre emplacement.</div>");
						profilmarker
								.openInfoWindowHtml("<div style='width:150px'>Votre emplacement est enregistré. <br/>Déplacez-moi pour indiquer plus précisément votre emplacement.</div>");

					});
		profilmap.clearOverlays();
		profilmap.addOverlay(profilmarker);
		if (place.AddressDetails.Accuracy < 8) {
			// if (place.AddressDetails.Accuracy > 5) {

			profilmarker
					.bindInfoWindowHtml("<div class='importanterr' style='width:150px'>Votre adresse n'est pas reconnu par notre système. "
							+ infotextnotac + "</div>");
			profilmarker
					.openInfoWindowHtml("<div class='importanterr' style='width:150px'>Votre adresse n'est pas reconnu par notre système. "
							+ infotextnotac + "</div>");
			/*
			 * }else { var idVille = $('villeid').value; new
			 * Ajax.Updater('jscripts','/restaurateur.php/profil/showMarquerOnTown?idville='+
			 * idVille, { evalScripts :true });
			 * 
			 *  }
			 */} else {
			profilmarker.bindInfoWindowHtml(infotext);
			profilmarker.openInfoWindowHtml(infotext);
		}
		// ///////////////////////////////////////////////
		if (isLoad) {
			isLoad = false;
			addAccesPointOnRegisterMap(registermap, registermarker, 10);
		}
		// ///////////////////////////////////////////////

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

}

function loadProfilMap() {

	if (GBrowserIsCompatible()) {
		if ($('s_lat').value == null || $('s_lng').value == null
				|| $('s_lat').value == "" || $('s_lng').value == "")
			fournpointSt = fournpoint;
		else
			fournpointSt = new GLatLng($('s_lat').value, $('s_lng').value);

		profilmap = new GMap2($("profil_map"));
		profilmap.setCenter(fournpoint, 14);
		profilmarker = new GMarker(fournpoint, {
			icon :restoicon,
			draggable :true
		});
		profilmarker.disableDragging();
		accessMarker = new GMarker(fournpointSt, {
			icon :accessIcon,
			draggable :true
		});
		accessMarker.disableDragging();
		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);
						profilmap.removeOverlay(poly);
						$('s_lat').value = p2.lat();
						$('s_lng').value = p2.lng();
						accessMarker.setLatLng(p2);
						showAccesPolylineOnMap(profilmap, profilmarker,
								new GMarker(p2));
					});
		});
		profilmap.addOverlay(accessMarker);
		profilmap.addOverlay(profilmarker);
		showAccesPolylineOnMap(profilmap, profilmarker, accessMarker);

		profilmap.addControl(new GSmallZoomControl3D());
		var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5, 5));
		profilmap.addControl(new GMenuMapTypeControl(), topRight);

	}

}

function editProfilMarker() {
	profilmarker.enableDragging();
	accessMarker.enableDragging();
	GEvent
			.addListener(
					profilmarker,
					"dragend",
					function(latlng) {
						addAccesPointOnRegisterMap(profilmap, profilmarker, 10);
						$('lat').value = latlng.lat();
						$('lng').value = latlng.lng();
						profilmarker
								.bindInfoWindowHtml("<div style='width:150px'>Votre emplacement est enregistré. <br/>Déplacez-moi pour indiquer plus précisément votre emplacement.</div>");
						profilmarker
								.openInfoWindowHtml("<div style='width:150px'>Votre emplacement est enregistré. <br/>Déplacez-moi pour indiquer plus précisément votre emplacement.</div>");

					});
	profilmarker
			.bindInfoWindowHtml("<div style='width:150px'>Vous pouvez me déplacer pour indiquer plus précisément votre emplacement.</div>");
	profilmarker
			.openInfoWindowHtml("<div style='width:150px'>Vous pouvez me déplacer pour indiquer plus précisément votre emplacement.</div>");

}

function loadRegisterMap(changed) {
	if ($('pays').value != "" && $('departement').value != ""
			&& $('ville').value != "" && $('cp').value != ""
			&& $('detail').value != "" && $('cp').value.length==5) {
		if (GBrowserIsCompatible()) {
			isLoad = true;
			registermap = new GMap2($("register_map"));
			address = $('detail').value + ", " + $('ville').value + ", "
					+ $('cp').value + ", FR";
			if (changed == undefined || changed == false || $('lat').value=="" || $('lng').value=="")
				geocoder.getLocations(address, showRegisterLocation);
			else
				restoreRegisterLocation();
			var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,
					10));
			registermap.addControl(new GSmallZoomControl3D(), topLeft);
			var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(
					8, 15));
			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>";
		isLoad = false;
	}

}

function restoreRegisterLocation() {
	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";
	var point = new GLatLng($('lat').value, $('lng').value);
	registermarker = new GMarker(point, {
		icon :restoicon,
		draggable :true
	});
	registermap.setCenter(point, 14);

	GEvent
			.addListener(registermarker,
					"dragend",
					function(latlng) {
					$('s_lat').value="";
					$('s_lng').value="";
						// ///////////////////////////////////////////////
					addAccesPointOnRegisterMap(registermap, registermarker, 10);
					// ///////////////////////////////////////////////
					$('lat').value = latlng.lat();
					$('lng').value = latlng.lng();
					registermarker
							.bindInfoWindowHtml("<div style='width:150px'>Votre emplacement est enregistré. <br/>Déplacez-moi pour indiquer plus précisément votre emplacement.</div>");
					registermarker
							.openInfoWindowHtml("<div style='width:150px'>Votre emplacement est enregistré. <br/>Déplacez-moi pour indiquer plus précisément votre emplacement.</div>");
					/*new Ajax.Updater('jscripts',
							'/restaurateur.php/registration/showQuartier?lat='
									+ latlng.lat() + '&lng=' + latlng.lng()
									+ '&ville=' + $('villeid').value
									+ '&villename=' + $('ville').value + '&cp='
									+ $("cp").value, {
								evalScripts :true
							});*/

				});
	/*new Ajax.Updater(
			'jscripts',
			'/restaurateur.php/registration/showQuartier?lat=' + $('lat').value
					+ '&lng=' + $('lng').value + '&ville=' + $('villeid').value
					+ '&villename=' + $('ville').value + '&cp=' + $("cp").value,
			{
				evalScripts :true
			});*/
	registermap.addOverlay(registermarker);
	addAccesPointOnRegisterMap(registermap, registermarker, 10);

	// //Ajouter l'affichage de l'access Marker (enregistré en base (draggable :
	// false))

	registermarker.bindInfoWindowHtml(infotext);
	registermarker.openInfoWindowHtml(infotext);

}

function showRegisterLocation(response) {
	$('s_lat').value = "";
	$('s_lng').value = "";
	if(registermarker!=null)
		registermap.removeOverlay(registermarker);
	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.";
	if (response.Placemark != null && response.Placemark.length > 0) {
		place = response.Placemark[0];
		point = new GLatLng(place.Point.coordinates[1],
				place.Point.coordinates[0]);

		if (place.AddressDetails.Accuracy < 6) {
			new Ajax.Request(
					'/registration/getVilleCoords?id=' + $('villeid').value
					+ "&ville=" + $('ville').value
					+ "&cp=" + $('cp').value,
					{
						onComplete : function(transport) {
							eval(transport.responseText);
						},
						asynchronous :false
					});
			$('lat').value = "";
			$('lng').value = "";
			
		} else {
			$('lat').value = point.lat();
			$('lng').value = point.lng();
		}
			registermap.setCenter(point, 14);
			registermarker = new GMarker(point, {
				icon :restoicon,
				draggable :true
			});
			GEvent
					.addListener(
							registermarker,
							"dragend",
							function(latlng) {
								$('s_lat').value="";
								$('s_lng').value="";
								// ///////////////////////////////////////////////
								addAccesPointOnRegisterMap(registermap,
										registermarker, 10);
								// ///////////////////////////////////////////////

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

							});
			/*new Ajax.Updater('jscripts',
					'/restaurateur.php/registration/showQuartier?lat='
							+ point.lat() + '&lng=' + point.lng() + '&ville='
							+ $('villeid').value + '&villename='
							+ $('ville').value + '&cp=' + $("cp").value, {
						evalScripts :true
					});*/

			registermap.addOverlay(registermarker);
			if (place.AddressDetails.Accuracy < 8) {

				registermarker
						.bindInfoWindowHtml("<div class='importanterr' style='width:150px'>Votre adresse n'est pas reconnu par notre système. "
								+ infotextnotac + "</div>");
				registermarker
						.openInfoWindowHtml("<div class='importanterr' style='width:150px'>Votre adresse n'est pas reconnu par notre système. "
								+ infotextnotac + "</div>");

			} else {
				registermarker.bindInfoWindowHtml(infotext);
				registermarker.openInfoWindowHtml(infotext);
			}
			if (isLoad) {
				isLoad = false;
				addAccesPointOnRegisterMap(registermap, registermarker, place.AddressDetails.Accuracy);
			}

		
	} else {
		registermap = new GMap2($("register_map"));
		var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10, 10));
		registermap.addControl(new GSmallZoomControl3D(), topLeft);
		var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT,
				new GSize(8, 15));
		registermap.addControl(new GMenuMapTypeControl(), topRight);

		address = $('ville').value + ", FR";
		geocoder.getLocations(address, showRegisterLocation);

	}

}

// //////////////////////////ACCES
// POLYLINE///////////////////////////////////////////////////////
var accessMarker = null;
/*
 * var accessIcon=new GIcon(G_DEFAULT_ICON, "/images/maptools/accesIcon.png");
 * accessIcon.iconSize = new GSize(10, 10); accessIcon.iconAnchor= new
 * GPoint(5,5); accessIcon.shadow ="";
 */
var poly = null;
var accu = null;

function addAccesPointOnRegisterMap(map, marker, precision) {
	if (accessMarker != null) {
		map.removeOverlay(accessMarker);
		map.removeOverlay(poly);
	}
	accu = precision;
	var dirn1 = new GDirections();
	
	if($('s_lat').value=="" || $('s_lng').value==''){
	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);
					$('s_lat').value = p2.lat();
					$('s_lng').value = p2.lng();
					$('lat').value=marker.getLatLng().lat();
					$('lng').value=marker.getLatLng().lng();
					marker
					.bindInfoWindowHtml("<div style='width:150px'>Votre emplacement est enregistré. <br/>Déplacez-moi pour indiquer plus précisément votre emplacement.</div>");
					marker
					.openInfoWindowHtml("<div style='width:150px'>Votre emplacement est enregistré. <br/>Déplacez-moi pour indiquer plus précisément votre emplacement.</div>");
			
			});
		});

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

		if (accu > 7) {
			$('s_lat').value = p.lat();
			$('s_lng').value = p.lng();
		}
		else{
			$('s_lat').value = "";
			$('s_lng').value = "";
		}
		return false;
	});
	}
	else{
		var p = new GLatLng($('s_lat').value,$('s_lng').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);
					$('s_lat').value = p2.lat();
					$('s_lng').value = p2.lng();
					$('lat').value=marker.getLatLng().lat();
					$('lng').value=marker.getLatLng().lng();
					marker
					.bindInfoWindowHtml("<div style='width:150px'>Votre emplacement est enregistré. <br/>Déplacez-moi pour indiquer plus précisément votre emplacement.</div>");
					marker
					.openInfoWindowHtml("<div style='width:150px'>Votre emplacement est enregistré. <br/>Déplacez-moi pour indiquer plus précisément votre emplacement.</div>");
			
			});
		});

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

		if (accu > 7) {
			$('s_lat').value = p.lat();
			$('s_lng').value = p.lng();
		}
		else{
			$('s_lat').value = "";
			$('s_lng').value = "";
		}
		return false;
	}

	return false;

}

function showAccesPolylineOnMap(map, marker, accessM) {
	// affiche le polyline entre le marker et son point d'acces sur la route

	poly = new GPolyline( [ accessM.getLatLng(), marker.getLatLng() ], "blue");
	if (poly.getVertexCount() > 0) {
		map.addOverlay(poly);
	}

	return false;
}
var directions = null;
var clientLocation = null;
var fournLocation = null;

var directionMap = null;
var directionPanel = null;
// ////////////////////////////////////////////////////////////////////////////////////////////////////
// ////////////////////DETAILS COMMANDE ///////////////////
function loadDetailCommandMap() {
	var dirMap = $('dely_address_map');

	fournLocation = fournpoint;
	var fournStLoc = (fournpointSt.lat()).toString().substring(0, 9) + ","
			+ (fournpointSt.lng()).toString().substring(0, 9);
	clientLocation = new GLatLng($('client_lat').value, $('client_lng').value);
	var clientStLoc = ($('client_latr').value).toString().substring(0, 9) + ","
			+ ($('client_lngr').value).toString().substring(0, 9);

	var checkpoint = [ fournStLoc, clientStLoc ];

	directionMap = new GMap2(dirMap);
	directionMap.addControl(new GSmallZoomControl3D());

	directions = new GDirections(directionMap);
	// GEvent.addListener(directions, "error", handleErrors);
	GEvent.addListener(directions, "addoverlay", detailCommandAddOverlay);

	directions.loadFromWaypoints(checkpoint);
	return false
}

function detailCommandAddOverlay() {
	directions.getMarker(0).hide();
	directions.getMarker(1).hide();

	var mark = new GMarker(fournLocation, restoicon);
	mark
			.bindInfoWindowHtml("<div id=\"info_window_content\" class=\"info_window_content\">"
					+ "Vous êtes ici !" + "</div>");
	var accessM = new GMarker(directions.getMarker(0).getLatLng(), accessIcon);
	showAccesPolylineOnMap(directionMap, mark, accessM);
	directionMap.addOverlay(mark);

	mark = new GMarker(clientLocation, clienticon);
	var accessM = new GMarker(directions.getMarker(1).getLatLng(), accessIcon);
	showAccesPolylineOnMap(directionMap, mark, accessM);
	directionMap.addOverlay(mark);

	return false;
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////
// ////////////////////ITINERAIRE DE LIVRAISON POUR LE
// FOURNISSEUR///////////////////

var dirOpts = null;
var nbMarker = null;
var dirMap = null;
function loadDirectionMap() {
	fournLocation = fournpoint;

	dirMap = $('dely_road_map');
	directionPanel = $('dely_road_panel');
	directionMap = new GMap2(dirMap);
	directionMap.addControl(new GSmallZoomControl3D());

	dirOpts = {};
	dirOpts.travelMode = G_TRAVEL_MODE_DRIVING;
	dirOpts.avoidHighways = false;
	// dirOpts.locale=$('language_selected').value;

	directions = new GDirections(directionMap, directionPanel);
	GEvent.addListener(directions, "error", handleErrors);
	GEvent.addListener(directions, "addoverlay", onDirectionDisplay);

	// NOT NECESSARY ANYMORE BECAUSE showDirectionOnMap is called after loading
	// the list with orderedlist parameter
	// GEvent.addListener(directionMap, "load", showDirectionOnMap);

	return false;
}

/**
 * Shows the road on the livraison map.
 * 
 * @param commandsArrayInOrder
 *            array of command ids in order to display (ex: {45, 34, 33}
 */
var commandsArray = new Array();
function showDirectionOnMap(commandsArrayInOrder) {
	// to get the lat lng and road_lat and road_lng :
	// $('lat_'+commandArrayInOrder[i]).value,
	// $('latr_'+commandArrayInOrder[i]).value
	directionMap.clearOverlays();
	var fournStLoc = (fournpointSt.lat()).toString().substring(0, 9) + ","
			+ (fournpointSt.lng()).toString().substring(0, 9);

	commandsArray = commandsArrayInOrder;
	nbMarker = commandsArray.length + 2;
	var bestdir = new Array();
	bestdir[0] = fournStLoc;
	for (i = 0; i < commandsArray.length; i++) {
		bestdir[i + 1] = ($('latr_' + commandsArray[i]).value).toString()
				.substring(0, 9)
				+ ","
				+ ($('lngr_' + commandsArray[i]).value).toString().substring(0,
						9);
	}
	bestdir.push(fournStLoc);
	directions.loadFromWaypoints(bestdir, dirOpts);
	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 onDirectionDisplay() {
	customPaneLivraison(directionMap, "directionMap", directions,
			directionPanel);
	for (i = 0; i < nbMarker; i++) {
		directions.getMarker(i).hide();
		var mark;
		var accessM;
		if (i != nbMarker - 1) {

			if (i == 0) {
				mark = new GMarker(fournLocation, restoicon);
				mark
						.bindInfoWindowHtml("<div id=\"info_window_content\" class=\"info_window_content\">"
								+ "Vous êtes ici !" + "</div>");
			} else {
				mark = new GMarker(new GLatLng(
						$('lat_' + commandsArray[i - 1]).value,
						$('lng_' + commandsArray[i - 1]).value), clienticon);

				mark
						.bindInfoWindowHtml("<div id=\"info_window_content\" class=\"info_window_content\">"
								+ ($('dely_road_comp_com_element_' + commandsArray[i - 1])).innerHTML
								+ "</div>");

			}
			accessM = new GMarker(directions.getMarker(i).getLatLng());
			showAccesPolylineOnMap(directionMap, mark, accessM);
			directionMap.addOverlay(mark);
		}
	}

	return false;
}

// ============ custom direction panel ===============
var html = "";
// === waypoint banner ===
function waypoint(point, type, address, mapname) {
	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" || type == "stop") {
		html += '      <img src="' + restoiconSt + '">'
	} else if (type == "pause") {
		html += '      <img src="' + clienticonSt + '">'
	}

	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 customPaneLivraison(map, mapname, dirn, div) {
	// === 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);
		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);

	// === 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 ===========
