//window.onload = function(){
//	load_geolocalisation();
//}

window.onunload = function(){
	GUnload();
}


	var map = null;
	var geocoder = null;
	var ref_bulle_active = null;
	
	var iconcommune = null;
	var customIcons = [];
	
	var liste_markers = [];
	
	// **** CREATION DU MARKER CORRESPONDANT AU POINT EN PARAMETRE ***************************************
	function init_icons_markers() {
		// icon communes
    	iconcommune = new GIcon(); 
    	iconcommune.image = 'http://www2.corbieres-sauvages.com/fileadmin/templates/images/marker_commune.png';
    	iconcommune.shadow = 'http://www2.corbieres-sauvages.com/fileadmin/templates/images/marker_ombre.png';
    	iconcommune.iconSize = new GSize(14, 22);
    	iconcommune.shadowSize = new GSize(20, 22);
    	iconcommune.iconAnchor = new GPoint(3, 22);
   	 	iconcommune.infoWindowAnchor = new GPoint(2, 1);
		// icon logez
    	iconlogez = new GIcon(); 
    	iconlogez.image = 'http://www2.corbieres-sauvages.com/fileadmin/templates/images/marker_logez.png';
    	iconlogez.shadow = 'http://www2.corbieres-sauvages.com/fileadmin/templates/images/marker_ombre.png';
    	iconlogez.iconSize = new GSize(14, 22);
    	iconlogez.shadowSize = new GSize(20, 22);
    	iconlogez.iconAnchor = new GPoint(3, 22);
    	iconlogez.infoWindowAnchor = new GPoint(2, 1);
		// icon regalez
    	iconregalez = new GIcon(); 
    	iconregalez.image = 'http://www2.corbieres-sauvages.com/fileadmin/templates/images/marker_regalez.png';
    	iconregalez.shadow = 'http://www2.corbieres-sauvages.com/fileadmin/templates/images/marker_ombre.png';
    	iconregalez.iconSize = new GSize(14, 22);
    	iconregalez.shadowSize = new GSize(20, 22);
    	iconregalez.iconAnchor = new GPoint(3, 22);
   	 	iconregalez.infoWindowAnchor = new GPoint(2, 1);
		// icon venez
    	iconvenez = new GIcon(); 
    	iconvenez.image = 'http://www2.corbieres-sauvages.com/fileadmin/templates/images/marker_venez.png';
    	iconvenez.shadow = 'http://www2.corbieres-sauvages.com/fileadmin/templates/images/marker_ombre.png';
    	iconvenez.iconSize = new GSize(14, 22);
    	iconvenez.shadowSize = new GSize(20, 22);
    	iconvenez.iconAnchor = new GPoint(3, 22);
    	iconvenez.infoWindowAnchor = new GPoint(2, 1);
		// icon profitez
    	iconprofitez = new GIcon(); 
    	iconprofitez.image = 'http://www2.corbieres-sauvages.com/fileadmin/templates/images/marker_venez.png';
    	iconprofitez.shadow = 'http://www2.corbieres-sauvages.com/fileadmin/templates/images/marker_ombre.png';
    	iconprofitez.iconSize = new GSize(14, 22);
    	iconprofitez.shadowSize = new GSize(20, 22);
    	iconprofitez.iconAnchor = new GPoint(3, 22);
    	iconprofitez.infoWindowAnchor = new GPoint(2, 1);
		// icon visitez
    	iconvisitez = new GIcon(); 
    	iconvisitez.image = 'http://www2.corbieres-sauvages.com/fileadmin/templates/images/marker_venez.png';
    	iconvisitez.shadow = 'http://www2.corbieres-sauvages.com/fileadmin/templates/images/marker_ombre.png';
    	iconvisitez.iconSize = new GSize(14, 22);
    	iconvisitez.shadowSize = new GSize(20, 22);
    	iconvisitez.iconAnchor = new GPoint(3, 22);
    	iconvisitez.infoWindowAnchor = new GPoint(2, 1);
		// liste des markers
    	customIcons["com"] = iconcommune;
    	// customIcons["logez"] = iconlogez;
		customIcons["1"] = iconlogez;
		customIcons["2"] = iconlogez;
		customIcons["3"] = iconlogez;
		customIcons["4"] = iconlogez;
		customIcons["5"] = iconlogez;
		customIcons["6"] = iconlogez;
    	// customIcons["regalez"] = iconregalez;
    	customIcons["7"] = iconregalez;
    	customIcons["8"] = iconregalez;
    	customIcons["9"] = iconregalez;
    	// customIcons["visitez"] = iconvisitez;
    	customIcons["10"] = iconvisitez;
    	customIcons["12"] = iconvisitez;
    	customIcons["13"] = iconvisitez;
    	customIcons["14"] = iconvisitez;
    	customIcons["19"] = iconvisitez;
    	customIcons["20"] = iconvisitez;
    	// customIcons["profitez"] = iconprofitez;
    	customIcons["15"] = iconprofitez;
    	customIcons["16"] = iconprofitez;
    	customIcons["17"] = iconprofitez;
    	customIcons["18"] = iconprofitez;
    	// customIcons["venez"] = iconvenez;
    	customIcons["21"] = iconvenez;
    	customIcons["22"] = iconvenez;
	}


	// **** SELECTION DU FICHIER XML EN FONCTION DU TYPE DE MARKERS ATTENDU **************************
	function refFichierXml () {
  		//if (typemarker == "logoni") {
		//	fichier_xml = "fileadmin/nimgeoloc/geoloc_presence_pays_" + typeproduit + ".xml";
		//} else {
		//	fichier_xml = "fileadmin/nimgeoloc/geoloc_revendeurs_" + typeproduit + ".xml";
		//}
	    fichier_xml = "fileadmin/templates/geoloc_cs.xml";
		return fichier_xml;
	}
	
	// **** INITIALISATIONS AU CHARGEMENT DE LA PAGE **************************************************
    function load_geolocalisation() {
	  if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
		//
			function TextualZoomControl() {}
		TextualZoomControl.prototype = new GControl();
		
		// Cr√©e un div pour chaque bouton et on les place dans un container
		TextualZoomControl.prototype.initialize = function(map) {
		  var container = document.createElement("div");
		
		  var size_of_direction_label = 25;
		  var width = map.getSize().width;
		  var middle_w = 0;
		  if (width > 0) middle_w = width/2 - size_of_direction_label;
		
		  var height = map.getSize().height;
		  var middle_height = 0;
		  if (height > 0) middle_height = height/2;
			
			init_icons_markers();
			
			//zoom in
		  var zoomInDiv = document.createElement("div");
		  this.setButtonStyle2_(zoomInDiv, height - height, middle_w - middle_w);
		  container.appendChild(zoomInDiv);
		  var img_zoomin = document.createElement('img');
		  img_zoomin.src = 'fileadmin/templates/images/geoloc_plus.png';
		  zoomInDiv.appendChild(img_zoomin);
		  GEvent.addDomListener(zoomInDiv, "click", function() {map.zoomIn();});

			
			//zoom out
		  var zoomOutDiv = document.createElement("div");
		  this.setButtonStyle2_(zoomOutDiv, height - height + 32 , middle_w - middle_w);
		  container.appendChild(zoomOutDiv);
		  var img_zoomout = document.createElement('img');
		  img_zoomout.src = 'fileadmin/templates/images/geoloc_moins.png';
		  zoomOutDiv.appendChild(img_zoomout);
		  GEvent.addDomListener(zoomOutDiv, "click", function() {map.zoomOut();});
		
		  map.getContainer().appendChild(container);
		  return container;
		}

		// By default, the control will appear in the top left corner of the
		// map with 7 pixels of padding.
		TextualZoomControl.prototype.getDefaultPosition = function() {
		  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 14));
		}
		
		// Sets the proper CSS for the given button element.
		TextualZoomControl.prototype.setButtonStyle_ = function(button,img) {
		  button.style.textDecoration = "underline";
		  button.style.font = "small Arial";
		  button.style.padding = "2px";
		  button.style.marginBottom = "10px";
		  button.style.textAlign = "center";
		  button.style.width = "24px";
		  button.style.height = "31px";
		  button.style.cursor = "pointer";
		  button.style.background = "url("+img+") top left no-repeat";
		}
		TextualZoomControl.prototype.setButtonStyle2_ = function(button, top_pos, left_pos) {
		  button.style.top = top_pos + "px";
		  button.style.left = left_pos + "px";
		  button.style.position = "absolute";
		  button.style.cursor = "pointer";
		}

		// initialement, se positionne sur le niveau 15 de zoom
		nivzoom = 14;
		// Par dÃ©efaut, se place au centre de toulouse
		lat_corbieres = '42.85124';
		lng_corbieres = '2.603539';
		map.enableDoubleClickZoom();//zoom au double click
		// ajout des options personnalisees de zooms	
		map.addControl(new TextualZoomControl());
       	map.setCenter(new GLatLng(lat_corbieres,lng_corbieres), nivzoom);
		// affiche les markers
		affiche_markers ();			
		if (zoom_geoloc != null) {
			zoom_geoloc_lieu (zoom_geoloc[0], zoom_geoloc[1], zoom_geoloc[2]);
		} else {
			nivzoom = 11;
			map.setCenter(new GLatLng(lat_corbieres,lng_corbieres), nivzoom);
		}
	  }
	}	
	
	
	// **** AFFICHE LES MARKERS DE GEOLOCALISATION **************************************************
	function affiche_markers () {
	if (GBrowserIsCompatible()) {
		map.clearOverlays();
  		// selectionne le fic xml correspondant aux markers attendus
  		fichier_xml = refFichierXml ();
    	geocoder = new GClientGeocoder();
        GDownloadUrl(fichier_xml, function(data) {
          var xml = GXml.parse(data);
          var markers = xml.documentElement.getElementsByTagName("marker");
		  var bounds = map.getBounds();
		  // affiche markers contextuels a la rubrique en cours
		  uriCourant = document.location.href;
		  indiceDepart = uriCourant.lastIndexOf('/')+1; 
		  indiceArrivee = uriCourant.length;
		  refPage = uriCourant.substring(indiceDepart, indiceArrivee);
		  // supprime les eventuels parametres additionnels
		  fin = refPage.indexOf('&');
		  if (fin >= 0) { refPage = refPage.substring(0, fin); }
		  // cas general (affiche tout) 
		  refCat = "";
		  // cas adherent
		  aliasPage = 'listecat';
		  detailPage = 'detail';
		  indiceCat = refPage.lastIndexOf(aliasPage);
		  if (indiceCat >= 0) {
			  refCat = refPage.substring(indiceCat+aliasPage.length, refPage.length);
		  } else {
			  indiceCat = refPage.lastIndexOf(detailPage);
		  	  if (indiceCat >= 0) {
			    refCat = refPage.substring(indiceCat+detailPage.length, refPage.length);
		      } else {
			     // cas communes
		  	     aliasPage = 'listecom';
			     detailPage = 'detailcom';
			     if ((refPage.lastIndexOf(aliasPage) >= 0) || (refPage.lastIndexOf(detailPage) >= 0)) { refCat = "com"; }
		      }
		  }
		  // affichage
		  for (var i = 0; i < markers.length; i++) {
			if ((refCat == "") || (refCat == markers[i].getAttribute("cat"))) {
            var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
			// affiche les markers seulement dans la partie visible de la carte
			if (bounds.contains(point) == true) {
				//if (typemarker == "logoni") {
				//	var name = "";
				//	var address = "";
				//	var typem = "ni";
				//} else {
					//var typem = typeproduit;
            		var name = markers[i].getAttribute("nom");
            		var address = markers[i].getAttribute("adresse1");
            		if ((markers[i].getAttribute("adresse2") != "") && (markers[i].getAttribute("adresse2") != null)) { address = address + "<br />" + markers[i].getAttribute("adresse2"); }
					address = address + "<br />" + markers[i].getAttribute("cp");
            		if ((markers[i].getAttribute("telephone") != "") && (markers[i].getAttribute("telephone") != null)) { address = address + "<br />T&eacute;l : " + markers[i].getAttribute("telephone"); }
					if ((markers[i].getAttribute("identifiant") != "") && (markers[i].getAttribute("cat") != "")) { 
						btnplus = "?id=detail" + markers[i].getAttribute("cat");
						if (markers[i].getAttribute("cat") == "com") btnplus = btnplus + "&com=";
						else btnplus = btnplus + "&adh=";
						btnplus = btnplus + markers[i].getAttribute("identifiant"); 
						refmarker = "ref"+markers[i].getAttribute("identifiant");
						liste_markers[refmarker] = marker;
					} else {
						btnplus = "";
					}
				//}
            	var marker = createMarker(point, name, address, btnplus, markers[i].getAttribute("cat"));
           		map.addOverlay(marker);
			}
          }
		  }
        });
		
		
		//if (liste_markers.length > 0) {
			//for (var i = 0; i < liste_markers.length; i++) {
			//	var point = new GLatLng(parseFloat(liste_markers[i][0]), parseFloat(liste_markers[i][1]));
			//	idresto = liste_markers[i][2];		
			//	var marker = createMarker(point, idresto);
				// ajoute marker
			//	map.addOverlay(marker);
			//}
			// en mode fiche detaillee, zoom sur resto en cours
			//if (openbulle) { map.setCenter(marker.getPoint(),15); }
		//}
      }
    }


	// **** CREATION DU MARKER CORRESPONDANT AU POINT EN PARAMETRE ***************************************
    function createMarker(point, name, address, btnplus, type) {
      var marker = new GMarker(point, customIcons[type]);
	  // zoom avant si clic sur logo ni
      	var html = "<p>";
	  	html = html + "<strong>" + name + "</strong>";
	  	if (address != "") { html = html + "<br/>" + address; }
	  	html = html + "</p>";
		if (btnplus != "") { html = html + "<p><a href='" + btnplus + "'>" + "En savoir plus" + "</a>"; }
      	GEvent.addListener(marker, 'click', function() {
      		//marker.openInfoWindowHtml(html);
			marker.openExtInfoWindow(map,"bulle_geoloc",html,{beakOffset: 3});
      	});
	  
      return marker;
    }


	// **** ZOOM SUR LA ZONE QUI CONTIENT TOUTES LES OBSERVATIONS A AFFICHER *****************************
	function zoomZoneObservations (coordonnees) {
		ecart_x = coordonnees[2] - coordonnees[0];
		centre_x = coordonnees[0] + (ecart_x / 2);
		ecart_y = coordonnees[3] - coordonnees[1];
		centre_y = coordonnees[1] + (ecart_y / 2);
		plus_grand_ecart = Math.max(ecart_x,ecart_y);
		// alert(plus_grand_ecart);
		if (plus_grand_ecart < 0.2) {
			nivzoom = 15;
		} else {
			if (plus_grand_ecart < 0.4) {
				nivzoom = 12;
			} else {
				nivzoom = 10;
			}
		}
		map.setCenter(new GLatLng(centre_x,centre_y), nivzoom);
	}

	// **** INFOBULLES MARKERS *****************************
	function close_infobulle(ref) { 
		var infobulle = document.getElementById(ref);
		infobulle.style.visibility = "hidden";
		infobulle.style.left =  -1000 + "px";
	}
	
	function open_infobulle(ref) {
		if (ref_bulle_active != null) { close_infobulle(ref_bulle_active); }
		var infobulle = document.getElementById(ref);
		infobulle.style.visibility = "visible";
		infobulle.style.left =  80 + "px";
		infobulle.style.top = 20 + "px";
		ref_bulle_active = ref;
	}
	
	// **** ZOOM SUR UN RESTO EN MODE LISTE *****************************
	function zoom_geoloc_lieu (idfiche, latitude, longitude) {
		//alert(liste_markers["ref"+idfiche]);
		//map.setCenter(new GLatLng(latitude,longitude),11);
		//point = new GLatLng(parseFloat(latitude), parseFloat(longitude));
		refmarker = "ref"+idfiche;
		
		GEvent.trigger(liste_markers[refmarker], "click"); 
		//open_infobulle(ref);
	}

