
var map;
var geocoder;
var reversegeocoder;
var gdir;
var icons = [];
//var types = new Array('spot','rider','ville','shop','club','annonce','stations','repere','trace','zone','mcf');
var types = [];		// tableau de markers
var spots 	= [];
var htmls 	= [];
	htmls['trace'] = new Array();
var traces 	= [];
var spot_lat = '';
var spot_lng = '';
var codePays;
var B_itineraire = false;
var B_searchVille = false;
var B_addSpot = false;
var B_addPoint = false;
var B_addTrace = false;
var B_addZone = false;
var optionsInfoWindow = {   
  maxWidth : 250
};





types["ville"] = new Array();

htmls["ville"] = new Array();

// GIcon ville > ville
var icon_ville_ville = new GIcon();
icon_ville_ville.image = 'http://www.vttspot.com/ihm/img/map/ville_ville.png';
icon_ville_ville.iconSize = new GSize(24, 30);
icon_ville_ville.iconAnchor = new GPoint(12, 15);
icon_ville_ville.infoWindowAnchor = new GPoint(12, 15);
icons["ville"] = icon_ville_ville;

types["ville"]["ville"] = new Array();

types["shop"] = new Array();

htmls["shop"] = new Array();

// GIcon shop > shop
var icon_shop_shop = new GIcon();
icon_shop_shop.image = 'http://www.vttspot.com/ihm/img/map/shop_shop.png';
icon_shop_shop.iconSize = new GSize(24, 30);
icon_shop_shop.iconAnchor = new GPoint(12, 15);
icon_shop_shop.infoWindowAnchor = new GPoint(12, 15);
icons["shop"] = icon_shop_shop;

types["shop"]["shop"] = new Array();

types["rider"] = new Array();

htmls["rider"] = new Array();

// GIcon rider > ami
var icon_rider_ami = new GIcon();
icon_rider_ami.image = 'http://www.vttspot.com/ihm/img/map/rider_ami.png';
icon_rider_ami.iconSize = new GSize(24, 30);
icon_rider_ami.iconAnchor = new GPoint(12, 15);
icon_rider_ami.infoWindowAnchor = new GPoint(12, 15);
icons["ami"] = icon_rider_ami;

types["rider"]["ami"] = new Array();

// GIcon rider > inconnu
var icon_rider_inconnu = new GIcon();
icon_rider_inconnu.image = 'http://www.vttspot.com/ihm/img/map/rider_inconnu.png';
icon_rider_inconnu.iconSize = new GSize(24, 30);
icon_rider_inconnu.iconAnchor = new GPoint(12, 15);
icon_rider_inconnu.infoWindowAnchor = new GPoint(12, 15);
icons["inconnu"] = icon_rider_inconnu;

types["rider"]["inconnu"] = new Array();

types["repere"] = new Array();

htmls["repere"] = new Array();

// GIcon repere > parking
var icon_repere_parking = new GIcon();
icon_repere_parking.image = 'http://www.vttspot.com/ihm/img/map/repere_parking.png';
icon_repere_parking.iconSize = new GSize(24, 30);
icon_repere_parking.iconAnchor = new GPoint(12, 15);
icon_repere_parking.infoWindowAnchor = new GPoint(12, 15);
icons["parking"] = icon_repere_parking;

types["repere"]["parking"] = new Array();

// GIcon repere > eau
var icon_repere_eau = new GIcon();
icon_repere_eau.image = 'http://www.vttspot.com/ihm/img/map/repere_eau.png';
icon_repere_eau.iconSize = new GSize(24, 30);
icon_repere_eau.iconAnchor = new GPoint(12, 15);
icon_repere_eau.infoWindowAnchor = new GPoint(12, 15);
icons["eau"] = icon_repere_eau;

types["repere"]["eau"] = new Array();

// GIcon repere > gap
var icon_repere_gap = new GIcon();
icon_repere_gap.image = 'http://www.vttspot.com/ihm/img/map/repere_gap.png';
icon_repere_gap.iconSize = new GSize(24, 30);
icon_repere_gap.iconAnchor = new GPoint(12, 15);
icon_repere_gap.infoWindowAnchor = new GPoint(12, 15);
icons["gap"] = icon_repere_gap;

types["repere"]["gap"] = new Array();

// GIcon repere > pierrier
var icon_repere_pierrier = new GIcon();
icon_repere_pierrier.image = 'http://www.vttspot.com/ihm/img/map/repere_pierrier.png';
icon_repere_pierrier.iconSize = new GSize(24, 30);
icon_repere_pierrier.iconAnchor = new GPoint(12, 15);
icon_repere_pierrier.infoWindowAnchor = new GPoint(12, 15);
icons["pierrier"] = icon_repere_pierrier;

types["repere"]["pierrier"] = new Array();

// GIcon repere > northshore
var icon_repere_northshore = new GIcon();
icon_repere_northshore.image = 'http://www.vttspot.com/ihm/img/map/repere_northshore.png';
icon_repere_northshore.iconSize = new GSize(24, 30);
icon_repere_northshore.iconAnchor = new GPoint(12, 15);
icon_repere_northshore.infoWindowAnchor = new GPoint(12, 15);
icons["northshore"] = icon_repere_northshore;

types["repere"]["northshore"] = new Array();

types["spot"] = new Array();

htmls["spot"] = new Array();

// GIcon spot > freeride
var icon_spot_freeride = new GIcon();
icon_spot_freeride.image = 'http://www.vttspot.com/ihm/img/map/spot_freeride.png';
icon_spot_freeride.iconSize = new GSize(24, 30);
icon_spot_freeride.iconAnchor = new GPoint(12, 15);
icon_spot_freeride.infoWindowAnchor = new GPoint(12, 15);
icons["freeride"] = icon_spot_freeride;

types["spot"]["freeride"] = new Array();

// GIcon spot > descente
var icon_spot_descente = new GIcon();
icon_spot_descente.image = 'http://www.vttspot.com/ihm/img/map/spot_descente.png';
icon_spot_descente.iconSize = new GSize(24, 30);
icon_spot_descente.iconAnchor = new GPoint(12, 15);
icon_spot_descente.infoWindowAnchor = new GPoint(12, 15);
icons["descente"] = icon_spot_descente;

types["spot"]["descente"] = new Array();

// GIcon spot > dirt
var icon_spot_dirt = new GIcon();
icon_spot_dirt.image = 'http://www.vttspot.com/ihm/img/map/spot_dirt.png';
icon_spot_dirt.iconSize = new GSize(24, 30);
icon_spot_dirt.iconAnchor = new GPoint(12, 15);
icon_spot_dirt.infoWindowAnchor = new GPoint(12, 15);
icons["dirt"] = icon_spot_dirt;

types["spot"]["dirt"] = new Array();

// GIcon spot > street
var icon_spot_street = new GIcon();
icon_spot_street.image = 'http://www.vttspot.com/ihm/img/map/spot_street.png';
icon_spot_street.iconSize = new GSize(24, 30);
icon_spot_street.iconAnchor = new GPoint(12, 15);
icon_spot_street.infoWindowAnchor = new GPoint(12, 15);
icons["street"] = icon_spot_street;

types["spot"]["street"] = new Array();

// GIcon spot > xcountry
var icon_spot_xcountry = new GIcon();
icon_spot_xcountry.image = 'http://www.vttspot.com/ihm/img/map/spot_xcountry.png';
icon_spot_xcountry.iconSize = new GSize(24, 30);
icon_spot_xcountry.iconAnchor = new GPoint(12, 15);
icon_spot_xcountry.infoWindowAnchor = new GPoint(12, 15);
icons["xcountry"] = icon_spot_xcountry;

types["spot"]["xcountry"] = new Array();

// GIcon spot > enduro
var icon_spot_enduro = new GIcon();
icon_spot_enduro.image = 'http://www.vttspot.com/ihm/img/map/spot_enduro.png';
icon_spot_enduro.iconSize = new GSize(24, 30);
icon_spot_enduro.iconAnchor = new GPoint(12, 15);
icon_spot_enduro.infoWindowAnchor = new GPoint(12, 15);
icons["enduro"] = icon_spot_enduro;

types["spot"]["enduro"] = new Array();

// GIcon spot > bikepark
var icon_spot_bikepark = new GIcon();
icon_spot_bikepark.image = 'http://www.vttspot.com/ihm/img/map/spot_bikepark.png';
icon_spot_bikepark.iconSize = new GSize(24, 30);
icon_spot_bikepark.iconAnchor = new GPoint(12, 15);
icon_spot_bikepark.infoWindowAnchor = new GPoint(12, 15);
icons["bikepark"] = icon_spot_bikepark;

types["spot"]["bikepark"] = new Array();

// GIcon spot > skatepark
var icon_spot_skatepark = new GIcon();
icon_spot_skatepark.image = 'http://www.vttspot.com/ihm/img/map/spot_skatepark.png';
icon_spot_skatepark.iconSize = new GSize(24, 30);
icon_spot_skatepark.iconAnchor = new GPoint(12, 15);
icon_spot_skatepark.infoWindowAnchor = new GPoint(12, 15);
icons["skatepark"] = icon_spot_skatepark;

types["spot"]["skatepark"] = new Array();

types["mcf"] = new Array();

htmls["mcf"] = new Array();

// GIcon mcf > mcf
var icon_mcf_mcf = new GIcon();
icon_mcf_mcf.image = 'http://www.vttspot.com/ihm/img/map/mcf_mcf.png';
icon_mcf_mcf.iconSize = new GSize(24, 30);
icon_mcf_mcf.iconAnchor = new GPoint(12, 15);
icon_mcf_mcf.infoWindowAnchor = new GPoint(12, 15);
icons["mcf"] = icon_mcf_mcf;

types["mcf"]["mcf"] = new Array();

types["station"] = new Array();

htmls["station"] = new Array();

// GIcon station > station
var icon_station_station = new GIcon();
icon_station_station.image = 'http://www.vttspot.com/ihm/img/map/station_station.png';
icon_station_station.iconSize = new GSize(24, 30);
icon_station_station.iconAnchor = new GPoint(12, 15);
icon_station_station.infoWindowAnchor = new GPoint(12, 15);
icons["station"] = icon_station_station;

types["station"]["station"] = new Array();


Gload = function() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GHierarchicalMapTypeControl());
		map.addControl(new GScaleControl());
		map.addMapType(G_PHYSICAL_MAP);
		map.setMapType(G_PHYSICAL_MAP);
		
		
					// limitation du zoom si pas connecté
			var mapTypes = map.getMapTypes();
			for(var i = 0; i < mapTypes.length; i++){
				mapTypes[i].getMaximumResolution = function(latlng){ return 13;};
			}
				
		
		map.enableDoubleClickZoom();
	    map.enableContinuousZoom();
		map.setCenter(new GLatLng(38.914398,-77.076302), 10);
	    geocoder = new GClientGeocoder();
	    
	    // Itinéraires
//		gdir = new GDirections(map);
//		GEvent.addListener(gdir,"load", function() {
//			setTimeout('customPanel(map,"map",gdir)',1000);
//      	}); 
//        GEvent.addListener(gdir, "error", gdirErrors);
		
        // menu contextuel
        new ContextMenu(map);
	    
        // chargement des points initial
		searchMap();
		
		// chargement des points au déplacement
		GEvent.addListener(map, "dragend", function() {
			if (!B_addSpot && !B_itineraire && !B_addTrace && !B_addPoint && !B_addZone) {
				map.closeInfoWindow();
				// on vide la ville si on bouge pour ne pas refaire une recherche ds un rayon de ...
//				$('#searchWhat').val('');
//				$('#searchVille').val('');
				searchMap();
			}
		});
		
		// chargement des points au zoom
		GEvent.addListener(map, "zoomstart", function() {
			
		});
		
		GEvent.addListener(map, "zoomend", function() {
			if (!B_addSpot && !B_itineraire && !B_addTrace && !B_addPoint && !B_addZone) {
				map.closeInfoWindow();
				// on vide la ville si on zoom pour ne pas refaire une recherche ds un rayon de ...
//				$('#searchWhat').val('');
//				$('#searchVille').val('');
				searchMap();
			}
		});
		
		map.hideControls();
		GEvent.addListener(map, "mouseover", function() {
			map.showControls();
		});
		GEvent.addListener(map, "mouseout", function() {
			map.hideControls(); 
		});
		
		
		// tooltip
	    tooltip = document.createElement("div");
		tooltip.className = "tooltip";
		map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
		tooltip.style.display = "none"; 

	};
};





GloadAjout = function() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GHierarchicalMapTypeControl());
		map.addControl(new GScaleControl());
		map.addMapType(G_PHYSICAL_MAP);
		map.setMapType(G_PHYSICAL_MAP);
		
		
					// limitation du zoom si pas connecté
			var mapTypes = map.getMapTypes();
			for(var i = 0; i < mapTypes.length; i++){
				mapTypes[i].getMaximumResolution = function(latlng){ return 13;};
			}
				
		
		map.enableDoubleClickZoom();
	    map.enableContinuousZoom();
		map.setCenter(new GLatLng(38.914398,-77.076302), 10);
	    geocoder = new GClientGeocoder();
	    
	   
	    // chargement des points initial
		//searchMap();
		
		// chargement des points au déplacement
		GEvent.addListener(map, "dragend", function() {
			if (!B_addSpot && !B_itineraire && !B_addTrace && !B_addPoint && !B_addZone) {
				map.closeInfoWindow();
				// on vide la ville si on bouge pour ne pas refaire une recherche ds un rayon de ...
//				$('#searchWhat').val('');
//				$('#searchVille').val('');
				searchMap();
			}
		});
		
		// chargement des points au zoom
		GEvent.addListener(map, "zoomstart", function() {
			
		});
		
		GEvent.addListener(map, "zoomend", function() {
			if (!B_addSpot && !B_itineraire && !B_addTrace && !B_addPoint && !B_addZone) {
				map.closeInfoWindow();
				// on vide la ville si on zoom pour ne pas refaire une recherche ds un rayon de ...
//				$('#searchWhat').val('');
//				$('#searchVille').val('');
				searchMap();
			}
		});
		
		map.hideControls();
		GEvent.addListener(map, "mouseover", function() {
			map.showControls();
		});
		GEvent.addListener(map, "mouseout", function() {
			map.hideControls(); 
		});

	};
};

refreshMapOnMove = function() {
	var bounds = map.getBounds();
	var lat_sw = bounds.getSouthWest().lat();
	var lat_ne = bounds.getNorthEast().lat();
	var lng_sw = bounds.getSouthWest().lng();
	var lng_ne = bounds.getNorthEast().lng();
	GDownloadUrl('http://www.vttspot.com/xml/XmlSpots.php?lat_sw='+lat_sw+'&lng_sw='+lng_sw+'&lat_ne='+lat_ne+'&lng_ne='+lng_ne, loadSpots);
};

loadSpots = function(data, responseCode) {
    map.clearOverlays();
    var showResults = true;
	if(responseCode == 200) { 
    	// si pas de résultat
    	if (data == 0) {
    		if (showResults) {
			    //sendResultsToShow(data);
			    sendResultsToFilters(data);
		    }
    	} else {
		    var xml = GXml.parse(data);
			var markers = xml.documentElement.getElementsByTagName("marker");
			
			// création des spots visibles
			var bounds = new GLatLngBounds();
			for (var i = 0; i < markers.length; i++) {
				
				// typeCat (spot, rider, shop, club, ..) + 0 ou plusieurs types (freeride, descente, ...) par typeCat
				var nodeTypeCat = markers[i].childNodes[0];
				var cat = nodeTypeCat.getAttribute("typeCat");
				
				// cas des spots, riders, shops, annonces, stations, repères ...
				if (cat != 'trace' && cat != 'zone' ) {
					
					if (cat == 'repere') showResults = false;
				
					// infos globales (id, nom, desc, lat, lng)
					var spot_id = markers[i].getAttribute("spot_id");
					var name = markers[i].getAttribute("name");
					var desc = markers[i].getAttribute("desc");
					var lat = parseFloat(markers[i].getAttribute("lat"));
					var lng = parseFloat(markers[i].getAttribute("lng"));
					var url = markers[i].getAttribute("url");
				
					var nbTypes = nodeTypeCat.childNodes.length;
					var A_ts = new Array();
					if ( nbTypes > 0) {
						for (var cpt=0; cpt<nbTypes; cpt++) {
							var ts = nodeTypeCat.childNodes[cpt].childNodes[0].nodeValue;
							A_ts.push(ts);
						}
					} else {
						A_ts.push(cat);
					}
	
					var point = new GLatLng(lat, lng);
					createMarker(point, name, desc, url, cat, A_ts, spot_id);
					
					// élargissement des frontières
					bounds.extend(new GLatLng(lat, lng));
				
				} else {
					showResults = false;
					
					// infos globales (id, nom, desc, lat, lng)
					var spot_id = markers[i].getAttribute("spot_id");
					var name = markers[i].getAttribute("name");
					var desc = markers[i].getAttribute("desc");
					var poly = markers[i].getAttribute("poly");

					polyline = createTrace(spot_id, name, desc, poly, cat);
					
					// on stocke la ligne
					traces[spot_id] = polyline;
					
					// on stocke le contenu de la bulle
					htmls['trace'][spot_id] = desc;
					
					// élargissement des frontières
					bounds.extend(polyline.getBounds().getSouthWest());
					bounds.extend(polyline.getBounds().getNorthEast()); 
				} 
			}

			// recherche par rayon + ville, on élargit la carte en fct des résultats
			if (B_searchVille || !showResults) {
				var zoom = map.getBoundsZoomLevel(bounds);
				if (zoom > 17) zoom = 17;
				map.setCenter(bounds.getCenter(), zoom);
				B_searchVille = false;
			}
			
		    if (showResults) {
			    //sendResultsToShow(data);
			    sendResultsToFilters(data);
		    }
		    
		}
	} else if(responseCode == -1) {
		alert("La liste des spots a mis trop de temps à s\'executer, veuillez réessayer.");
		if (showResults) {
		    //sendResultsToShow(0);
		    sendResultsToFilters(0);
	    }
	} else { 
		alert("La liste des spots a générée une erreur ! Veuillez réessayer.");
		if (showResults) {
		    //sendResultsToShow(0);
		    sendResultsToFilters(0);
	    }
	}

};

sendResultsToShow = function(data) {
	// affichage texte à coté
    $.ajax({type: "POST",
			//processData: false,
			//contentType: 'application/xhtml+xml; charset=UTF-8',
			url: 'http://www.vttspot.com/pages/ajax/searchResults.php', 
			data: {'xml': data},
			success: function(data){
				$('#action').html(data).fadeIn('slow');
			},
			loadingId: '#action'
    });	
};

sendResultsToFilters = function(data) {
	// affichage texte à coté
    $.ajax({type: "POST",
			//processData: false,
			//contentType: 'application/xhtml+xml; charset=UTF-8',
			url: 'http://www.vttspot.com/pages/ajax/searchFiltres.php', 
			data: {'xml': data},
			success: function(data){
				$('#filtre').html(data).fadeIn('slow');
			},
			loadingId: '#filtre'
    });	
};


createMarker = function(point, name, desc, url, cat, A_ts, spot_id) {
	for ( var i=0; i < A_ts.length; i++) {
		var marker = new GMarker(point, icons[A_ts[i]]);
		marker.title = name;
		if (cat == 'repere') {
			GEvent.addListener(marker, 'click', function() {
				openInfoBullePoint(marker,spot_id);
			});
		} 
		if (cat == 'mcf' || cat == 'shop' || cat == 'station') {
			var html = desc;
			GEvent.addListener(marker, 'click', function() {
				marker.openInfoWindowHtml(html,optionsInfoWindow);
			});
		} else {
			var html = '<div class="infoWindow">';
			var html = '<div>';
			
			// urls
			var link_url = '';
			if (cat == 'spot') {
				link_url =  'http://www.vttspot.com/spot-'+ url;
			} else if (cat == 'rider') {
				link_url =  'http://www.vttspot.com/rider-'+ url;
			}
			
			if (url != '') {
				html += '<h2><a href="'+link_url+'">' + name + '</a></h2>';
			} else {
				html += '<h2>' + name + '</h2>';
			}
			//html += '<p>' + desc + '</p>';
			html += desc;
			html += '<div class="hr"></div>';
			html += '</div>';
			html += '<p>';
			if (url != '') {
				if (cat == 'spot') {
					html += '<a href="'+link_url+'">Voir les détails du spot</a><br />';
				}
				if (cat == 'rider') {
					html += '<a href="'+link_url+'">Voir sa fiche</a><br />';
				}
			}
						
			
			//html += 'Venir ici à partir de&nbsp;:&nbsp;';
			//html += '<input type="text" name="fromDest" id="fromDest" class="fromDest" value="" />&nbsp;';
			//html += '<input type="button" name="fromDestGo" id="fromDestGo" class="fromDestGo" value="Go" onclick="itineraire(\''+point.lat()+','+point.lng()+'\');"/>';
			//html += '</p>';
			
			GEvent.addListener(marker, 'click', function() {
				marker.openInfoWindowHtml(html,optionsInfoWindow);
			});
		}
		
		
		
		GEvent.addListener(marker,"mouseout",function(){
			tooltip.style.display = "none"; 
		});
		
		GEvent.addListener(marker,"mouseover",function(){
			tooltip.innerHTML = marker.title;
			tooltip.style.display = "block";
			var curr = map.getCurrentMapType().getProjection();
			var pt = curr.fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
			var offset = curr.fromLatLngToPixel(marker.getLatLng(),map.getZoom());
			var anchor = marker.getIcon().iconAnchor;
			var width = marker.getIcon().iconSize.width+6;
			var tpos = new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(offset.x-pt.x-anchor.x+width,offset.y-pt.y-anchor.y-11));
			tpos.apply(tooltip); 
		});
		
		// on stocke le contenu de la bulle
		htmls[cat][spot_id] = html;
		
		// on stocke le marker en fct de sa catégorie et de son type pour pouvoir le filtrer ensuite via les filtres (checkbox)
		types[cat][A_ts[i]][spot_id] = marker;
		
		map.addOverlay(marker);
	}
};


createTrace = function(spot_id, name, desc, poly, cat) {
	
	if (cat == 'trace') {
		var polyOptions = {geodesic:true};
		var polyline = new GPolyline(eval(poly), getColor(true), 2, 1);
		polyline.title = name;
		map.addOverlay(polyline);
		
		GEvent.addListener(polyline, 'click', function(point) {
			openInfoBulleTrace(polyline, point, spot_id);
		});
		
		GEvent.addListener(polyline,"mouseover",function(){
			tooltip.innerHTML = polyline.title;
			tooltip.style.display = "block";
			var curr = map.getCurrentMapType().getProjection();
			var pt = curr.fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
			var offset = curr.fromLatLngToPixel(polyline.getVertex(0),map.getZoom());
			var tpos = new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(offset.x - pt.x - 30, offset.y - pt.y - 11 ));
			tpos.apply(tooltip); 
		});
		
		GEvent.addListener(polyline,"mouseout",function(){
			tooltip.style.display = "none"; 
		});
		
		return polyline;
	} else {
		var polygon = new GPolygon(eval(poly), getColor(true), 2, 1, getColor(true), 0.2);
		polygon.title = name;
		map.addOverlay(polygon);
		
		GEvent.addListener(polygon, 'click', function(point) {
			openInfoBulleZone(polygon, point, spot_id);
		});
		
		GEvent.addListener(polygon,"mouseover",function(){
			tooltip.innerHTML = polygon.title;
			tooltip.style.display = "block";
			var curr = map.getCurrentMapType().getProjection();
			var pt = curr.fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
			var offset = curr.fromLatLngToPixel(polygon.getVertex(0),map.getZoom());
			var tpos = new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(offset.x - pt.x - 30, offset.y - pt.y - 11 ));
			tpos.apply(tooltip); 
		});
		
		GEvent.addListener(polygon,"mouseout",function(){
			tooltip.style.display = "none"; 
		});
		
		return polygon;
	}
	
};

addSpotOnMap = function(marker) {
	B_addSpot = true;
	map.closeInfoWindow();
	map.disableDoubleClickZoom();
	
	//$('#filtres').fadeOut('slow');
	//map.clearOverlays();
	if (!marker) {
		var ncoords = map.getCenter();
		var marker = new GMarker(ncoords, {draggable:true});
		//map.setZoom(13);
	}
	
	// on récupère les coordonnées du marker
	spot_lat = marker.getPoint().lat();
	spot_lng = marker.getPoint().lng();
	
	$.get('http://www.vttspot.com/pages/ajax/f_addSpot.php', 
			{ spot_lat: spot_lat, spot_lng: spot_lng }, 
			function(data){
				$('#action').fadeOut('normal', function() {
				
													$('#titreAction').html('Ajouter un spot et des éléments');
													$(this).html(data);
													
													// on place le spot
													//map.addOverlay(marker);
													
													// reverse geocoding
										    		markerDragEnd(marker);
										    		
										    		//ToggleTinyMCEEditors();
												}).fadeIn();	
	});
	
	// recup des coordonnées du point + appel aux WS pour récup infos ville
	GEvent.addListener(map, "dragend", function() {
		markerDragEnd();
	});
	
};

editSpot = function(id) {
	B_addSpot = true;
	var ncoords = map.getCenter();
	var marker = new GMarker(ncoords, {draggable:true});
	GDownloadUrl("http://www.vttspot.com/xml/xmlSpot.php?spot_id="+id, loadSpots);
	$.get('http://www.vttspot.com/pages/ajax/f_editSpot.php', 
			{ spot_id: id }, 
			function(data){
				$('#action').fadeOut('normal', function() {
													$('#titreAction').html('Ajouter des éléments à un spot');
													$(this).html(data);
												}).fadeIn();	
	});
};


findFromSearch = function (cat, id) {
	// univers : spots, riders, mcf, spots, stations
	var univers = $('input[@name=radio_entrie]:checked').val(); 

	// si on est pas dans le bon univers recherché, on bascule dessus
	if ( (cat == 'spot' && univers != 'spots')
		|| (cat == 'rider' && univers != 'riders')
		|| (cat == 'shop' && univers != 'shops')
		|| (cat == 'station' && univers != 'stations')
		|| (cat != univers)
		) {
		
		// on rajoute le 's' final
		if (cat != 'mcf') {
			var univ = cat+'s'; 
		} else {
			var univ = cat;
		}
		
		// on sélectionne le bon univers, ce qui relance la recherche ...
		$('input[@value='+univ+']').attr('checked','checked').trigger('click');
	}

	// on attend le temps que la recherche se refasse ...
	setTimeout(function() {
		// on affiche le point demandé
		var trouve = false;
		for (var typ in types[cat]) {
			for (var idPt in types[cat][typ]) {
				if (id == idPt) {
					var marker = types[cat][typ][idPt];
					map.addOverlay(marker);
					map.panTo(marker.getPoint());
					markerDragEnd();
					setTimeout(function() {marker.openInfoWindowHtml(htmls[cat][id],optionsInfoWindow);}, '250');
					trouve = true;
				}
			}
		}
		
		// non présent sur la carte, à recup via ajax
		if (!trouve) {
			getAndShowPointByAjax(cat, id);
		}
	}, '1000');
	
};

getAndShowPointByAjax = function (cat, id) {
	
	$.ajax({type: "GET",
					url: 'http://www.vttspot.com/pages/ajax/searchX.php', 
					data: {'cat': cat, 
							'id': id
					},
					success: function(data) {
						// on recharge la carte avec le point demandé
						loadSpots(data,200);
						
						// on affiche le point demandé
						for (var typ in types[cat]) {
							for (var idPt in types[cat][typ]) {
								if (id == idPt) {
									var marker = types[cat][typ][idPt];
									map.addOverlay(marker);
									map.panTo(marker.getPoint());
									markerDragEnd();
									setTimeout(function() {marker.openInfoWindowHtml(htmls[cat][id],optionsInfoWindow);}, '250');
								}
							}
						}
					}
		    });	
};

showSpot = function (cat, type, id) {
	
	var marker = types[cat][type][id];
	if (marker) {
		map.addOverlay(marker);
		map.panTo(marker.getPoint());
		setTimeout(function() {marker.openInfoWindowHtml(htmls[cat][id],optionsInfoWindow);}, '250');
	} else {
		getAndShowPointByAjax(cat, id);
	}
};

showTrace = function (tr_id) {
	
	var poly = traces[tr_id];
	var firstPointOfLine = poly.getVertex(1);
	
	$.get('http://www.vttspot.com/pages/ajax/f_addTrace.php',
						{tr_id: tr_id},
						function(html) {
							map.openInfoWindowHtml(firstPointOfLine, html,optionsInfoWindow);
						});
};

showZone = function (tr_id) {
	
	var poly = traces[tr_id];
	var firstPointOfLine = poly.getBounds().getCenter();
	
	$.get('http://www.vttspot.com/pages/ajax/f_addTrace.php',
						{tr_id: tr_id},
						function(html) {
							map.openInfoWindowHtml(firstPointOfLine, html,optionsInfoWindow);
						});
};

markerDragEnd = function(marker) {

	// si on n'est pas en train d'ajouter un point, tracé ou zone
	if (!B_addPoint && !B_addTrace && !B_addZone && B_addSpot) {
		// on récupère les coordonnées du marker
		if (!marker) {
			var center = map.getCenter();
			spot_lat = center.lat();
			spot_lng = center.lng();
		} else {
			// on cache le marker
			marker.hide();
			spot_lat = marker.getPoint().lat();
			spot_lng = marker.getPoint().lng();
		}
		
		
		// on affiche un spinner AJAX le tps que le process soit fini
	    $('#spinner_com').show();
	    $('#spot_com_id').hide();
	    $('#submitSpot').attr("disabled","true").attr("value", "Veuillez patienter ...");
		
		// on met à jour le formulaire
	    $('[name=spot_lat]', $('#formAddSpot')).attr('value', spot_lat);
	    $('[name=spot_lng]', $('#formAddSpot')).attr('value', spot_lng);
	    
	    // on recup le code pays pour pouvoir actualiser la liste des communes FR
	    var url = 'http://www.vttspot.com/pages/ajax/countrySubdivision.php?lat='+spot_lat+'&lng='+spot_lng;	
	    GDownloadUrl(url, function(data, responseCode) {
			if(responseCode == 200) { 
				codePays = data;
				
				// si autre que france on insert la commune
				if (codePays != 'FR' && codePays != '') {
					// on recup les infos de la commune la plus proche
					rgeocodeSpot();
			    } else {
			    	resfreshListeCommunes()
			    }
		        
		    	//marker.show();
			}  else if(responseCode == -1) { 
				// si trop lent à répondre on relance ...
				markerDragEnd();
			} else {
				// si trop lent à répondre on relance ...
				markerDragEnd();
			}
		});
	}
};

resfreshListeCommunes = function() {
	$("#spot_com_id").removeOption(/./);
    $("#spot_com_id").ajaxAddOption('http://www.vttspot.com/pages/ajax/a_selectCom.php',
    								{ spot_lat: spot_lat, spot_lng: spot_lng, code_pays: codePays },
    								true,
    								function (select) {
    									$("#spot_com_id").selectOptions(1, false, true);
    									$('#spot_com_id').show();	
    									$('#spinner_com').hide();
    									$('#submitSpot').removeAttr("disabled").attr("value", "Enregistrer");							
									}
								);
};

rgeocodeSpot = function() {
	var url = 'http://www.vttspot.com/pages/ajax/findNearbyPostalCodes.php?lat='+spot_lat+'&lng='+spot_lng;	
    
    var script = document.createElement('script');
	document.body.appendChild(script);
	script.src = 'http://prado.ws.geonames.org/findNearbyPostalCodesJSON?lat=' + spot_lat + '&lng=' + spot_lng + '&callback=insertNewVille';
};

insertNewVille = function(result) {
	$('#pays').val('');
	$('#region').val('');
	$('#departement').val('');
	$('#commune').val('');

	// si geonames trouve pas on passe par google
	if (result.postalCodes.length == 0) {
	
		reversegeocoder = new GReverseGeocoder(map);
		
		GEvent.addListener(reversegeocoder, "load",
			function(placemark) {
				var lat = placemark.Point.coordinates[1];
				var lng = placemark.Point.coordinates[0];
				var AdministrativeAreaName = reversegeocoder.getPlacemarkProperty(placemark, "AdministrativeAreaName");
				var SubAdministrativeAreaName = reversegeocoder.getPlacemarkProperty(placemark, "SubAdministrativeAreaName");
				var LocalityName = reversegeocoder.getPlacemarkProperty(placemark, "LocalityName");
			}
		);
		
		GEvent.addListener(reversegeocoder, "error",
			function() {
				//alert("Impossible de déterminer la ville la plus proche de ce point !");
			}
		);


        reversegeocoder.reverseGeocode(new GLatLng(spot_lat, spot_lng));
		
	} else {
		var lat = result.postalCodes[0].lat;
		var lng = result.postalCodes[0].lng;
		var AdministrativeAreaName = result.postalCodes[0].adminName1;
		var SubAdministrativeAreaName = result.postalCodes[0].adminName2;
		var LocalityName = result.postalCodes[0].placeName;
	}
		
	$('#pays').val(codePays);
	$('#region').val(AdministrativeAreaName);
	$('#departement').val(SubAdministrativeAreaName);
	$('#commune').val(LocalityName);
	
	// au passage on insert en BDD puis on raffraichit la liste des communes
	$.get('http://www.vttspot.com/pages/ajax/insertNewVille.php', 
				{ 	pays: codePays, 
					region: AdministrativeAreaName,
					dept: SubAdministrativeAreaName,
					commune: LocalityName,
					lat: lat,
					lng: lng
				 },
				function(data) {
					resfreshListeCommunes();								
				}
			);	
};


function loadJSFormAddSpot() {
	var options = { 
	    target:        '#action',   // target element(s) to be updated with server response 
	    beforeSubmit:  showRequest,  // pre-submit callback 
	    success:       showResponse  // post-submit callback 
	}; 
	
	$('#formAddSpot').submit(function() { 
		if (checkFuturSpot()) {
			cleanReperes();
			markerDragEnd();
	    	$(this).ajaxSubmit(options); 
		}
	    return false; 
	}); 
	
	function showRequest(formData, jqForm, options) { 
		$('#action').fadeOut();
	    return true; 
	} 
	
	function showResponse(responseText, statusText)  {
		$('#action').fadeIn();
	} 
};

function loadJSFormEditSpot() {
	var options = { 
	    target:        '#action',   // target element(s) to be updated with server response 
	    beforeSubmit:  showRequest,  // pre-submit callback 
	    success:       showResponse  // post-submit callback 
	}; 
	
	$('#formAddSpot').submit(function() { 
		if (checkFuturSpot()) {
			cleanReperes();
	    	$(this).ajaxSubmit(options); 
		}
	    return false; 
	}); 
	
	function showRequest(formData, jqForm, options) { 
		$('#action').fadeOut();
	    return true; 
	} 
	
	function showResponse(responseText, statusText)  {
		$('#action').fadeIn();
	} 
};

afterAddSpot = function() {
	B_addSpot = false;
	B_addPoint = false;
	B_addTrace = false;
	B_addZone = false;
	map.enableDoubleClickZoom();
	//setTimeout('searchMap()', 3000);	
};

// FILTRES ------------------------------------------------------------------------

toggleGroup = function(cat, type) {
	if (type != undefined) {
		for (var i in types[cat][type]) {
			var marker = types[cat][type][i];
			if ($('#cb_'+cat+'_'+type).is(':checked')) {
				marker.show();
			} else {
				marker.hide();
			}
		}
	} else {
		$('.cb_'+cat).attr('checked', $('#cb_'+cat).is(':checked'));
		for (var i in types[cat]) {
			for (j in types[cat][i]) {
				var marker = types[cat][i][j];
				if ($('#cb_'+cat+'_'+i).is(':checked')) {
					marker.show();
				} else {
					marker.hide();
				}
			}
		}
	}
};





// ITINERAIRES --------------------------------------------------------------------

function customPanel(map, mapname, gdir) {
	if (!$('#titreAction').children('img')) {
		$('#titreAction').html('Itinéraire');
	}
	$('#action').hide();
	var html = '';
	function waypoint(point, type, address) {
		var target = mapname + ".showMapBlowup(new GLatLng(" + point.toUrlValue(6) + "))";
		html += '<table style="border: 1px solid #476b25; border-collapse: collapse; background-color: #8cbb13;">';
		html += '  <tr style="cursor: pointer;" onclick="'+target+'">';
		html += '    <td style="padding: 4px 15px 0px 5px; vertical-align: middle; width: 20px;">';
		if (type == 'stop') {
			html += '      <img src="http://www.vttspot.com/ihm/img/map/repere_parking.png">';
		} else {
			html += '      <img src="http://www.google.com/intl/en_ALL/mapfiles/icon-dd-' +type+ '-trans.png">';
		}		
		html += '    </td>';
		html += '    <td style="vertical-align: middle; width:100%;">';
		html +=        address;
		html += '    </td>';
		html += '  </tr>';
		html += '</table>';
	}
	
	function routeDistance(dist) {
		html += '<div style="text-align: right; padding: 10px 0;">' + dist + '</div>';
	}
	
	function detail(point, num, description, dist) {
		var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
		html += '<table style="margin: 0px 0px 5px 0px; padding: 0px; border-collapse: collapse; border-top: 1px solid #e6f0d5;">';
		html += '  <tr style="cursor: pointer;" onclick='+target+'>';
		html += '    <td style="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="margin: 0px; padding: 0.3em 3px; vertical-align: top; width:100%;">';
		html +=        description;
		html += '    </td>';
		html += '    <td style="margin: 0px; padding: 0.3em 3px 0.3em 0.5em; vertical-align:top; text-align: right;">';
		html +=        dist;
		html += '    </td>';
		html += '  </tr>';
		html += '</table>';
	}
	
	function copyright(text) {
		html += '<div style="font-size: 0.86em;">' + text + "</div>";
	}
	
	for (var i=0; i<gdir.getNumRoutes(); i++) {
		if (i==0) {
			var type="play";
		} else {
			var type="pause";
		}
		var route = gdir.getRoute(i);
		var geocode = route.getStartGeocode();
		var point = route.getStep(0).getLatLng();
		waypoint(point, type, geocode.address);
		routeDistance(route.getDistance().html + " (environ " + route.getDuration().html + ")");
		for (var j=0; j<route.getNumSteps(); j++) {
			var step = route.getStep(j);
			detail(step.getLatLng(), j+1, step.getDescriptionHtml(),step.getDistance().html);
		}
	}
	
	var geocode = route.getEndGeocode();
	var point = route.getEndLatLng();
	waypoint(point, "stop", geocode.address);
	
	//copyright(gdir.getCopyrightsHtml());
	$('#action').html(html).fadeIn('slow');
};





function itineraireFicheSpot(toAddress) {
	if (toAddress == '') {
		center = map.getCenter();
		toAddress = center.lat()+','+center.lng();
	}
	var fromAddress = $('#fromDestSpot').val();
 	gdir.load('from: ' + fromAddress + ' to: ' + toAddress, { 'locale': 'fr' }, map.closeInfoWindow());
 	$('#closeItineraireSpot').show();
};



function itineraire(toAddress) {
	B_itineraire = true;
	var fromAddress = $('#fromDest').val();
 	gdir.load('from: ' + fromAddress + ' to: ' + toAddress, { 'locale': 'fr' }, map.closeInfoWindow());
};

function gdirErrors(){
	if (gdir.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: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	else if (gdir.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: " + gdir.getStatus().code);
	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	else alert("An unknown error occurred.");
   
};

function gdirLoad(){ 
  //alert(gdir.getDistance().meters);
  //alert(gdir.getDistance().html);
  //alert(gdir.getDuration().seconds);
  //alert(gdir.getDuration().html);
  //alert(gdir.getPolyline());
};



// CONTEXT MENU -------------------------------------------------------------------

function ContextMenu(oMap){
	this.initialize(oMap);
};

//Construct the DOM tree of the menu
ContextMenu.prototype.initLink = function(oMap){
	var that=this;
	
	a_link = document.createElement("li");
	a_link.innerHTML="<a href='javascript:void(0);'>Zoom +</a>";
	GEvent.addDomListener(a_link, 'click', function() {
		that.map.zoomIn();
		that.contextmenu.style.display='none';
	});
	this.ul_container.appendChild(a_link);
	
	a_link = document.createElement("li");
	a_link.innerHTML="<a href='javascript:void(0);'>Zoom -</a>";
	GEvent.addDomListener(a_link, 'click', function() {
		that.map.zoomOut();
		that.contextmenu.style.display='none';
	});
	this.ul_container.appendChild(a_link);
	
	a_link = document.createElement("li");
	a_link.innerHTML="<a href='javascript:void(0);'>Zoom ici</a>";
	GEvent.addDomListener(a_link, 'click', function() {
		var point = that.map.fromContainerPixelToLatLng(that.clickedPixel);
		that.map.zoomIn(point,true);
		that.contextmenu.style.display="none";
	});
	this.ul_container.appendChild(a_link);
	
	a_link = document.createElement("li");
	a_link.innerHTML="<a href='javascript:void(0);'>Centre la carte ici</a>";
	GEvent.addDomListener(a_link, 'click', function() {
		var point = that.map.fromContainerPixelToLatLng(that.clickedPixel);
		that.map.panTo(point);
		that.contextmenu.style.display="none";
	});
	this.ul_container.appendChild(a_link);
	
	a_link = document.createElement("li");
	a_link.innerHTML="<a href='javascript:void(0);'>Altitude</a>";
	this.activeLabel=null;
	this.timer=null;
	
	
	//This will manage the request for the altitude: once the result will be shown on a TLabel, and will disappear after 3 seconds.
	GEvent.addDomListener(a_link, 'click', function(){
		var point = that.map.fromContainerPixelToLatLng(that.clickedPixel);
		var url = 'http://www.vttspot.com/pages/ajax/get_altitude.php?alt_lat='+point.lat()+'&alt_lng='+point.lng();	
		that.contextmenu.style.display="none";
		GDownloadUrl(url, function(data, responseCode) {
			//This is the returned value if no data is available
			if(data=="-32768"){
				var retval = "N/A";
			}else{
				var retval = data + " m";
			}
			if(that.activeLabel!=null || that.timer!=null){
				map.removeTLabel(that.activeLabel);
				window.clearTimeout(that.timer);
				that.timer=null;
			}	
			var label = new TLabel();
			label.id = 'tlabel_altezza';
			label.anchorLatLng =point;
			label.percentOpacity = 85;
			label.content = '<div style="width:50px;font-weight:bold;border:1px solid #ffcc00;background:#77a743;color:#ffcc00;padding:4px;">'+retval+'</div>';
			map.addTLabel(label);
			var cb = that.bind(function(){map.removeTLabel(that.activeLabel);that.activeLabel=null;that.timer=null;});
			that.timer=window.setTimeout(cb,3000);
			that.activeLabel=label;
		});
	});
	this.ul_container.appendChild(a_link);	
};


ContextMenu.prototype.bind = function(method) {
	var self = this;
	var opt_args = [].slice.call(arguments, 1);
	return function() {
		var args = opt_args.concat([].slice.call(arguments));
		return method.apply(self, args);
	}
};

//The object 'constructor'
ContextMenu.prototype.initialize = function(oMap){
	this.map = oMap;
	var that=this;
	
	this.contextmenu = document.createElement("div");
	this.contextmenu.style.display="none";
	//CSS class name of the menu
	this.contextmenu.className="contextmenu";
	this.ul_container = document.createElement("ul");
	this.ul_container.id="context_menu_ul";
	this.contextmenu.appendChild(this.ul_container);	
	this.initLink();
	this.map.getContainer().appendChild(this.contextmenu);	

	//Event listeners that will interact with our context menu
	GEvent.addListener(oMap,"singlerightclick",function(pixel,tile) {
		that.clickedPixel = pixel;
		var x=pixel.x;
		var y=pixel.y;
		//Prevents the menu to go out of the map margins, in this case the expected menu size is 150x110
		if (x > that.map.getSize().width - 160) { x = that.map.getSize().width - 160 }
		if (y >that.map.getSize().height - 120) { y = that.map.getSize().height - 120 }
		var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));  
		pos.apply(that.contextmenu);
		that.contextmenu.style.display = "";
	});	
	GEvent.addListener(oMap, "move", function() {
		that.contextmenu.style.display="none";
	});
	GEvent.addListener(oMap, "click", function(overlay,point) {
		that.contextmenu.style.display="none";
	});	
};



// RECHERCHE -------------------------------------------------------------------

switchSearch = function() {
	var searchEntry = $('#searchEntry').val();
	if (searchEntry == 'ville') {
		$('#searchRayonArea').fadeIn('slow');
	} else {
		$('#searchRayonArea').fadeOut('slow');
	}
};

searchMap = function() {
	
	B_itineraire = false;
	if (!B_addSpot) {
		$('#titreAction').html('Eléments présents sur la carte');
		//$('#filtres').fadeOut('slow');
		$('#action').fadeOut('slow');
		
		var searchEntry = '';
				searchEntry = $('input[@name=radio_entrie]:checked').val() + '-'; 
		
		B_searchVille = false;
		var bounds = map.getBounds();
		var lat_sw = bounds.getSouthWest().lat();
		var lat_ne = bounds.getNorthEast().lat();
		var lng_sw = bounds.getSouthWest().lng();
		var lng_ne = bounds.getNorthEast().lng();
		GDownloadUrl('http://www.vttspot.com/xml/search.php?searchEntry='+searchEntry+'&lat_sw='+lat_sw+'&lat_ne='+lat_ne+'&lng_sw='+lng_sw+'&lng_ne='+lng_ne+'&zoom='+map.getZoom(), loadSpots);
	} else {
		alert('Vous devez finir d\'ajouter votre spot avant de rafraichir la carte !');
		return false;
	}
};


chooseVille = function(com_id) {
	var searchEntry = '';
		if ($('#entry_spots').is(':checked')) searchEntry += 'spots-';
	if ($('#entry_riders').is(':checked')) searchEntry += 'riders-';
	if ($('#entry_mcf').is(':checked')) searchEntry += 'mcf-';
	if ($('#entry_shops').is(':checked')) searchEntry += 'shops-';
	if ($('#entry_stations').is(':checked')) searchEntry += 'stations-';
	var searchWhat 	= $('#searchWhat').val();
	var searchRayon = $('#searchRayon').val();
	GDownloadUrl('http://www.vttspot.com/xml/search.php?searchVille='+com_id+'&searchWhat='+searchWhat+'&searchEntry='+searchEntry+'&searchRayon='+searchRayon, loadSpots);
	tb_remove();
};





// POINT / TRACES / ZONES --------------------------------------------------------------------------------

var COLORS = [["red", "#ff0000"], ["orange", "#ff8800"], ["green","#008000"],
              ["blue", "#000080"], ["purple", "#800080"]];
var A_points 		= {};
var A_polys 		= {};
var A_zones 		= {};
var A_ptIds 		= {};	// ids des éléments enregistrés
var options 		= {};
var cptPoints 		= 0;
var colorIndex_ 	= 0;


loadJSFormAddPoint = function() {
	var options = { 
	    target:        '#newPoint',   // target element(s) to be updated with server response 
	    beforeSubmit:  showRequest,  // pre-submit callback 
	    success:       showResponse  // post-submit callback 
	}; 
	
	$('#formAddPoint').submit(function() {
	    $(this).ajaxSubmit(options); 
	    return false; 
	}); 
	
	function showRequest(formData, jqForm, options) { 
		$('#newPoint').fadeOut();
	    return true; 
	} 
	
	function showResponse(responseText, statusText)  { 
		$('#newPoint').fadeIn();
		$('#submitPoint').click( function() {
								setTimeout('loadJSFormAddPoint()', 500);
							}); 
	} 
};


loadJSFormAddTrace = function() {
	var options = { 
	    target:        '#newTrace',   // target element(s) to be updated with server response 
	    beforeSubmit:  showRequest,  // pre-submit callback 
	    success:       showResponse  // post-submit callback 
	}; 
	
	$('#formAddTrace').submit(function() {
	    $(this).ajaxSubmit(options); 
	    return false; 
	}); 
	
	function showRequest(formData, jqForm, options) { 
		$('#newTrace').fadeOut();
	    return true; 
	} 
	
	function showResponse(responseText, statusText)  { 
		$('#newTrace').fadeIn();
		$('#submitTrace').click( function() {
								setTimeout('loadJSFormAddTrace()', 500);
							}); 
	} 
};


loadJSFormAddZone = function() {
	var options = { 
	    target:        '#newZone',   // target element(s) to be updated with server response 
	    beforeSubmit:  showRequest,  // pre-submit callback 
	    success:       showResponse  // post-submit callback 
	}; 
	
	$('#formAddZone').submit(function() {
	    $(this).ajaxSubmit(options); 
	    return false; 
	}); 
	
	function showRequest(formData, jqForm, options) { 
		$('#newZone').fadeOut();
	    return true; 
	} 
	
	function showResponse(responseText, statusText)  { 
		$('#newZone').fadeIn();
		$('#submitZone').click( function() {
								loadJSFormAddZone();
								setTimeout('loadJSFormAddZone()', 500);
							}); 
	} 
};


select = function(buttonId) {
	//document.getElementById("hand_b").className="unselected";
	document.getElementById("shape_b").className="unselected";
	document.getElementById("line_b").className="unselected";
	document.getElementById("placemark_b").className="unselected";
	document.getElementById(buttonId).className="selected";
};


getColor = function(named) {
	return COLORS[(colorIndex_++) % COLORS.length][named ? 0 : 1];
};

getIcon = function(color) {
	var icon = new GIcon();
	icon.image = "http://google.com/mapfiles/ms/micons/" + color + ".png";
	icon.iconSize = new GSize(24, 30);
	icon.iconAnchor = new GPoint(12, 30);
	icon.infoWindowAnchor = new GPoint(12, 0);
	return icon;
};


placeMarker = function() {
	B_addPoint = true;
	select("placemark_b");
	
	var clickMapListener = GEvent.addListener(map, "click", function(overlay,latlng) {
		GEvent.removeListener(clickMapListener);
	
		var color = getColor(true);
		var marker = new GMarker(latlng, {icon: getIcon(color), draggable: true});
		map.addOverlay(marker);
		
		cptPoints++;
		A_points[cptPoints] = marker;
		
		openInfoBullePoint(marker);
		
		GEvent.addListener(marker, "dragstart", function() {
			map.closeInfoWindow();
		});
		
		GEvent.addListener(marker, "dragend", function() {
			openInfoBullePoint(marker);
		});
		
		GEvent.addListener(marker, "click", function() {
			openInfoBullePoint(marker);
		});
	});
};


startLine = function() {
	B_addTrace = true;
	select("line_b");
	
	// on créé le tracé
	var color = getColor(true);
	var line = new GPolyline([], color, 2, 1, {geodesic:true});

	map.addOverlay(line);
	line.enableDrawing({});
	
	GEvent.addListener(line, "endline", function(latlng) {
		
		// création du marker sur le premier point de la ligne
		var point = line.getVertex(0);
		var marker = new GMarker(point, {icon: getIcon(color), draggable: false});
		
		// stockage du marker
		cptPoints++;
		A_points[cptPoints] = marker;
		
		// stockage de la polylin pour pouvoir la supprimer ensuite
		A_polys[cptPoints] = line;
		
		// ouverture de la bulle
		openInfoBulleTrace(line,point);
				
		// clic sur la ligne on raffiche la bulle sur la ligne
		GEvent.addListener(line, "click", function(latlng, index) {
												openInfoBulleTrace(line, latlng);
											});
	});
};


startZone = function() {
	B_addTrace = true;
	select("shape_b");
	
	// on créé la zone
	var color = getColor(true);
	var line = new GPolygon([], color, 2, 0.7, color, 0.2);

	map.addOverlay(line);
	line.enableDrawing({});
	
	GEvent.addListener(line, "endline", function(latlng) {
		
		// création du marker sur le premier point de la ligne
		var point = line.getVertex(0);
		var marker = new GMarker(point, {icon: getIcon(color), draggable: false});
	
		// stockage du marker
		cptPoints++;
		A_points[cptPoints] = marker;
		
		// stockage de la polylin pour pouvoir la supprimer ensuite
		A_zones[cptPoints] = line;
		
		// ouverture de la bulle
		openInfoBulleZone(line, point);
		
		// clic sur la ligne on raffiche la bulle sur le dernier marker
		GEvent.addListener(line, "click", function(latlng, index) {
												openInfoBulleZone(line, latlng);
											});
	});
};





openInfoBullePoint = function(marker, pt_id) {
	if (!pt_id) {
		for (idx in A_points) {
			if (A_points[idx].getLatLng().equals(marker.getLatLng())) {
				pt_id = A_ptIds[idx];
			}
		}
	}
	$.get('http://www.vttspot.com/pages/ajax/f_addPoint.php',
						{pt_lat: marker.getLatLng().lat(), pt_lng: marker.getLatLng().lng(), pt_id: pt_id},
						function(html) {
							var listenerInfoWindowOpen = GEvent.addListener(marker, "infowindowopen", function() {
								loadJSFormAddPoint();
								$('#submitPoint').click( function() {
									setTimeout('loadJSFormAddPoint()', 500);
								});
								GEvent.removeListener(listenerInfoWindowOpen);
							}); 
							marker.openInfoWindowHtml(html,optionsInfoWindow);
						});
};


openInfoBulleTrace = function(line, clikedPoint, tr_id) {

	// on récup le marker du dernier point de la ligne,
	// cas de la création de tracé, car on ne connait pas encore l'id du futur tracé
	// donc on se base sur le marker ajouté lors de la création (marker positionné sur le premier point de la ligne)
    var firstPointOfLine = line.getVertex(0);
	for (idx in A_points) {
		if (A_points[idx].getLatLng().equals(firstPointOfLine)) {
			marker = A_points[idx];
		}
	}
		
	// calcul des pts de la ligne, pour les passer en param au formulaire de tracé
	var A_traces = new Array();	// tableau de GPoints
	for(i=0; i<=(line.getVertexCount()-1); i++) {
        A_traces[i] = line.getVertex(i);
    }
    var S_trace = A_traces.join("|");
    
    // on récup l'id du tracé s'il n'y en a pas en param
	if (!tr_id) {
		for (idx in A_points) {
			if (A_points[idx].getLatLng().equals(marker.getLatLng())) {
				tr_id = A_ptIds[idx];
			}
		}
	}
	$.get('http://www.vttspot.com/pages/ajax/f_addTrace.php',
						{line: S_trace, tr_id: tr_id},
						function(html) {
							var listenerInfoWindowOpen = GEvent.addListener(map, "infowindowopen", function() {
								loadJSFormAddTrace();
								$('#submitTrace').click( function() {
									setTimeout('loadJSFormAddTrace()', 500);
								});
								GEvent.removeListener(listenerInfoWindowOpen);
							}); 
							map.openInfoWindowHtml(clikedPoint,html,optionsInfoWindow);
						});
};

openInfoBulleZone = function(line, clikedPoint, tr_id) {
	
	// on récup le marker du dernier point de la ligne,
	// cas de la création de tracé, car on ne connait pas encore l'id du futur tracé
	// donc on se base sur le marker ajouté lors de la création (marker positionné sur le premier point de la ligne)
    var firstPointOfLine = line.getVertex(0);
	for (idx in A_points) {
		if (A_points[idx].getLatLng().equals(firstPointOfLine)) {
			marker = A_points[idx];
		}
	}
	
	// calcul des pts de la ligne, pour les passer en param au formulaire d'ajout de zone
	var A_traces = new Array();	// tableau de GPoints
	for(i=0; i<=(line.getVertexCount()-1); i++) {
        A_traces[i] = line.getVertex(i);
    }
    var S_trace = A_traces.join("|");

    // on récup l'id de la zone s'il n'y en a pas en param
	if (!tr_id) {
		for (idx in A_points) {
			if (A_points[idx].getLatLng().equals(marker.getLatLng())) {
				tr_id = A_ptIds[idx];
			}
		}
	}
	$.get('http://www.vttspot.com/pages/ajax/f_addZone.php',
						{line: S_trace, tr_id: tr_id},
						function(html) {
							var listenerInfoWindowOpen = GEvent.addListener(map, "infowindowopen", function() {
								loadJSFormAddZone();
								$('#submitZone').click( function() {
									setTimeout('loadJSFormAddZone()', 500);
								});
								GEvent.removeListener(listenerInfoWindowOpen);
							}); 
							map.openInfoWindowHtml(clikedPoint,html,optionsInfoWindow);
						});
};


openInfoBulleTraceCreated = function(marker, tr_id) {
	$.get('http://www.vttspot.com/pages/ajax/f_addTrace.php',
						{tr_id: tr_id},
						function(html) {
							marker.openInfoWindowHtml(html,optionsInfoWindow);
						});
};

openInfoBulleZoneCreated = function(marker, tr_id) {
	$.get('http://www.vttspot.com/pages/ajax/f_addZone.php',
						{tr_id: tr_id},
						function(html) {
							marker.openInfoWindowHtml(html,optionsInfoWindow);
						});
};

addPointDatasToSpot = function(datas) {
	$.post('http://www.vttspot.com/pages/ajax/addPointDatasToSpot.php',
						{datas:datas, markerCounter: cptPoints},
						function(html) {
							$("#newPoint").effect("transfer", { to: "#listePoints" }, 3000);
							setTimeout(function () {
												$("#listePoints").append(html);
												map.closeInfoWindow();
												
												// changer l'icone du point juste ajouté
												marker = A_points[cptPoints];
												marker.setImage('http://www.vttspot.com/ihm/img/map/spot_spot.png');
												
												// virer le dragabble au passage
												marker.disableDragging();
												
												// puis on recentre la carte sur ce point pour rester ds la bonne zone
												map.panTo(marker.getLatLng());
										}, 3000);
						});
};

addTraceDatasToSpot = function(datas) {
	$.post('http://www.vttspot.com/pages/ajax/addTraceDatasToSpot.php',
						{datas:datas, markerCounter: cptPoints},
						function(html) {
							$("#newTrace").effect("transfer", { to: "#listePoints" }, 3000);
							setTimeout(function () {
												$("#listePoints").append(html);
												map.closeInfoWindow();
												
												// changer l'icone du point juste ajouté
												marker = A_points[cptPoints];
												marker.setImage('http://www.vttspot.com/ihm/img/map/spot_spot.png');
												
												// puis on recentre la carte sur ce point pour rester ds la bonne zone
												map.panTo(marker.getLatLng());
										}, 3000);
						});
};


addZoneDatasToSpot = function(datas) {
	$.post('http://www.vttspot.com/pages/ajax/addZoneDatasToSpot.php',
						{datas:datas, markerCounter: cptPoints},
						function(html) {
							$("#newZone").effect("transfer", { to: "#listePoints" }, 3000);
							setTimeout(function () {
												$("#listePoints").append(html);
												map.closeInfoWindow();
												
												// changer l'icone du point juste ajouté
												marker = A_points[cptPoints];
												marker.setImage('http://www.vttspot.com/ihm/img/map/spot_spot.png');
												
												// puis on recentre la carte sur ce point pour rester ds la bonne zone
												map.panTo(marker.getLatLng());
										}, 3000);
						});
};



delPoint = function(pt_id) {

	if (confirm('Etes vous sûr de vouloir supprimer ce repère ?')) {
		// suppression du marker
		for (counterM in A_ptIds) {
			if (A_ptIds[counterM] == pt_id) {
				map.closeInfoWindow();
				map.removeOverlay(A_points[counterM]);
				delete A_points[counterM];
			}
		}
		
		// suppression du point ds le tableau de points
		delete A_ptIds[pt_id];
		
		// suppression ds la fiche ajout de spot
		$('#pt_' + pt_id).remove();
		
		// suppression en BDD
		$.get('http://www.vttspot.com/pages/ajax/delPoint.php', {pt_id: pt_id});
	}
};


delTrace = function(tr_id) {

	if (confirm('Etes vous sûr de vouloir supprimer ce tracé ?')) {
		// suppression du marker et du tracé
		for (counterM in A_ptIds) {
			if (A_ptIds[counterM] == tr_id) {
				map.closeInfoWindow();
				map.removeOverlay(A_points[counterM]);
				map.removeOverlay(A_polys[counterM]);
				delete A_points[counterM];
				delete A_polys[counterM];
				var idx = counterM;
			}
		}
		
		// suppression du point ds le tableau de points
		delete A_ptIds[tr_id];
		
		// suppression ds la fiche ajout de spot
		$('#trace_' + tr_id).remove();
		
		// suppression en BDD
		$.get('http://www.vttspot.com/pages/ajax/delTrace.php', {tr_id: tr_id});
	}
};

delZone = function(tr_id) {

	if (confirm('Etes vous sûr de vouloir supprimer cette zone ?')) {
		
		// suppression du marker et de la zone
		for (counterM in A_ptIds) {
			if (A_ptIds[counterM] == tr_id) {
				map.closeInfoWindow();
				map.removeOverlay(A_points[counterM]);
				map.removeOverlay(A_zones[counterM]);
				delete A_points[counterM];
				delete A_zones[counterM];
				var idx = counterM;
			}
		}
		
		// suppression du point ds le tableau de points
		delete A_ptIds[tr_id];
		
		// suppression ds la fiche ajout de spot
		$('#zone_' + tr_id).remove();
		
		// suppression en BDD
		$.get('http://www.vttspot.com/pages/ajax/delTrace.php', {tr_id: tr_id});
	}
};

checkFuturSpot = function() {
	if($("#listePoints").html().length == 0) {
		alert('Merci de bien vouloir ajouter au minimum un repère sur ce spot, ou alors cliquez sur "Annuler"');
		return false;
	}
	return true;
};

cancelAddSpot = function() {
	B_addSpot = false;
	B_addPoint = false;
	B_addTrace = false;
	B_addZone = false;
	cleanReperes();
	map.enableDoubleClickZoom();
	top.location.href = 'http://www.vttspot.com/';
};

// suppression des éléments non enregistrés + appellée juste avant de soumettre un nouveau spot, 
// des fois que le centre de la carte initiale ai bcp changé suite aux ajouts de repères et autres tracés ...
cleanReperes = function() {
	var bounds = new GLatLngBounds(map.getCenter());
	
	for (idx in A_points) {
		if(A_ptIds[idx] == undefined) {
			map.removeOverlay(A_points[idx]);
			delete A_points[idx];
		} else {
			bounds.extend(new GLatLng(A_points[idx].getLatLng().lat(), A_points[idx].getLatLng().lng()));
		}
	}
	for (idx in A_polys) {
		if(A_ptIds[idx] == undefined) {
			map.removeOverlay(A_polys[idx]);
			delete A_polys[idx];
		} else {
			bounds.extend(A_polys[idx].getBounds().getSouthWest());
			bounds.extend(A_polys[idx].getBounds().getNorthEast());
		}
	}
	for (idx in A_zones) {
		if(A_ptIds[idx] == undefined) {
			map.removeOverlay(A_zones[idx]);
			delete A_zones[idx];
		} else {
			bounds.extend(A_zones[idx].getBounds().getSouthWest());
			bounds.extend(A_zones[idx].getBounds().getNorthEast());
		}
	}
	
	map.setCenter(bounds.getCenter());
	
	// on met à jour le formulaire
    $('[name=spot_lat]', $('#formAddSpot')).attr('value', bounds.getCenter().lat());
    $('[name=spot_lng]', $('#formAddSpot')).attr('value', bounds.getCenter().lng());
};

window.onunload = GUnload;


