var gmarkers = [];
var select_html;
var om = new OverlayMessage(document.getElementById('map'));

if (GBrowserIsCompatible())
{
	// === Create an associative array of GIcons() ===
	var Metar = new GIcon();
	Metar.iconSize=new GSize(70,35);
	Metar.shadowSize=new GSize(22,20);
	Metar.iconAnchor=new GPoint(6,20);
	Metar.infoWindowAnchor=new GPoint(5,1);

	var Station = new GIcon();
	Station.iconSize=new GSize(12,20);
	Station.shadowSize=new GSize(22,20);
	Station.iconAnchor=new GPoint(6,20);
	Station.infoWindowAnchor=new GPoint(5,1);
	var IconsStation = [];
	IconsStation[1] = new GIcon(Station, "http://www.previmeteo.fr/static/picto_gmap/mm_20_green.png");
	IconsStation[2] = new GIcon(Station, "http://www.previmeteo.fr/static/picto_gmap/mm_20_yellow.png");
	IconsStation[3] = new GIcon(Station, "http://www.previmeteo.fr/static/picto_gmap/mm_20_orange.png");
	IconsStation[4] = new GIcon(Station, "http://www.previmeteo.fr/static/picto_gmap/mm_20_red.png");

	var icone = new GIcon();
	//icone.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/green/blank.png";
	icone.shadow = "http://www.previmeteo.fr/static/picto_gmap/shadow50.png";
	icone.iconSize = new GSize(20, 34);
	icone.shadowSize = new GSize(37, 34);
	icone.iconAnchor = new GPoint(9, 34);
	icone.infoWindowAnchor = new GPoint(9, 2);

	function charge_xml()
	{
		//Création du marqueur au centre de la carte.
		var point = map.getCenter();
		var marqueur = new GMarker(point, icone);
		//select_html = '<select onChange="handleSelected(this)">' + '<option selected> - Liste des stations - <\/option>';
		map.addOverlay(marqueur);

		var center = map.getCenter();
		map.clearOverlays();
		// hide the info window, otherwise it still stays open where the removed marker used to be
	    map.getInfoWindow().hide();


        var bounds = map.getBounds();
  		var southWest = bounds.getSouthWest();
  		var northEast = bounds.getNorthEast();
		On();
		GDownloadUrl("GoogleMap/XML.php?ptsw="+southWest.toString()+"&ptne="+northEast.toString()+"&zoom="+map.getZoom(), function(data)
		{
			var xml = GXml.parse(data);
			var markers = xml.documentElement.getElementsByTagName("marker");
			for (var i = 0; i < markers.length; i++)
			{
				var lat = parseFloat(markers[i].getAttribute("lat"));
	            var lng = parseFloat(markers[i].getAttribute("lng"));
				var point = new GLatLng(lat,lng);
			    var html = GXml.value(markers[i].getElementsByTagName("infowindow")[0]);
	         	var label = markers[i].getAttribute("label");
	            var icontype = markers[i].getAttribute("icontype");

	            if(icontype == "ICAO")
	            {
	            	var ts = markers[i].getAttribute("ts");
	            	var temp = markers[i].getAttribute("temp");
	           		var vent = markers[i].getAttribute("vent");
	           		var color = "";
	            }
	            else
	            {
	            	var ts = "";
	            	var temp = "";
	           		var vent = "";
	           		var color = markers[i].getAttribute("color");
	            }
	            // === create the marker, passing the icontype string ===
				var marker = createMarker(point,label,html,icontype,ts,temp,vent,color);
	         	map.addOverlay(marker);
			}
	        // ===== final part of the select box =====
	       // select_html += '<\/select>';
	        //document.getElementById("selection").innerHTML = select_html;

		});
	}


	// Create the marker and corresponding information window
	function createMarker(point,name,html,icontype,ts,temp,vent,color)
	{
		if(icontype == "ICAO"){
			var marker = new GMarker(point, new GIcon(Metar, "/temps-reel/GoogleMap/picto.php?ts="+ts+"&temp="+temp+"&vent="+vent));
		}
		else
		{
			var marker = new GMarker(point, IconsStation[color]);
		}
		marker.category = icontype;   //Station ou ICAO
	    marker.name = name;
		GEvent.addListener(marker, "click",function() {marker.openInfoWindowHtml(html);});
		gmarkers.push(marker);
		// ======= Add the entry to the select box =====
 	    //select_html += '<option> ' + name + '<\/option>';
  	    // ==========================================================
		return marker;
	}

	 // ======= This function handles selections from the select box ====
      // === If the dummy entry is selected, the info window is closed ==
	function handleSelected(opt) {
        var i = opt.selectedIndex - 1;
        if (i > -1) {
          GEvent.trigger(gmarkers[i],"click");
        }
        else {
          map.closeInfoWindow();
        }
      }

	function On()
    {
    	om.SetBackgroundColor('#ffffff');
		om.SetBorderColor('#6F6F6F');
		om.Set( 'Merci de patienter quelques secondes...' );
   		setTimeout( "Off()", 6000 );
    }
	function Off()
    {
    	om.Clear();
    }

	var map = new GMap2(document.getElementById("map"));
	map.setCenter(new GLatLng(44.5, 0.15), 5,G_SATELLITE_MAP);

	/*Ajoute les barres d'outil de controle du Zoom et du Type d'affichage Plan ou Satellite*/
	//Zoom / dézoom à droite :
	map.addControl(new GSmallMapControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT,new GSize(20,40)));
    //Carte miniature en bas à droite :
	map.addControl(new GOverviewMapControl(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT,new GSize(20,0)));
	map.addControl(new GScaleControl());
	//Menu horizontal Plan, Sat Mixte :
	//map.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT,new GSize(60,-10)));
	//Menu déroulant Plan, Sat Mixte :
	map.addControl(new GMenuMapTypeControl(true,false));
    // Put the loading message underneath the tiles
  	document.getElementById("map").style.backgroundImage = "url(http://www.previmeteo.fr/static/picto_gmap/loading_tmp_reel.gif)";
  	// display the loading message

  	var center_old = map.getCenter();

	GEvent.addListener(map, "moveend", function()
	{
		var center_new = map.getCenter();
		var distance=Math.sqrt( (center_old.lat()-center_new.lat())*(center_old.lat()-center_new.lat()) + (center_old.lng()-center_new.lng())*(center_old.lng()-center_new.lng()));

		if (distance> (15/map.getZoom()))
		{
			//je me deplace de plus de 1 deg sur l hypothenuse
			charge_xml();
			center_old = map.getCenter();
		}
	});
	GEvent.addListener(map, "zoomend", function()
	{
		charge_xml();
	});
	charge_xml();

}


// == shows all markers of a particular category, and ensures the checkbox is checked ==
function show(category)
{
	for (var i=0; i<gmarkers.length; i++)
	{
		if (gmarkers[i].category == category)
		{
			gmarkers[i].show();
		}
	}
	// == check the checkbox ==
	document.getElementById(category+"box").checked = true;
}

// == hides all markers of a particular category, and ensures the checkbox is cleared ==
function hide(category)
{
	for (var i=0; i<gmarkers.length; i++)
	{
		if (gmarkers[i].category == category)
		{
			gmarkers[i].hide();
		}
	}
	// == clear the checkbox ==
	document.getElementById(category+"box").checked = false;
	// == close the info window, in case its open on a marker that we just hid
	map.closeInfoWindow();
}

// == a checkbox has been clicked ==
function boxclick(box,category)
{
	if (box.checked)
	{
	  show(category);
	}
	else
	{
	  hide(category);
	}
}
