/**
* Page		: carteOL.js
* Contenu	: Code javascript pour l'interface OL de la carte
* Date		: 23/12/09
* @author	Gael Sauvanet
* @version	1.0
*/
var map;					// Objet map

var controlDrag = null;				// Contrôleur de l'évenement drag
var controlMousePosition = null;

var layerMarkers;				// Couche contenant les marqueurs
var layerPOIs;					// Couche contenant les marqueurs
var layerCyclemap;				// Couche OpenCycleMap
var layerOSM;					// Couche OSM
var layerCloudmade;				// Couche CloudMade Géovélo
var layerMapquest;				// Couche Mapquest
var layerGoogleSat;				// Couche Google Maps Satellite
var layerGoogleAlti;				// Couche Google Maps Alti
var layerCyclabilite;				// Couche des notes de cyclabilité
var layerCyclabiliteComm;			// Couche des notes de cyclabilité communautaire
var layerCyclabiliteUtilisateur;		// Couche des notes de cyclabilité utilisateur

var dynamic;					// Pour savoir si la carte est dynamique (zoom et autre)
var path_static;				// Numéro d'itinéraire pour le passage index -> feuille de route

var chargement=0;				// numéro d'itinéraire choisi quand on utilise un chargement d'itinéraire par la BDD. Egal à 0 sinon

var lastFeature = null;				// Gestion tooltip : dernier objet sélectionné
var tooltipPopup = null;			// Gestion tooltip : popup

var bounds_itineraire;				// bounds de l'itinéraire
var bounds_zone;				// bounds de la zone

var perso;					// Mode personnalisée
var criteres_perso;				// Réglage personnalisé des critères

/**
 * Initialise et prépare la carte OL
 */
function initialize(lat1,lon1,lat2,lon2,latc,lonc,z,i,dynamic_map,coordEtapes,var_perso) {
	// Création de l'objet carte
	map = new OpenLayers.Map("map",
	{ 
		maxExtent: new OpenLayers.Bounds(-20037508,-20037508,20037508,20037508),
		numZoomLevels: 19,
		maxResolution: 156543.0339,
		units: 'm',
		projection: new OpenLayers.Projection("EPSG:900913"),
		displayProjection:  new OpenLayers.Projection("EPSG:4326"),
		controls: [
			new OpenLayers.Control.LayerSwitcher({roundedCorner: true, roundedCornerColor: '#696969'}),
			new OpenLayers.Control.ScaleLine({geodesic: true}),
			new OpenLayers.Control.PanZoomBar()
		]
	});

	// Gestion des boutons d'échelle
	map.events.register( "zoomend", map, function(){
		var niveaux =  [9,12,15,18];
		for(var numZL in niveaux)
		{
			// ici, on met à jour les images, version grise ou colorée
			if(niveaux[numZL] != map.getZoom())
				$j("#boutonZoom"+niveaux[numZL]+" a img").attr("src","res/lib/OL/img/zoom-label-"+niveaux[numZL]+".png");
			else
				$j("#boutonZoom"+niveaux[numZL]+" a img").attr("src","res/lib/OL/img/zoom-label-"+niveaux[numZL]+"-colore.png");
		}
	});
	
	// Zoom Extent = zoom sur l'itinéraire
	map.zoomToMaxExtent = function() {
		return map.zoomToExtent(bounds_zone);
	};

	// Restreindre le niveau de zoom
	map.setCenter = function(lonlat, zoom, dragging, forceZoomChange) {
		if(((zoom >= MIN_ZOOM) && (zoom <= MAX_ZOOM))||(zoom == null))
		{
			this.moveTo(lonlat, zoom, {
			    'dragging': dragging,
			    'forceZoomChange': forceZoomChange,
			    'caller': 'setCenter'
			});
		}
	    };

	dynamic = dynamic_map;
	if(var_perso == true) perso = true;
	else perso = false;

	criteres_perso = [1,1,1,1];

	if (i!=0) chargement=i; // Si on a charger i(la solution choisie) par la BDD, on le met dans chargement
	path_static = i;

	if(dynamic)
	{
		// On adapte la carte à la taille de la fenêtre 
		resizeApp();
	}
	
	
	//*********************************** Définition du Gestinnaire des couches POIs ****************************************
	gestionnaireCouchesPOI = {
		couches: new Array(),// tableau des couches supportées
		fonctionAffichage: new Array(), // le contenu du Popup en fonction des types contenus dans l'attribut ensemplesTypes
			//Creation de la couche
		ajouterCouche : function(couche,fct)
		{
			this.couches.push(couche);
			this.fonctionAffichage.push(fct);
		},		
		//Ajout de gestionnaire d'evenements aux couches
		initGestionnaireEvt:function(){
			this.selectcontrol = new OpenLayers.Control.SelectFeature(this.couches, {
				onSelect : this.selectPOI,
				onUnselect : this.unselect});
			map.addControl(this.selectcontrol);
			this.selectcontrol.activate();
		},
		//affichage du Popup après un evenement select
		selectPOI : function(feature){
			// on cherche à obtenir le contenu de la popup
			var contenu = "";
			for(var i = 0; i < gestionnaireCouchesPOI.fonctionAffichage.length && contenu == ""; i++)
			{
				var fct = gestionnaireCouchesPOI.fonctionAffichage[i];
				contenu = fct(feature);
			}
			
			tooltipPopup = new OpenLayers.Popup.FramedCloud("activetooltip",
				feature.geometry.getBounds().getCenterLonLat(),
				new OpenLayers.Size(200,10),contenu,icon2,true,function() {
						gestionnaireCouchesPOI.unselect(feature);
						gestionnaireCouchesPOI.selectcontrol.unselect(feature);
//						this.selectcontrol.unselect(feature);
					});
			tooltipPopup.contentDiv.style.backgroundColor='#ffffff';
			tooltipPopup.contentDiv.style.overflow='hidden';
			tooltipPopup.contentDiv.style.padding='3px';
			tooltipPopup.contentDiv.style.width='200px';
			tooltipPopup.contentDiv.style.margin='0';
			tooltipPopup.panMapIfOutOfView = false;
			feature.popup = tooltipPopup;
			map.addPopup(tooltipPopup);
		},
		
		unselect:function(e)
		{
			if(tooltipPopup != null)
			{
				map.removePopup(tooltipPopup);
				delete tooltipPopup;
				tooltipPopup = null;
			}
		},
		activer:function(){
			this.selectcontrol.activate();
		},
		desactiver:function(){
			this.selectcontrol.deactivate();
		}
		
	}
	//***********************************Fin définition du Gestinnaire des couches POIs****************************************

	// Initialisation de l'outil de géocodage
	initialiserGeocoder();

	layerCloudmade = new OpenLayers.Layer.OSM("CloudMade Géovélo",
                 ["http://a.tile.cloudmade.com/e2555e93f9985265ba6af342920a8741/13838/256/",
                  "http://b.tile.cloudmade.com/e2555e93f9985265ba6af342920a8741/13838/256/",
		  "http://c.tile.cloudmade.com/e2555e93f9985265ba6af342920a8741/13838/256/"],
                 { type: 'png', getURL: getTileURL, displayOutsideMaxExtent: true, transitionEffect: 'resize'});
	map.addLayer(layerCloudmade);

	layerMapquest = new OpenLayers.Layer.OSM("Mapquest",
                 ["http://otile1.mqcdn.com/tiles/1.0.0/osm/",
		  "http://otile2.mqcdn.com/tiles/1.0.0/osm/",
		  "http://otile3.mqcdn.com/tiles/1.0.0/osm/",
		  "http://otile4.mqcdn.com/tiles/1.0.0/osm/"],
                 { type: 'png', getURL: getTileURL, displayOutsideMaxExtent: true, transitionEffect: 'resize'});
	map.addLayer(layerMapquest);

	layerGoogleSat = new OpenLayers.Layer.Google(
		"Google Satellite",
		{type: google.maps.MapTypeId.SATELLITE}
	);
	map.addLayer(layerGoogleSat);

	if(ZONE_QUALIFIEE){
		layerCyclabilite = new OpenLayers.Layer.OSM("Qualité des voies",
			 ["http://tiles.geovelo.fr/cyclabilite/"],
			 { type: 'png', getURL: getTileURL,  transitionEffect: 'resize',isBaseLayer: false, visibility: false, opacity:0.6});
		map.addLayer(layerCyclabilite);
	}

	if(ZONE_MODE_NOTATION){
		layerCyclabiliteComm = new OpenLayers.Layer.OSM("Qualité des voies - notes communautaires",
				 ["http://tiles.geovelo.fr/notes_communaute/"],
				 { type: 'png', getURL: getTileURL,  transitionEffect: 'resize',isBaseLayer: false, visibility: false, opacity:0.6});
		map.addLayer(layerCyclabiliteComm);
		

		layerCyclabiliteUtilisateur = new OpenLayers.Layer.Vector("Qualité des voies - mes notes", {
		projection: new OpenLayers.Projection("EPSG:4326"),
		strategies: [
			new OpenLayers.Strategy.BBOX({resFactor: 1})
		],
		protocol: new OpenLayers.Protocol.HTTP({
			url: "get_cyclabilite_utilisateur.php", 
			format: new OpenLayers.Format.KML({
				extractStyles: true,
				extractAttributes: true 
			})
		})
		});
		map.addLayer(layerCyclabiliteUtilisateur);
		layerCyclabiliteUtilisateur.setOpacity(0.6);
		layerCyclabiliteUtilisateur.setVisibility(false);
	}
		
	layerCouverture = new OpenLayers.Layer.Vector("Couverture");
	layerCouverture.visibility = false;
	map.addLayer(layerCouverture);
	
	
	function onLoadCouverture(r)
	{
		if (r.status == 200)
		{
			var reader = new OpenLayers.Format.KML();
			data = reader.read(r.responseText);
	                
			for (var i=0; i<data.length; i++)
			{
				// On récupère les informations du tronçon
				data[i].geometry.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));

				if(data[i].attributes.type == "couverture")
					couverture = new OpenLayers.Feature.Vector(data[i].geometry,null,polygonCouverture);
				else
					couverture = new OpenLayers.Feature.Vector(data[i].geometry,null,polygonCouverture2);
				layerCouverture.addFeatures(couverture);
			}
		}
	}
	function onLoadFailedCouverture(r){}
	OpenLayers.loadURL(URL_BASE_SITEWEB+DOSSIER_SITEWEB+"kml/"+ZONE+".couverture.kml", {}, null, onLoadCouverture, onLoadFailedCouverture);

	// Couche par défaut
	map.setBaseLayer(layerCloudmade);

	// Création de la couche des POIs
	layerPOIs = new OpenLayers.Layer.Vector("POIs");
	layerPOIs.displayInLayerSwitcher = false;
	map.addLayer(layerPOIs);

	// Création de la couche contenant les marqueurs de départ & arrivée
	layerMarkers = new OpenLayers.Layer.Vector("Markers");
	layerMarkers.displayInLayerSwitcher = false;
	map.addLayer(layerMarkers);
	
	gestionnaireCouchesPOI.ajouterCouche(layerMarkers,function(element){return ""});
	
	//*****************************************************************
	
	//var ensembleCouches = [layerMarkers];
	if(ZONE_MODE_EVENEMENTS)
	{
		// Layer contenant les POIs
		layerPOIs = new OpenLayers.Layer.Vector("Evènements", {
		projection: new OpenLayers.Projection("EPSG:4326"),
		strategies: [
			new OpenLayers.Strategy.BBOX({resFactor: 1})
		],
		protocol: new OpenLayers.Protocol.HTTP({
			url: "get_evenements.php", 
			format: new OpenLayers.Format.KML({
			        extractAttributes: true
			})
		}),
		styleMap: new OpenLayers.StyleMap({
			"default": iconEvenement
		})
		});
		map.addLayer(layerPOIs);
		layerPOIs.setVisibility(false);
		
		/***********************Ajout du contrôleur d'évenements layerPOIs**********/
		gestionnaireCouchesPOI.ajouterCouche(layerPOIs,function(element){
			var point = MToLonLat(LonLatToPoint(element.geometry.getBounds().getCenterLonLat()));
			
			if(element.attributes.date_debut != undefined && element.attributes.date_debut != "")
			{
				
				var titre = "";
				if(!element.attributes.lien)
				{
					titre = element.attributes.titre;
				}
				else
				{
					titre = '<a href="'+element.attributes.lien+'">'+element.attributes.titre+'</a>';
				}
				
				var date = "";
				if(element.attributes.date_debut == element.attributes.date_fin)
				{
					date = "Le " + element.attributes.date_debut;
				}
				else
				{
					date = "Du " + element.attributes.date_debut+" au " + element.attributes.date_fin;
				}
				
				return "<img src=\"res/img/evenement.png\" /><b>"+titre+"</b><br>" +
					"<i>"+feature.attributes.description+"</i><br>"+
					date+"<br>"+
					"<br/>" + "<div class=\"actionpopup\" onclick=\"gestionnaireCouchesPOI.unselect();xajax_selectionnerNoeud("+point.x+","+point.y+",'depart'); return false;\"><img src=\"res/img/picto_depart2.png\" /> Définir comme point de départ</div>" +
					"" + "<div class=\"actionpopup\"onclick=\"gestionnaireCouchesPOI.unselect();xajax_selectionnerNoeud("+point.x+","+point.y+",'arrivee'); return false;\"><img src=\"res/img/picto_arrivee2.png\" /> Définir comme point d'arrivée</div>";
			}
			else
			{
				return "";
			}
		});
		/***********************************************************************/
	}
	
	if(ZONE_MODE_CIRCUITS)
	{
		layerCircuits = new OpenLayers.Layer.Vector("POI Circuits");
		layerCircuits.setVisibility(true);
		layerCircuits.displayInLayerSwitcher = false;
		map.addLayer(layerCircuits);
		gestionnaireCouchesPOI.ajouterCouche(layerCircuits,function(element) {
			if(element.attributes.type != undefined && element.attributes.type == "circuit")
			{
				return "<b> " + element.attributes.nom+ "</b><br>" +
				"<input type=\"button\" onclick=\"javascript:gestionnaireCouchesPOI.unselect();afficherCircuit("+element.attributes.id+")\" value=\"Visualiser\">";
			}
			else
			{
				return "";
			}
		});
	}
	
	if(ZONE_VLS)
	{
		// Limitation des niveaux de zoom de la carte
		var MIN_ZOOM_POI = 0.01;
		var MAX_ZOOM_POI = 6.0;

		// Layer contenant les POIs
		layerVLS = new OpenLayers.Layer.Vector(VLS_RESEAU, {
		projection: new OpenLayers.Projection("EPSG:4326"),
		strategies: [
			new OpenLayers.Strategy.BBOX({resFactor: 1})
		],
		protocol: new OpenLayers.Protocol.HTTP({
			url: "get_vls.php", 
			format: new OpenLayers.Format.KML({
				extractStyles: true,
				extractAttributes: true 
			})
		}),
		maxResolution: MAX_ZOOM_POI, minResolution: MIN_ZOOM_POI
		});
		map.addLayer(layerVLS);
		layerVLS.setVisibility(true);
		
		/***********************Ajout controleur d'evenement layerVLS**********/
		gestionnaireCouchesPOI.ajouterCouche(layerVLS,function(element){
			if(element.attributes.type == "vls")
			{
				
				// Gestion des VLS et parkings
				var nom = element.attributes.nom;
				var point = MToLonLat(LonLatToPoint(element.geometry.getBounds().getCenterLonLat()));
				return "<img src=\"res/img/POIBalade"+element.attributes.num+".png\" /><b> "+nom+"</b>"+
					"<br/>" + "<div class=\"actionpopup\" onclick=\"gestionnaireCouchesPOI.unselect();xajax_selectionnerNoeud("+point.x+","+point.y+",'depart'); return false;\"><img src=\"res/img/picto_depart2.png\" /> Définir comme point de départ</div>" +
					"" + "<div class=\"actionpopup\"onclick=\"gestionnaireCouchesPOI.unselect();xajax_selectionnerNoeud("+point.x+","+point.y+",'arrivee'); return false;\"><img src=\"res/img/picto_arrivee2.png\" /> Définir comme point d'arrivée</div>";
			}
			else
			{
				return "";
			}
		});
		/***********************************************************************/
	}
	
	
	if(ZONE_POI)
	{
		// Layer contenant les POIs
		layerPOI = new OpenLayers.Layer.Vector("Points d'intérêt", {
		projection: new OpenLayers.Projection("EPSG:4326"),
		strategies: [
			new OpenLayers.Strategy.BBOX({resFactor: 1})
		],
		protocol: new OpenLayers.Protocol.HTTP({
			url: "get_poi.php", 
			format: new OpenLayers.Format.KML({
				extractStyles: true,
				extractAttributes: true 
			})
		})
		});
		
		map.addLayer(layerPOI);
		layerPOI.setVisibility(false);
		
		/***********************Ajout controleur d'evenement layerVLS**********/
		gestionnaireCouchesPOI.ajouterCouche(layerPOI,function(element){
			if(element.attributes.poi != undefined && element.attributes.poi == "1")
			{
				// Gestion des VLS et parkings
				var description = "";
				if(element.attributes.description != undefined)description = element.attributes.description+"<br>";
				var nom = element.attributes.nom;
				var point = MToLonLat(LonLatToPoint(element.geometry.getBounds().getCenterLonLat()));
				var lien = "";
				if(mode_colonne_droite != 6)
				{
					lien = "<br/>" + "<div class=\"actionpopup\" onclick=\"gestionnaireCouchesPOI.unselect();xajax_selectionnerNoeud("+point.x+","+point.y+",'depart'); return false;\"><img src=\"res/img/picto_depart2.png\" /> Définir comme point de départ</div>" +
					"" + "<div class=\"actionpopup\"onclick=\"gestionnaireCouchesPOI.unselect();xajax_selectionnerNoeud("+point.x+","+point.y+",'arrivee'); return false;\"><img src=\"res/img/picto_arrivee2.png\" /> Définir comme point d'arrivée</div>";
				}
				else
				{
					lien = "<div class=\"actionpopup\" onclick=\"gestionnaireCouchesPOI.unselect();ajouterEtapeCoord("+point.x+","+point.y+");return false;\"><img src=\"res/img/picto_etape.png\" /> Ajouter ce point d'intérêt</div>"
				}
				return "<img src=\"res/img/POI/"+element.attributes.type+".png\" width=\"15\" height=\"15\"/><b> "+element.attributes.nom+"</b><br>"+
					description +
					"<br/>" + lien;
			}
			else
			{
				return "";
			}
		});
		/***********************************************************************/
	}
	
	
	if(ZONE_MODE_BALADE)
	{
		// Création de la couche contenant le tracé (itinéraire) de la balade
		layerBaladeTrace = new OpenLayers.Layer.Vector("Tracé de la balade");
		layerBaladeTrace.setOpacity(0.7);
		layerBaladeTrace.displayInLayerSwitcher = false;
		map.addLayer(layerBaladeTrace);


		// Layer contenant les POIs des balades
		layerPOIsBalades = new OpenLayers.Layer.Vector("POIs Balades");
		layerPOIsBalades.displayInLayerSwitcher = false;
		map.addLayer(layerPOIsBalades);

		gestionnaireCouchesPOI.ajouterCouche(layerPOIsBalades, function(element) {
				if(element.attributes.type != undefined && element.attributes.type == "poi")
				{
					return "<b> " + element.attributes.nom+ "</b><br>" +
					element.attributes.description+"<br>"+
					((element.attributes.image && element.attributes.image != 'undefined')?
							'<a href="javascript:afficherLightbox(\''+element.attributes.image+'\')" ><img src="'+element.attributes.image+'" class="img_poi_balade"><a>'
							:"");;
				}
				else
				{
					return "";
				}
		});
		
		// affichage des balades par point de départ
		layerListeBalades = new OpenLayers.Layer.Vector("Liste des balades");
		layerListeBalades.displayInLayerSwitcher = false;
		map.addLayer(layerListeBalades);

		gestionnaireCouchesPOI.ajouterCouche(layerListeBalades, function(element) {
				if(element.attributes.type != undefined && element.attributes.type == "balade")
				{
					return "<b> " + element.attributes.nom+ "</b> par "+element.attributes.auteur+"<br>" +
					"<input type=\"button\" onclick=\"javascript:gestionnaireCouchesPOI.unselect();afficherInfosBalade("+element.attributes.id+")\" value=\"Visualiser\">";
				}
				else
				{
					return "";
				}
		});
	}
	
	if(ZONE_TRAVAUX)
	{
		layerTram = new OpenLayers.Layer.Vector("Travaux du Tram");
		layerTram.setVisibility(false);
		layerTram.displayInLayerSwitcher = false;
		map.addLayer(layerTram);
		OpenLayers.loadURL(URL_BASE_SITEWEB+DOSSIER_SITEWEB+'get_tram_infos.php', {}, null, onLoadTram, onLoadFailedTram);
		gestionnaireCouchesPOI.ajouterCouche(layerTram, stationSelectTram);
	}	
	
	marqueurPoint = {
		layerPoint : "",
		initialiser: function(){
			if(this.layerPoint != ""){this.supprimer();map.removeLayer(this.layerPoint);map.addLayer(this.layerPoint);return;}
			this.layerPoint = new OpenLayers.Layer.Vector("point bleu");
			this.layerPoint.setVisibility(false);
			this.layerPoint.displayInLayerSwitcher = false;
			map.addLayer(this.layerPoint);
		},
		positionner: function(lon,lat){
			this.supprimer();
			var iconePointBleu = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
			if($j.browser.msie && $j.browser.version.substring($j.browser.version.indexOf("."))*1 < 9)// si IE < 9
			{
				iconePointBleu.externalGraphic = URL_BASE_SITEWEB+DOSSIER_SITEWEB+"res/lib/OL/img/point.gif";
				iconePointBleu.graphicWidth = 16;
			}
			else
			{
				iconePointBleu.externalGraphic = URL_BASE_SITEWEB+DOSSIER_SITEWEB+"res/lib/OL/img/point.png";
				iconePointBleu.graphicWidth = 66;
			}
			iconePointBleu.graphicHeight = iconePointBleu.graphicWidth;
			iconePointBleu.graphicXOffset = -iconePointBleu.graphicWidth/2; 
			iconePointBleu.graphicYOffset = -iconePointBleu.graphicWidth/2;
			iconePointBleu.graphicOpacity = 0.9;
			var markerPointBleu = new OpenLayers.Feature.Vector(LonLatToPoint(LonLatToM(new OpenLayers.LonLat(lon,lat))),null, iconePointBleu);
			this.layerPoint.addFeatures(markerPointBleu);
			this.montrer();
		},
		supprimer: function(){this.layerPoint.removeAllFeatures();},
		cacher: function(){this.layerPoint.setVisibility(false)},
		montrer: function(){this.layerPoint.setVisibility(true)}
	};

	// Création et positionnement des marqueurs
	if(lat1 == 0)
	{
		defItineraire.lat1 = MARKER1_LAT;
		defItineraire.lon1 = MARKER1_LON;
		defItineraire.lat2 = MARKER2_LAT;
		defItineraire.lon2 = MARKER2_LON;
	}
	else
	{
		defItineraire.lat1 = lat1;
		defItineraire.lon1 = lon1;
		defItineraire.lat2 = lat2;
		defItineraire.lon2 = lon2;
	}
	markerDepart = new OpenLayers.Feature.Vector(LonLatToPoint(LonLatToM(new OpenLayers.LonLat(defItineraire.lon1,defItineraire.lat1))),null,iconDepart);
	markerArrivee = new OpenLayers.Feature.Vector(LonLatToPoint(LonLatToM(new OpenLayers.LonLat(defItineraire.lon2,defItineraire.lat2))),null,iconArrivee);
	markerDepart.attributes.nom = 'depart';
	markerArrivee.attributes.nom = 'arrivee';
	layerMarkers.addFeatures(markerDepart);
	layerMarkers.addFeatures(markerArrivee);
	layerMarkers.drawFeature(markerDepart);
	layerMarkers.drawFeature(markerArrivee);

	// Positionner la carte
	bounds_zone = new OpenLayers.Bounds();
	bounds_zone.extend(LonLatToM(new OpenLayers.LonLat(MIN_LON,MIN_LAT)));
	bounds_zone.extend(LonLatToM(new OpenLayers.LonLat(MAX_LON,MAX_LAT)));

	bounds_itineraire = new OpenLayers.Bounds();
	lonmin=defItineraire.lon1;latmin=defItineraire.lat1;lonmax=defItineraire.lon1;latmax=defItineraire.lat1;
	if (defItineraire.lon2<lonmin) lonmin=defItineraire.lon2;
	if (defItineraire.lon2>lonmax) lonmax=defItineraire.lon2;
	if (defItineraire.lat2<latmin) latmin=defItineraire.lat2;
	if (defItineraire.lat2>latmax) latmax=defItineraire.lat2;

	if (coordEtapes!=null)
		for (var i=0; i<coordEtapes.length; i++)
		{
			if (coordEtapes[i][1]<lonmin) lonmin=coordEtapes[i][1];
			if (coordEtapes[i][1]>lonmax) lonmax=coordEtapes[i][1];
			if (coordEtapes[i][0]<latmin) latmin=coordEtapes[i][0];
			if (coordEtapes[i][0]>latmax) latmax=coordEtapes[i][0];
		}

	bounds_itineraire.extend(LonLatToM(new OpenLayers.LonLat(lonmin,latmin)));
	bounds_itineraire.extend(LonLatToM(new OpenLayers.LonLat(lonmax,latmax)));
	boundsarray = bounds_itineraire.toArray();
	boundsarray[0] = boundsarray[0] - 100;
	boundsarray[1] = boundsarray[1] - 100;
	boundsarray[2] = boundsarray[2] + 100;
	boundsarray[3] = boundsarray[3] + 100;
	bounds_itineraire = new OpenLayers.Bounds.fromArray(boundsarray);
	map.zoomToExtent(bounds_itineraire);

	// Ajout du contrôle drag sur la couche des marqueurs
	controlDrag = new OpenLayers.Control.DragFeature(layerMarkers, {'onComplete': function(feature) {
		lonlat = new OpenLayers.LonLat(feature.geometry.x,feature.geometry.y);
		ll = MToLonLat(lonlat);
		feature.style.graphicOpacity = 1;

		if (feature.attributes.nom=='depart' || feature.attributes.nom=='arrivee')
			xajax_selectionnerNoeud(ll.lon,ll.lat,feature.attributes.nom);
		else
			xajax_selectionnerNoeud(ll.lon,ll.lat,feature.attributes.nom.substring(0,5),feature.attributes.nom.charAt(5));
		controlDrag.deactivate();
		},
		'onStart': function(feature) {
		feature.style.graphicOpacity = 0.5;
		lonlat_old=new OpenLayers.LonLat(feature.geometry.x,feature.geometry.y);
		ll_old=MToLonLat(lonlat_old);
		}});

	// Ajout du contrôle de position de la souris
	controlMousePosition = new OpenLayers.Control.MousePosition({
		formatOutput: function(lonLat) {
	       		return ''
	   	}});
	controlNavigation = new OpenLayers.Control.Navigation();

	if(dynamic)	// Sur la feuille de route, on interdit de pouvoir déplacer/zommer la carte à la souris
	{
		map.addControl(controlMousePosition);
		map.addControl(controlDrag);
		map.addControl(controlNavigation);
		controlDrag.activate();
		controlMousePosition.activate();
		controlNavigation.activate();
	}

	// Si on a choisi un itinéraire depuis la BDD et qu'il contient des étapes, on les initialise
	setPositionDepart(defItineraire.lat1,defItineraire.lon1,false);
	for(var i = 0; i < coordEtapes.length; i++)
	{
		setPositionEtape(coordEtapes[i][0],coordEtapes[i][1],i+1,false);
	}
	setPositionArrivee(defItineraire.lat2,defItineraire.lon2,true);
	

	if(typeof initialiserZone == 'function') initialiserZone();
	if(dynamic || ZONE_MODE_NOTATION || ZONE_MODE_OSB) initialiserModeNotation();
	
	OpenLayers.Lang.setCode("fr-FR");
	
	//Initialiser le gestionnaire d'evenements
	gestionnaireCouchesPOI.initGestionnaireEvt();
}

/**
 * Affiche et sauvegarde une URL courte pour que l'utilisateur puisse garder son itinéraire calculé
 */
function afficherURL(tache,id)
{
	if (tache=="enregistrer") // On vient de index.php, l'utilisateur à cliquer sur "afficher l'URL"
	{
		// Enregistrement de l'itineraire
		if (defItineraire.ListemarkerEtape!=null)
		{
			// On met dans un tableau la liste des lon,lat des étapes pour pouvoir sauvegarder dans la BDD
			ListeCoordEtape=new Array();
			for (i=1; i<defItineraire.ListemarkerEtape.length; i++)
			{
				ll = new OpenLayers.LonLat(defItineraire.ListemarkerEtape[i].geometry.x,defItineraire.ListemarkerEtape[i].geometry.y);
				ll=MToLonLat(ll);
				ListeCoordEtape[i]=new Array(ll.lat,ll.lon);
			}
		}
		// Sauvegarde de l'itinéraire
		xajax_EnregistrerItineraire(defItineraire.lat1,defItineraire.lon1,defItineraire.lat2,defItineraire.lon2,solution_actuelle,ListeCoordEtape);
	}
	else if (tache=="afficher") // On vient de sauvegarder dans la BDD l'itinéraire, on a maintenant un ID unique à passer à l'utilisateur
	{
		// On construit l'adresse de la page
		var lien = URL_SITE + "index.php" + "?it="+id;
		afficherDialoguePartager(lien,"Mon itinéraire sur Géovélo",0);
	}
}

/**
 * Permet d'afficher/cacher la feuille de route
 */
function switchfeuille()
{
	if(feuille_visible)
	{
		feuille_visible = false;
		$j('#colonne_droite').hide();
		$j('#cacherfeuille1').hide();
		$j('#cacherfeuille2').show();
		if(dynamic)$j('#conteneur').css("margin",'10px 10px 0 255px');
	}
	else
	{
		feuille_visible = true;
		$j('#colonne_droite').show();
		$j('#cacherfeuille1').show();
		$j('#cacherfeuille2').hide();
		if(dynamic)$j('#conteneur').css("margin",'10px 255px 0 255px');
	}
}



