/**
 * @author nlamblin
 */
var map;
var directionsPanel;
var directions;
var geocoder;
var address;
var i= 0;
var nbEtape = 0;
var etape;
var panel;
var direction;
var latlon;
var gdir;
var polyline = null;
var steps = null;
var nbEtapes = 0;

function afficherCarte(id){
	map = new GMap2(document.getElementById(id));
    directions = new GDirections(map, '');
    //map.setCenter(new GLatLng(lat, longi), 15);
//    afficherMarker(lat, longi);
    //map.addControl(new GLargeMapControl);
    geocoder = new GClientGeocoder();
    var customUI = map.getDefaultUI();
    customUI.controls.scalecontrol = false;
    customUI.controls.menumaptypecontrol = false;
    
    map.setUI(customUI);
}


function dessiner_carte_ajout_perso(id, lat, longi){
    map = new GMap2(document.getElementById(id));
    directions = new GDirections(map, '');
    map.setCenter(new GLatLng(lat, longi), 15);
//    afficherMarker(lat, longi);
    //map.addControl(new GLargeMapControl);
    geocoder = new GClientGeocoder();
    var customUI = map.getDefaultUI();
    customUI.controls.scalecontrol = false;
    customUI.controls.menumaptypecontrol = false;
    
    map.setUI(customUI);
    GEvent.addListener(map, "click", function(overlay, latlng){
        if (latlng) {
            var gpoint = latlng;
            afficherMarker(gpoint.y, gpoint.x);
        }
    });
    //map.addControl(new GSmallMapControl());
    //map.addControl(new GMapTypeControl());
}
/*
function dessiner_carte(id, lat, longi){
    map = new GMap2(document.getElementById(id));
    directions = new GDirections(map, '');
    map.setCenter(new GLatLng(lat, longi), 15);
    afficherMarker(lat, longi);
    //map.addControl(new GLargeMapControl);
    geocoder = new GClientGeocoder();
    var customUI = map.getDefaultUI();
    customUI.controls.scalecontrol = false;
    customUI.controls.menumaptypecontrol = false;
    
    map.setUI(customUI);
    GEvent.addListener(map, "click", function(overlay, latlng){
        if (latlng) {
            var gpoint = latlng;
            afficherMarker(gpoint.y, gpoint.x);
        }
    });
    //map.addControl(new GSmallMapControl());
    //map.addControl(new GMapTypeControl());
}
*/
function dessiner_itineraire(id, lat, longi, itineraire){
//	console.log(id);
//	console.log(lat);
//	console.log(longi);
//	console.log(itineraire);
    map = new GMap2(document.getElementById(id));
    map.setCenter(new GLatLng(lat, longi), 15);
    directions = new GDirections(map, '');
    directions.load(itineraire);
    //map.addControl(new GLargeMapControl);
    var customUI = map.getDefaultUI();
    customUI.controls.scalecontrol = false;
    customUI.controls.menumaptypecontrol = false;
    
    map.setUI(customUI);
}

function recupAdresse(reponse){
	var cp = ville = adresse =  "";
	var lat = lon = 0;
	var place = reponse.Placemark[0];
//	console.log(place.AddressDetails);
	if (place.AddressDetails) {
        if (place.AddressDetails.Country.CountryName) 
            pays = place.AddressDetails.Country.CountryName;
        if (place.AddressDetails.Country.AdministrativeArea) {
            if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) {
                if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) {
                    if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality) {
                        if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare) 
                            if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName) 
                                adresse = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
                        if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode) 
                            cp = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
                        if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName) 
                            ville = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
                    }
                }
            }
        }
    }
//	console.log(place.Point);
	var lat = place.Point.coordinates[1];
	var lon = place.Point.coordinates[0];
	return {'ville':ville,'cp':cp,'adresse':adresse,'pays':pays,'lat':lat,'lon':lon};
}

function changementAdresse(mode,point){
	if (mode == 'D') {
		geocoder.getLocations(point, function(response){
			if (response) {
//				console.log(response);
				var newAdresseD = recupAdresse(response);
//				console.log(newAdresseD);
				$j('#Ville_Depart').val(newAdresseD.ville);
				$j('#CP_Depart').val(newAdresseD.cp);
				$j('#Adresse_Depart').val(newAdresseD.adresse);
				$j('#Lat_Depart').val(newAdresseD.lat);
				$j('#Lon_Depart').val(newAdresseD.lon);
			}else{
				alert('Impossible de récupérer les informations liées aux coordonnées GPS. Merci de déplacer plus précisement le marker.');
			}
		});
	}
	if (mode == 'A') {
		geocoder.getLocations(point, function(response){
			if (response) {
//				console.log(response);
				var newAdresseA = recupAdresse(response);
				$j('#Ville_Arrivee').val(newAdresseA.ville);
				$j('#CP_Arrivee').val(newAdresseA.cp);
				$j('#Adresse_Arrivee').val(newAdresseA.adresse);
				$j('#Lat_Arrivee').val(newAdresseA.lat);
				$j('#Lon_Arrivee').val(newAdresseA.lon);
			}else{
				alert('Impossible de récupérer les informations liées aux coordonnées GPS. Merci de déplacer plus précisement le marker.');
			}
		});
	}
}

var newMarkers = [];
var latLngs = [];
var icons = [];
var ArraySteps = [];
var Markers = [];
var trajet = [];
var etapeMarker;
var MarkerDrag;
var origLine = [];
var numMarker = 0;
var numEtape;
var NomAdr;
var orignalTrajet = [];

function dessiner_itineraire_modifiable(id, lat, longi, itineraire)
{
//	console.log(itineraire);
//	console.log(trajet);
	var iti="";
   if(map)
   		map = null;
    map = new GMap2(document.getElementById(id));
    map.setCenter(new GLatLng(lat, longi), 15);
//	if(gdir)
//		gdir = null;
    gdir = new GDirections(map, '');
	if(trajet.length ==0){
		iti='from:';
		iti += itineraire[0] + ' to:' + itineraire[1];
		trajet = itineraire;
	}else{
		var dep = itineraire[0] ;
		var fin = itineraire[1];
		iti = 'from:'+ dep + ' to: ';
		for(var i=1; i< trajet.length-1; i++){
			iti += trajet[i] + ' to: ';
		}
		iti += fin;
		trajet[0]= dep;
		trajet[trajet.length-1] = fin;
	}
//	console.log('Nouveau trajet (adresses):' +iti);
    gdir.load(iti,{getPolyline: true, getSteps:true});
	GEvent.addListener(gdir, "addoverlay", modifTrajet); // Triggers marker swap, Esa

    var customUI = map.getDefaultUI();
    customUI.controls.scalecontrol = false;
    customUI.controls.menumaptypecontrol = false;
    
    map.setUI(customUI);
}

function createMarkerEtape(point,i)
{
	MarkerDrag = false;
	var StepMarker = new GMarker(point, {
        icon: new GIcon({
            iconAnchor: new GPoint(10,10),
			iconSize:new GSize(20,20),
            image: 'http://maps.google.com/mapfiles/kml/pal4/icon57.png'//'http://maps.google.com/mapfiles/ms/micons/ylw-pushpin.png' //
         }),
        draggable: true,
        bouncy: true,
		dragCrossMove:true
    });
	
	GEvent.addListener(StepMarker,'dragend',function(){
//			console.log("pointpositionné");
			var markerLatLng = StepMarker.getLatLng().lat() + ',' + StepMarker.getLatLng().lng();
//			console.log(trajet);
			var last = trajet.pop();
//			console.log(trajet);
			trajet.push(markerLatLng);
			trajet.push(last);
			map.clearOverlays();
//			console.log(markerLatLng);
			geocoder.getLocations(StepMarker.getLatLng(), function (response){
				if(response){
					if(response.Status.code == 602){
						alert("Le système n'a pas pu déterminer les coordonnées GPS de l'adresse.");
					}
					if(response.Status.code == 200){
						var adresse = recupAdresse(response);
//						console.log(adresse);
						var data = [];
						data.push({
							name: 'Adresse_Etape',
							value: adresse['adresse']
						});
						data.push({
							name: 'CP_Etape',
							value: adresse['cp']
						});
						data.push({
							name: 'Ville_Etape',
							value: adresse['ville']
						});
						data.push({
							name: 'ListePays_Ville_Etape',
							value: adresse['pays']
						});
						data.push({
							name: 'Lat_Etape',
							value: adresse['lat']
						});
						data.push({
							name: 'Lon_Etape',
							value: adresse['lon']
						});
						appendEtape(data);
					}
				}
			});
			var newTrajet ="from: " ; 
			for(var i =0; i<trajet.length-1;i++){
				newTrajet += trajet[i] + " to: ";
			}
			newTrajet += trajet[trajet.length-1];
			gdir.clear();
			map.clearOverlays();
			if($j('#itiCarto')){
				$j('#itiCarto').val(newTrajet);
			}
//			console.log('Nouveau trajet (ajout etape):' + newTrajet);
			gdir.load(newTrajet,{getPolyline: true, getSteps: true});
		});
	return StepMarker;
}


function modifTrajet(){
	polyline = null;
	origLine = [];
	polyline = gdir.getPolyline();
//		polyline.enableEditing();
//	GEvent.addListener(polyline,'lineupdated',afficheMarkerEtape);
//	var count_steps = steps.
//	console.log('Nb :' + count_point);

	// sauvegarde des points du trajet
	if (polyline) {
		for (var i = 0; i < polyline.getVertexCount(); i++) {
			origLine.push(polyline.getVertex(i));
		}
	} else{
		polyline = gdir.getPolyline();
		for (var i = 0; i < polyline.getVertexCount(); i++) {
			origLine.push(polyline.getVertex(i));
		}
	}
//	console.log(origLine[0]);
	if (trajet.length == 0) {
		trajet[0] = origLine[0].y + ',' + origLine[0].x;
		trajet[1] = origLine[origLine.length - 1].y + ',' + origLine[origLine.length - 1].x;
	}
	etapeMarker = createMarkerEtape(new GLatLng(origLine[0].y, origLine[0].x), 0);
	map.addOverlay(etapeMarker);
	etapeMarker.hide();
	GEvent.addListener(map, 'mousemove', mouseMove);
	
//	console.log(polyline);
  // Remove the draggable markers from previous function call.
	
	if(newMarkers){
		map.removeOverlay(newMarkers);
		newMarkers = [];
	}
	// Loop through the markers and create draggable copies
	for (var i = 0; i <= gdir.getNumRoutes(); i++) {
		var originalMarker = gdir.getMarker(i);
		latLngs[i] = originalMarker.getLatLng();
		icons[i] = originalMarker.getIcon();
		var markerEtape = new GMarker(latLngs[i], {
			icon: icons[i],
			draggable: true,
			title: 'Point déplaçable N°'+i
		});
		newMarkers[i] = markerEtape;
		
		GEvent.addListener(newMarkers[i],'mouseover',mouseOver);
		
		map.addOverlay(newMarkers[i]);
		// Get the new waypoints from the newMarkers array and call loadFromWaypoints by dragend
		GEvent.addListener(newMarkers[i],"dragstart", function(){
			MarkerDrag = true;
		});
		GEvent.addListener(newMarkers[i], "dragend", function(){

			NomAdr = "Etape["+ numEtape + "]";
			trajet[numEtape+1] = newMarkers[numEtape+1].getLatLng().lat() + ',' + newMarkers[numEtape+1].getLatLng().lng();
			geocoder.getLocations(newMarkers[numEtape+1].getLatLng(), function (response)
			{
				if(response)
				{
					if(response.Status.code == 602)
					{
						alert("Le système n'a pas pu déterminer les coordonnées GPS de l'adresse.");
					}
					if(response.Status.code == 200)
					{
						var adresse = recupAdresse(response);
						$j('input').each(function(i, field){
							if (field.id.substring(0, NomAdr.length) == NomAdr) {
								if (field.id.substr(NomAdr.length) == "['Adresse_Etape']") {
									field.value = adresse['adresse'];
								}
								if (field.id.substr(NomAdr.length) == "['CP_Etape']") {
									field.value = adresse['cp'];
								}
								if (field.id.substr(NomAdr.length) == "['Ville_Etape']") {
									field.value = adresse['ville'];
								}
								if (field.id.substr(NomAdr.length) == "['Lat_Etape']") {
									field.value = adresse['lat'];
								}
								if (field.id.substr(NomAdr.length) == "['Lon_Etape']") {
									field.value = adresse['lon'];
								}
								if (field.id.substr(NomAdr.length) == "['ListePays_Ville_Etape']") {
									field.value = adresse['pays'];
								}
							}
						});
						var newVisible = "<tr id='Etape"+ numEtape+ "'><td>" + adresse['adresse'].substring(0,adresse['adresse'].length-1) + "</td>"
								+ "<td>" + adresse['cp'] + "</td>"
								+ "<td>" + adresse['ville']+ "</td>"
								+ "<td>" + adresse['pays'] + "</td><td><a href='javascript:supprimerEtape(" + numEtape + ")'>Supprimer cette étape </a></tr>";
						$j("tr#Etape"+numEtape).replaceWith(newVisible);
					}
				}
			});
			var premier = newMarkers[0].getLatLng();
			changementAdresse('D',premier);
			var dernier = newMarkers[newMarkers.length-1].getLatLng();
			changementAdresse('A',dernier);
			var points = [];
			var newTrajet = "from: ";
			for (var i = 0; i < newMarkers.length-1; i++) {
				
				points[i] = newMarkers[i].getLatLng();
				newTrajet += newMarkers[i].getLatLng().lat() + ',' + newMarkers[i].getLatLng().lng() + " to: ";
			}
			for (var i = 0; i < newMarkers.length; i++) 
			{
				points[i] = newMarkers[i].getLatLng();
			}
			newTrajet += newMarkers[newMarkers.length-1].getLatLng().lat() + ',' + newMarkers[newMarkers.length-1].getLatLng().lng();
//			console.log("Nouveau trajet (Modif marker):"+newTrajet);
			gdir.clear();
			map.removeOverlay(newMarkers);
			map.clearOverlays();
			if($j('#itiCarto')){
				$j('#itiCarto').val(newTrajet);
			}
//			gdir.load(newTrajet,{getPolyline: true});
			gdir.clear();
			gdir.loadFromWaypoints(points,{getPolyline: true, getSteps:true});
		});
		//Bind 'click' event to original markers 'click' event
		copyClick(newMarkers[i], originalMarker);
		
		// Now we can remove the original marker safely
		map.removeOverlay(originalMarker);
		
	}
}

function supprimerEtape(numero)
{
	//on enleve les champs cachés
	
	//on enleve la ligne du tableau d'affichage
	$j("tr#Etape"+numero).remove();
	var numWaypoint = numero+1;
	for(var i=0; i< newMarkers.length;i++){
		map.removeOverlay(newMarkers[i]);
	}
	//on décalle les étapes dont le numero est superieur à celui de l'etape supprimer
	var chmpHidden = $j('input:hidden[id^=Etape]');
	var dataNEtape = [];
	for(var i = numero; i< chmpHidden.length/6;i++){
		var newidAdr = "Etape[" + i + "]['Adresse_Etape']";
		var newidAdr2 = "Etape[" + parseInt(i+1) + "]['Adresse_Etape']";
		var newidCP = "Etape[" + i + "]['CP_Etape']";
		var newidCP2 = "Etape[" + parseInt(i+1) + "]['CP_Etape']";
		var newidVille = "Etape[" + i + "]['Ville_Etape']";
		var newidVille2 = "Etape[" +parseInt(i+1) + "]['Ville_Etape']";
		var newidPays = "Etape[" + i + "]['ListePays_Ville_Etape']";
		var newidPays2 = "Etape[" + parseInt(i+1) + "]['ListePays_Ville_Etape']";
		var newidLat = "Etape[" + i + "]['Lat_Etape']";
		var newidLat2 = "Etape[" + parseInt(i+1) + "]['Lat_Etape']";
		var newidLon = "Etape[" + i + "]['Lon_Etape']";
		var newidLon2 = "Etape[" + parseInt(i+1) + "]['Lon_Etape']";
		dataNEtape.push({
			old: newidAdr2,
			name: newidAdr,
			value:document.getElementById(newidAdr2)?document.getElementById(newidAdr2).value : ""
		});
		dataNEtape.push({
			old:newidCP2,
			name: newidCP,
			value:document.getElementById(newidCP2)?document.getElementById(newidCP2).value : ""
		});
		dataNEtape.push({
			name: newidVille,
			value:document.getElementById(newidVille2)?document.getElementById(newidVille2).value : ""
		});
		dataNEtape.push({
			old: newidPays2,
			name: newidPays,
			value:document.getElementById(newidPays2)?document.getElementById(newidPays2).value : ""
		});
		dataNEtape.push({
			old:newidLat2,
			name: newidLat,
			value:document.getElementById(newidLat2)?document.getElementById(newidLat2).value : ""
		});
		dataNEtape.push({
			old: newidLon2,
			name: newidLon,
			value:document.getElementById(newidLat2)?document.getElementById(newidLat2).value : ""
		});
	}
	jQuery.each(dataNEtape,function(i,field){
		if(document.getElementById(field.name)){
			document.getElementById(field.name).value = field.value;
		}
	});
	var nom = "#HEtape"+parseInt(chmpHidden.length/6-1);
	$j(nom).remove();
	newMarkers.splice(numWaypoint,1);
	trajet.splice(numWaypoint,1);
	var newTrajet = "from: ";
	var points = [];
	for (var i = 0; i < newMarkers.length-1; i++) 
	{
		newTrajet += newMarkers[i].getLatLng().lat() + ',' + newMarkers[i].getLatLng().lng() + " to: ";
	}
	for (var i = 0; i < newMarkers.length; i++) 
	{
		points[i] = newMarkers[i].getLatLng();
	}
	newTrajet += newMarkers[newMarkers.length-1].getLatLng().lat() + ',' + newMarkers[newMarkers.length-1].getLatLng().lng();
	
	gdir.clear();
	if($j('#itiCarto')){
		$j('#itiCarto').val(newTrajet);
	}
	gdir.loadFromWaypoints(points,{getPolyline: true, getSteps:true});
	
	
}

function sommetplusproche(mouseLatLng) {
		if (MarkerDrag) { return; }
		if (origLine.length > 1){
			var bounds = map.getBounds();
			var SW = bounds.getSouthWest();
			var NE = bounds.getNorthEast();
			var diag = SW.distanceFrom(NE);
			threshold = diag / 100;
			var minDist = 9999999999;
			var intermediateIndex = Math.round(origLine.length / 100);
			if (intermediateIndex > 0) {
				for (var n = 0 ; n < origLine.length-intermediateIndex ; n+= intermediateIndex ) {
					if (mouseLatLng.distanceFrom(origLine[n]) < minDist) {
						minDist = mouseLatLng.distanceFrom(origLine[n]);
						if (minDist < threshold) {
							etapeMarker.show();
							etapeMarker.setLatLng(new GLatLng(origLine[n].y,origLine[n].x));
						}
						else {
							etapeMarker.hide();
						}
					}
				}
			}
		}
	}
 
	function mouseMove(mousePt) {
		mouseLatLng = mousePt;
		sommetplusproche(mouseLatLng);
	}
 
function mouseOver(pointer)
{
	var tabEtape = $j('#recapEtape tbody');
	for (var n = 0; n < newMarkers.length; n ++) {
		if (pointer.distanceFrom(newMarkers[n].getLatLng()) == 0) {
			if(n >=1)
				numEtape = n-1;
			else
				numEtape =0;
			break;

		}
	}
}
	
function copyClick(newMarker,oldMarker){
    GEvent.addListener(newMarker, 'click', function(){
      	GEvent.trigger(oldMarker,'click');
    });
}

function geoRemplissagePoint(marker0){
	geocoder = new GClientGeocoder();
    geocoder.getLocations(marker0.getLatLng(), function(response){
        if (!response || response.Status.code != 200) {
            if (response.Status.code == 602) 
                alert('Impossible de récupérer les coordonnées GPS.');
        }
        else {
            place = response.Placemark[0];
            var latipt = place.Point.coordinates[1];
            var longipt = place.Point.coordinates[0];
            recupcor = response.name;
            tabcor = recupcor.split(",");
            adresse = cp = ville = pays = "";
            if (place.AddressDetails) {
                if (place.AddressDetails.Country.CountryName) 
                    pays = place.AddressDetails.Country.CountryName;
                if (place.AddressDetails.Country.AdministrativeArea) {
                    if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) {
                        if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) {
                            if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality) {
                                if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare) 
                                    if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName) 
                                        adresse = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
                                if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode) 
                                    cp = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
                                if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName) 
                                    ville = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
                            }
                        }
                    }
                }
            }
            marker0.openInfoWindowHtml( //'<b>orig latlng:</b>' + response.name + '<br/>' +
            '<div class="infowindow"><b>Adresse : </b>' + adresse + '<br>' +
            '<b>Code postal : </b>' +
            cp +
            '<br>' +
            '<b>Ville : </b>' +
            ville +
            '<br/>' +
            '<b>Pays : </b>' +
            pays +
            '<br/></div>' //'<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
            );
//			if (!location.href.search(/adresseperso/)) {
				if($j('#Addrese_Point'))
					$j('#Adresse_Point').val(adresse);
				if($j('#CP_Point'))
					$j('#CP_Point').val(cp);
				if($j('#Ville_Point'))
					$j('#Ville_Point').val(ville);
				if($j('#Lat_Point'))
					$j('#Lat_Point').val(latipt);
				if($j('#Lon_Point'))
					$j('#Lon_Point').val(longipt);
				if (document.getElementById('ListePays_Adresse')) {
                    var tabPays = $j('#ListePays_Adresse option:selected').val();
                    for (var i = 0; i < tabPays.length; i++) {
						if(pays == "Luxembourg") pays = "GD"+pays;
                        if (pays == tabPays[i].text) {
                            tabPays[i].selected = "selected";
                        }
                        
                    }
                }
				if(document.getElementById('ChmpAdressePoint'))
					document.getElementById('ChmpAdressePoint').value = place.address;
//			}
			
        }
    });
}

/*geocoder.getLocations(marker0.getLatLng(), function(response){
            if (!response || response.Status.code != 200) {
                if (response.Status.code == 602) 
                    alert('Impossible de récupérer les coordonnées GPS.');
            }
            else {
                place = response.Placemark[0];
                var latipt = place.Point.coordinates[1];
                var longipt = place.Point.coordinates[0];
                recupcor = response.name;
                tabcor = recupcor.split(",");
                adresse = cp = ville = pays = "";
                if (place.AddressDetails) {
                    if (place.AddressDetails.Country.CountryName) 
                        pays = place.AddressDetails.Country.CountryName;
                    if (place.AddressDetails.Country.AdministrativeArea) {
                        if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) {
                            if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) {
                                if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality) {
                                    if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare) 
                                        if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName) 
                                            adresse = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
                                    if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode) 
                                        cp = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
                                    if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName) 
                                        ville = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
                                }
                            }
                        }
                    }
                }
                marker0.openInfoWindowHtml( //'<b>orig latlng:</b>' + response.name + '<br/>' +
                '<b>Adresse : </b>' + adresse + '<br>' +
                '<b>Code postal : </b>' +
                cp +
                '<br>' +
                '<b>Ville : </b>' +
                ville +
                '<br/>' +
                '<b>Pays : </b>' +
                pays +
                '<br/>'                //'<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
                );
                document.getElementById('Adresse_Point').value = adresse;
                document.getElementById('CP_Point').value = cp;
                document.getElementById('Ville_Point').value = ville;
                if (document.getElementById('Lat_Point')) 
                    document.getElementById('Lat_Point').value = latipt;
                if (document.getElementById('Lon_Point')) 
                    document.getElementById('Lon_Point').value = longipt;
                if (document.getElementById('Pays_Point')) 
                    document.getElementById('Pays_Point').value = pays;
				if($j('#Lat_Point'))
					$j('#Lat_Point').val(latipt);
				if($j('#Lon_Point'))
					$j('#Lon_Point').val(longipt);
				if(document.getElementById('ChmpAdressePoint'))
					document.getElementById('ChmpAdressePoint').value = place.address;
                if (document.getElementById('ListePays_Adresse')) {
                    var tabPays = $j('#ListePays_Adresse option:selected').val();
                    for (var i = 0; i < tabPays.length; i++) {
						if(pays == "Luxembourg") pays = "GD"+pays;
                        if (pays == tabPays[i].text) {
                            tabPays[i].selected = "selected";
                        }
                        
                    }
                }
            }
        });
*/

function afficherMarker(lat_, longi_) {

    map.clearOverlays();
    var marker0 = new GMarker(new GLatLng(lat_, longi_), {
        draggable: true,
        image: 'http://www.covivo.eu/images/icon6.png'
    });
    geoRemplissagePoint(marker0);
    
    GEvent.addListener(marker0, "dragstart", function(){
        map.closeInfoWindow();
    });
    GEvent.addListener(marker0, "dragend", function(){
        geoRemplissagePoint(marker0);
    });
    map.addOverlay(marker0);
}

function createMarkerOnPlacemark(nom_, lat_, longi_){
    var marker = new GMarker(new GLatLng(lat_, longi_), {
        icon: new GIcon({
            iconAnchor: new GPoint(lat_, longi_),
            infoWindowAnchor: new GPoint(9, 4),
            image: 'http://www.covivo.eu/images/icon7.png'
        })
    });
    GEvent.addListener(marker, "click", function(){
    
        var text = nom_;
        paren1 = text.indexOf('(');
        paren2 = text.indexOf(')');
        pipe = text.indexOf('|');
        ville = text.substring(0, paren1);
        cp = text.substring(paren1 + 1, paren2);
        if (pipe > paren2) 
            adresse = text.substring(pipe + 1, text.length);
        else 
            adresse = '';
        var html = '';
        html = '<div class="infowindow"><b>Adresse : </b>' + adresse + '<br/>';
        html += '<b>Code postal : </b>' + cp + '<br/>';
        html += '<b>Ville : </b>' + ville + '<br/></div>';
		if($j('#Addrese_Point'))
			$j('#Adresse_Point').val(adresse);
		if($j('#CP_Point'))
			$j('#CP_Point').val(cp);
		if($j('#Ville_Point'))
			$j('#Ville_Point').val(ville);
		if($j('#Pays_point'))
			$j('#Pays_point').val(1);
		if($j('#Lat_Point'))
			$j('#Lat_Point').val(lat_);
		if($j('#Lon_Point'))
			$j('#Lon_Point').val(longi_);
        marker.openInfoWindowHtml(html);
    });
    map.addOverlay(marker);
}
function createMarkerOnPlacemark2(nom_, lat_, longi_){
    var marker = new GMarker(new GLatLng(lat_, longi_), {
        icon: new GIcon({
            iconAnchor: new GPoint(lat_, longi_),
            infoWindowAnchor: new GPoint(9, 4),
            image: 'http://www.covivo.eu/images/icon39.png'
        })
    });
    GEvent.addListener(marker, "click", function(){
    
        var text = nom_;
        paren1 = text.indexOf('(');
        paren2 = text.indexOf(')');
        pipe = text.indexOf('|');
        ville = text.substring(0, paren1);
        cp = text.substring(paren1 + 1, paren2);
        if (pipe > paren2) 
            adresse = text.substring(pipe + 1, text.length);
        else 
            adresse = '';
        var html = '';
        html = '<div class="infowindow"><b>Adresse : </b>' + adresse + '<br/>';
        html += '<b>Code postal : </b>' + cp + '<br/>';
        html += '<b>Ville : </b>' + ville + '<br/></div>';
		if($j('#Addrese_Point'))
			$j('#Adresse_Point').val(adresse);
		if($j('#CP_Point'))
			$j('#CP_Point').val(cp);
		if($j('#Ville_Point'))
			$j('#Ville_Point').val(ville);
		if($j('#Pays_point'))
			$j('#Pays_point').val(1);
		if($j('#Lat_Point'))
			$j('#Lat_Point').val(lat_);
		if($j('#Lon_Point'))
			$j('#Lon_Point').val(longi_);
        marker.openInfoWindowHtml(html);
    });
    map.addOverlay(marker);
}

function dessiner_carte_perso(id, lat, longi){
    map = new GMap2(document.getElementById(id));
    directions = new GDirections(map, '');
    map.setCenter(new GLatLng(lat, longi), 15);
    afficherMarker_perso(lat, longi);
    //map.addControl(new GLargeMapControl);
    geocoder = new GClientGeocoder();
    var customUI = map.getDefaultUI();
    customUI.controls.scalecontrol = false;
    customUI.controls.menumaptypecontrol = false;
    
    map.setUI(customUI);
}

function afficherMarker_perso(lat_, longi_){
    var marker = new GMarker(new GLatLng(lat_, longi_));
    map.addOverlay(marker);
}


function DessinerCarteItineraire(id,directions){
//	i = 0;
	etape = new Array();
	
	if (GBrowserIsCompatible()) { 
 
      map = new GMap2(document.getElementById(id));
	  panel = document.getElementById('directions');
	  direction = new GDirections(map,panel);
	  var customUI = map.getDefaultUI();
    	customUI.controls.scalecontrol = false;
		customUI.controls.menumaptypecontrol = false;
    
   	  map.setUI(customUI);
      map.setCenter(new GLatLng(48.860801696777,2.34579992294308),13);
      
	    GEvent.addListener(map, "click", function(overlay, latlng){
	        if (latlng) {
				
	            var gpoint = latlng;
	            etape[i] = new Array();
				etape[i]['Lat'] = gpoint.y;
	            etape[i]['Long'] = gpoint.x;
				ajouterMarker(gpoint.y, gpoint.x);
				//$j('#Click').append('<p><p>Point '+ i + ' : </p>lat : ' + etape[i]['Lat'] + '<br/>long : ' + etape[i]['Long'] + '</p>');
//				console.log(etape[i]);
				i++;
	        }
	    });
	 
    }else {
      alert("Désolé vous ne pouvez pas avoir google map sur votre navigateur.");
    }
}

function dessiner_itineraire_etape(id, lat, longi, itineraire){
//	console.log(id);
//	console.log(lat);
//	console.log(longi);
//	console.log(itineraire);

//	console.log(nbEtape);
    map = new GMap2(document.getElementById(id));
    map.setCenter(new GLatLng(lat, longi), 15);
    directions = new GDirections(map, '');
    directions.load(itineraire,{
		getPolyline: true,
		getSteps: true
	});
    //map.addControl(new GLargeMapControl);
    var customUI = map.getDefaultUI();
    customUI.controls.scalecontrol = false;
    customUI.controls.menumaptypecontrol = false;
    map.setUI(customUI);
	
	//drag du trajet pour le modifier
	var pointD = directions.getGeocode(0);
	ajouterMarkerDraggable(pointD);
	
	//Click sur la carte pour les étapes
//	 GEvent.addListener(map, "click", function(overlay, latlng){
//	 	if (nbEtape < 3) {
//			if (latlng) {
//			
//				var gpoint = latlng;
//				console.log(gpoint);
//				etape[nbEtape] = new Array();
//				etape[nbEtape]['Lat'] = gpoint.y;
//				etape[nbEtape]['Long'] = gpoint.x;
//				
//				itineraire = ajouterMarkerItineraire(id,gpoint.y, gpoint.x,itineraire);
//				console.log(itineraire);
//				dessiner_itineraire_etape(id, gpoint.y, gpoint.x, itineraire)
////				afficherMarker(gpoint.y,gpoint.x);
//				
//				//$j('#Click').append('<p><p>Point '+ i + ' : </p>lat : ' + etape[i]['Lat'] + '<br/>long : ' + etape[i]['Long'] + '</p>');
//				//				console.log(etape[i]);
//				nbEtape++;
//			}
//		}
//    });
}

function ajouterMarkerDraggable(point)
{
	
 
	var point = new GLatLng(point.Point.coordinates[1],point.Point.coordinates[0]);
	dragMarker = new GMarker(point, {image: 'http://www.covivo.eu/images/icon57.png',draggable:true,bouncy:false});
	GEvent.addListener(dragMarker, 'dragend', function(){
	});
	
	GEvent.addListener(dragMarker, 'dragstart', function(){
			markerDragging = true;
	});
	map.addOverlay(point);
}


function ajouterMarkerItineraire(id,lat_,long_,itineraire)
{
	var iti = itineraire;
	var tabIti = itineraire.split(' to:');
	if(tabIti.length == 2) //depart-arrivee
	{
		var etape = ' to:' + lat_ + ',' + long_;
		iti = tabIti[0] + etape + ' to:'+ tabIti[1];
	}else if(tabIti.length == 3) //depart-etape1-arrivee
	{
		var etape = ' to:' + lat_ + ',' + long_;
		iti = tabIti[0] + ' to:'+ tabIti[1] + etape + ' to:'+ tabIti[2];
	}
//	console.log(iti);
	return iti;
}

function ajouterMarker(lat_,longi_){
    var marker0 = new GMarker(new GLatLng(lat_, longi_), {
        draggable: false,
        image: 'http://www.covivo.eu/images/icon6.png'
    });
	map.addOverlay(marker0);
}

function itineraire(){
	waypoints = '';
	var k=i;
	for(var j=0;j<i;j++){
		waypoints +=etape[j]['Lat'] + ','+ etape[j]['Long'];
		waypoints += ' to:';
	}
	waypoints = waypoints.substr(0,waypoints.length-3);
//	var depart = $j('#VilleDeDepart').val();
//	var arrivee = $j('#VilleDArrivee').val();
//	waypoints += depart + ' to:' + arrivee;
//	console.log(waypoints);
	map.clearOverlays();
	direction.load(waypoints);
//	console.log(direction);
}


function coordonnees(){
	map.clearOverlays();
	$j('#Click').html('');
	geocoder = new GClientGeocoder();
	var adresse = $j('#Coord').val();
	 geocoder.getLocations(adresse, function(response){
        if (!response || response.Status.code != 200) {
            if (response.Status.code == 602) 
                alert('Impossible de récupérer les coordonnées GPS.');
            //            alert("Status Code:" + response.Status.code);
        }
        else {
//			console.log(response);
			for(var i = 0;i<response.Placemark.length;i++){
	            place = response.Placemark[i];
	            var latipt = place.Point.coordinates[1];
	            var longipt = place.Point.coordinates[0];
				var latlon = new GLatLng(latipt,longipt);
//				afficherMarker(latipt,longipt);
//				afficherMarker(latipt,longipt);
				afficherMarker_perso(latipt,longipt);
				$j('#Click').append("<p><p>Lat:" + latipt + "</p><p>Lon:" + longipt + "</p><p>Adresse: "+ place.name + "</p></p>");
				$j.ajax({url:'/outils/pause',
						data:{d:1},
						async: false,
						success: function(data){
							getAddress(latlon);
						}
				});
			}
//            recupcor = response.name;
//            tabcor = recupcor.split(",");
//            adresse = cp = ville = pays = "";
//            if (place.AddressDetails) {
//                if (place.AddressDetails.Country.CountryName) 
//                    pays = place.AddressDetails.Country.CountryName;
//                if (place.AddressDetails.Country.AdministrativeArea) {
//                    if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) {
//                        if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) {
//                            if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality) {
//                                if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare) 
//                                    if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName) 
//                                        adresse = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
//                                if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode) 
//                                    cp = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
//                                if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName) 
//                                    ville = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
//                            }
//                        }
//                    }
//                }
//            }
			
			$j('#Lat_Point').val(latipt);
			$j('#Lon_Point').val(longipt);
		}
	});
}

function getAddress(latlon) {
//	console.log(latlon)
  if (latlon != null) {
    geocoder.getLocations(latlon, showAddress);
  }
}

function showAddress(response) {
//	console.log(response.Status.code);
//	console.log(response);
  if (!response || response.Status.code != 200) {
//  	var latlon new GLatLng()
    alert("Status Code:" + response.Status.code);
  } else {
    place = response.Placemark[0];
    var info = $j(
        '<p><b>orig latlng:</b>' + response.name + '<br/>' + 
        '<b>latlng:</b>' + place.Point.coordinates[1] + "," + place.Point.coordinates[0] + '<br>' +
        '<b>Status Code:</b>' + response.Status.code + '<br>' +
        '<b>Status Request:</b>' + response.Status.request + '<br>' +
        '<b>Address:</b>' + place.address + '<br>' +
        '<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
        '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode + '<br/>-------------------------------------</p>');
	$j('#Click').append(info);
  }
  
}
function pause( iMilliseconds )
{
  var sDialogScript = 'window.setTimeout( function () { window.close(); }, ' + iMilliseconds + ');';
  window.showModalDialog('javascript:document.writeln ("<script>' + sDialogScript + '<' + '/script>")');
}

function dessiner_carte_evt(id, lat_, longi_, titre){
//	console.log(document.getElementById(id));
    map = new GMap2(document.getElementById(id));
    directions = new GDirections(map, '');
    map.setCenter(new GLatLng(lat_, longi_), 15);
    afficherMarker_evt(lat_, longi_, titre);
}


function afficherMarker_evt(lat_, longi_, titre){
    map.clearOverlays();
   var marker0 = new GMarker(new GLatLng(lat_, longi_), {
        draggable: false,
        image: 'http://www.covivo.eu/images/icon6.png'
    });
	map.addOverlay(marker0);
//    marker0.openInfoWindowHtml('<b>TItre : </b>' + titre + '<br/>');
}

function dessiner_carte_relais(id, lat, longi,zoom){
	if(!zoom) zoom = 15;
    map = new GMap2(document.getElementById(id));
    directions = new GDirections(map, '');
    map.setCenter(new GLatLng(lat, longi), zoom);
    //map.addControl(new GLargeMapControl);
    geocoder = new GClientGeocoder();
    var customUI = map.getDefaultUI();
    customUI.controls.scalecontrol = false;
    customUI.controls.menumaptypecontrol = false;
    
    map.setUI(customUI);
    
    //map.addControl(new GSmallMapControl());
    //map.addControl(new GMapTypeControl());
}
function createMarkerArretBus(arret){
	    var marker = new GMarker(new GLatLng(arret.lat, arret.longi), {
	        icon: new GIcon({
	            iconAnchor: new GPoint(arret.lat, arret.longi),
	            infoWindowAnchor: new GPoint(9, 4),
	            image: 'http://www.covoiturage-dynamique.eu/images/dynamique/ico_points_relais_sms.png'
	        })
	    });
	    GEvent.addListener(marker, "click", function(){
	    	var html= '<div id="infos" style="height:250px;"><b>Code du point relais : '+arret.NumArretBus+'</b><br/>';
			var adresse = arret.NomLitteral;
			var nomAdresse = adresse.substring(0,adresse.lastIndexOf('-'));
			var nomArret = adresse.substring(adresse.lastIndexOf('-')+1,adresse.length);
			html+= '<p style="clear:both;">Adresse : ' + nomAdresse +" " + nomArret+ '</p>';
			if(arret.Image)
				var img = '<div style="text-align:center;"><img src="' + arret.Image.Url + '" alt="' + arret.NomLitteral + '" width="' + arret.Image.width +'" height="'+ arret.Image.height+'"/></div></div>';
			else
				var img = '';
			html += img;
			marker.openInfoWindowHtml(html);
//			html+="<a href='javascript:ajouterAdr(" + arret.id + ")' >Ajouter ce point relais à mes adresses</a>";
	    });
	    map.addOverlay(marker);
};
