//gmap
var map = null;
var TousMesMarqueurs = [];
var markersArray=[],markersArray1=[],markersArray2=[],markersArray3=[],markersArray4=[];
var markerdynamique = null;
var marker = null;
var markers;
var cluster,cluster1,cluster2;
// on charge les coordonnées par défaut, 
var initLat100 = 49.640677937894125;
var initLng100 =-1.5780830383300781;
var initZoom100 = 14;

var initcarte=1;
var myRacineSite="http://www.mairie-tourlaville.fr";
var NomRubrique="utilitaires/cartographie";
 var urlChMark=myRacineSite+"/fr/"+NomRubrique+"/chargement_marker.asp";

// si on vient d'une fiche on zoom sur le lieu
/*
var initLatCible = 48.60510623;
var initLngCible =-1.511993408;
var initZoomCible = 14;
*/

// soit :
var initLat = initLat100;
var initLng =initLng100;
var initZoom = initZoom100;

// ou :
/*
var initLat = initLatCible;
var initLng =initLngCible;
var initZoom = initZoomCible;
*/

//<![CDATA[
	
	//**************************************************************** controles personnalisés //

function TextualZoomControl() {
}

// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object
TextualZoomControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
TextualZoomControl.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var zoomOutDiv = document.createElement("div");
  this.setButtonStyle_(zoomOutDiv);
  container.appendChild(zoomOutDiv);
  zoomOutDiv.appendChild(document.createTextNode("Zoom initial"));
  GEvent.addDomListener(zoomOutDiv, "click", function() {
    //map.zoomOut();
	map.setCenter(new GLatLng(initLat100, initLng100), initZoom100);
  });

  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_RIGHT, new GSize(10, 140));
}

// Sets the proper CSS for the given button element.
TextualZoomControl.prototype.setButtonStyle_ = function(button) {
  button.style.textDecoration = "underline";
  button.style.color = "#0000cc";
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.border = "1px solid black";
  button.style.padding = "2px";
  button.style.marginBottom = "3px";
  button.style.textAlign = "center";
  button.style.width = "4em";
  button.style.cursor = "pointer";
}

//**********************************************
	
	function load() {
						
		if (GBrowserIsCompatible()) {
//**************************************************************** Création de la carte et de ses contrôles //

								map = new GMap2(document.getElementById('map'),{mapTypes:[G_SATELLITE_MAP,G_HYBRID_MAP,G_NORMAL_MAP,G_PHYSICAL_MAP ]});

								//map.addControl(new GSmallMapControl(),new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(22,35)));
								map.addControl(new GSmallMapControl(),new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(22,35)));
								map.addControl(new GMapTypeControl());
								map.addControl(new TextualZoomControl()); // mon control perso pour retour1:1
								map.setMapType(G_PHYSICAL_MAP);
								//map.removeMapType(G_PLAN_MAP); //Permet de retirer un mode d'affichage
								map.setCenter(new GLatLng(initLat, initLng), initZoom);
								
		//****clustering*******************************************************
		function myClusterClick(args) {
	 	//alert (this.numcat)
			this.defaultClickAction=function(){
				map.setCenter(args.clusterMarker.getLatLng(), map.getBoundsZoomLevel(args.clusterMarker.clusterGroupBounds))
			map.closeInfoWindow();
				delete this.defaultClickAction;
			}
			var html='<div style="height:8em; overflow:auto; width:24em"  id="textebulle">';
			html+='<h4 class=textebulle >'+args.clusteredMarkers.length+' lieux dans cette zone :</h4>';
			html+='<a href="javascript:cluster'+this.numcat+'.defaultClickAction()" class="lienbulle" > >> Zoomer sur cette zone </a><br><br>';
			
			
			for (i=0; i<args.clusteredMarkers.length; i++) {

				html+=' > <a href="javascript:cluster'+this.numcat+'.triggerClick('+args.clusteredMarkers[i].index+')" title="cliquer pour zoomer sur ce lieu" class="listebulle" >'+args.clusteredMarkers[i].getTitle()+'</a><br />';
			}
			html+='</div>';
			//	args.clusterMarker.openInfoWindowHtml(html);
			map.openInfoWindowHtml(args.clusterMarker.getLatLng(), html);
		}
		
			//	create a ClusterMarker
			//	create a custom GIcon to use as the cluster marker icon
		var myclusterBaseIcon=new GIcon();
		//myclusterBaseIcon.image='icones/cluster.png';
		myclusterBaseIcon.iconSize=new GSize(20, 20);
		myclusterBaseIcon.iconAnchor=new GPoint(10, 10);
		myclusterBaseIcon.infoWindowAnchor=new GPoint(20, 3);
		myclusterBaseIcon.shadow='icones/shadow_cluster.png';
		myclusterBaseIcon.shadowSize=new GSize(37, 20);
		var myclusterMarkerIcon1=new GIcon(myclusterBaseIcon, myRacineSite+'/gmap/icones/cluster-blue.png');
		var myclusterMarkerIcon2=new GIcon(myclusterBaseIcon,  myRacineSite+'/gmap/icones/cluster-darkblue.png');
		var myclusterMarkerIcon3=new GIcon(myclusterBaseIcon,  myRacineSite+'/gmap/icones/cluster-green.png');
		var myclusterMarkerIcon4=new GIcon(myclusterBaseIcon,  myRacineSite+'/gmap/icones/cluster-orange.png');
		
				
cluster1=new ClusterMarker(map, {clusterMarkerTitle:'Cliquer pour voir %count lieux' , clusterMarkerClick:myClusterClick, numcat:1,clusterMarkerIcon:myclusterMarkerIcon1});
cluster2=new ClusterMarker(map, {clusterMarkerTitle:'Cliquer pour voir %count lieux' , clusterMarkerClick:myClusterClick, numcat:2,clusterMarkerIcon:myclusterMarkerIcon2});
cluster3=new ClusterMarker(map, {clusterMarkerTitle:'Cliquer pour voir %count lieux' , clusterMarkerClick:myClusterClick, numcat:3,clusterMarkerIcon:myclusterMarkerIcon3});
cluster4=new ClusterMarker(map, {clusterMarkerTitle:'Cliquer pour voir %count lieux' , clusterMarkerClick:myClusterClick, numcat:4,clusterMarkerIcon:myclusterMarkerIcon4});
			//*******************************-----------------------------------------------
	}

							// génération des markers
								var ToutesLesBalisesInput = document.getElementsByTagName('input');
								
								if(ToutesLesBalisesInput != null){
								for(var i = 0; i < ToutesLesBalisesInput.length; i++){
								if(ToutesLesBalisesInput[i].type == 'checkbox'){
								ToutesLesBalisesInput[i].checked=true // on force au chargement toutes les cases cochées
									if (ToutesLesBalisesInput[i].checked){ Envoicategorie(ToutesLesBalisesInput[i]);} // on affiche les lieux correspondants
								ToutesLesBalisesInput[i].onclick=function(){Envoicategorie(this);}

								}
								}
								}
								
								
}
// fin load

function toggleClustering() {
	cluster1.clusteringEnabled=!cluster1.clusteringEnabled;
	cluster1.refresh(true);
	cluster2.clusteringEnabled=!cluster2.clusteringEnabled;
	cluster2.refresh(true);
		cluster3.clusteringEnabled=!cluster3.clusteringEnabled;
	cluster3.refresh(true);
		cluster4.clusteringEnabled=!cluster4.clusteringEnabled;
	cluster4.refresh(true);
}
								
//****************************************************************			
function Envoicategorie(val){

//	alert(val.value)
if(val == null){return;}
var categorieselec=val.value;
				if(val.checked==true){
/*
				{"markers": [
     {"lat":48.9908338, "lng":1.717222, "html":"Ici, c\'est chez moi&nbsp;!"},
     {"lat":48.862222, "lng":2.351111, "html":"Je bosse ici."},
     {"lat":45.62, "lng":-1.03, "html":"Et l&agrave;, les vacances..."}
   ]
}
*/
// chargement au format json

			GDownloadUrl(urlChMark, function(json) {
						//var markers = eval('(' + json + ')');
						var markers = eval(json);
							var FormulaireItineraire = [];
				var latcoord = [];
				var lngcoord = [];
				var couleurfond = [];
			//var xml = GXml.parse(data);
			//	var markers = xml.documentElement.getElementsByTagName("marker");
			
			if(categorieselec=='Equipements sportifs'){
			markersArray1=[];
			}
			if(categorieselec=='Bâtiments communautaires'){
			markersArray2=[];
			}
			if(categorieselec=='Ecoles'){
			markersArray3=[];
			}
			if(categorieselec=='Travaux'){
			markersArray4=[];
			}
			//	for (var i = 0; i < markers.length; i++) {
				for(i in markers) {
				var type = markers[i].type;  // pb dans IE
				
					latcoord[i] = parseFloat(markers[i].lat);
					lngcoord[i] = parseFloat(markers[i].lng);
					couleurfond[i] = "#ffffff";
					
					/*
							if(type=='Is'){couleurfond[i] = "#6795C6";} 
							if(type=='C'){couleurfond[i] = "#0CF5F2";} 
							*/
				if(type == categorieselec){
					var point = new GLatLng(latcoord[i], lngcoord[i]);
					
					var id_fiche = markers[i].id_fiche;
					var nom = markers[i].nom;
					var CartoChapeau = markers[i].CartoChapeau;
					var CartoTexte = markers[i].CartoTexte;
					var CartoDate = markers[i].CartoDate;
					var CartoPhotoNom = markers[i].CartoPhotoNom;
					var CartoPhotoLegende = markers[i].CartoPhotoLegende;
					var CartoUrlHrefInterne = markers[i].CartoUrlHrefInterne;
					var CartoUrlLibelleInterne = markers[i].CartoUrlLibelleInterne;
					var CartoUrlHrefExterne = markers[i].CartoUrlHrefExterne;
					var CartoUrlLibelleExterne = markers[i].CartoUrlLibelleExterne;
					var CartoDocumentType = markers[i].CartoDocumentType;
					var CartoDocumentNom = markers[i].CartoDocumentNom;
					var CartoDocumentFichier = markers[i].CartoDocumentFichier;
					var CartoDocumentPoids = markers[i].CartoDocumentPoids;
					var CartoDocumentTexteAssocie = markers[i].CartoDocumentTexteAssocie;
					var imgid = markers[i].imgid;
					//alert (adresse) 

					if (imgid!="") {
					var imag= "<img src='"+UrlWebDev+"/"+NomRubrique+"/images/"+imgid+"' >"
					}
					else{
					var imag= ""
					}
					LienInterne=""
					if (CartoUrlHrefInterne!="") {
					LienInterne="<br>> <a href=\"javascript:VoirLieu(\'"+CartoUrlHrefInterne+"\');\">"+CartoUrlLibelleInterne+"</a>"
							}
					LienExterne=""
					if (CartoUrlHrefExterne!="") {
					LienExterne="<br>> <a href=\""+CartoUrlHrefExterne+"\">"+CartoUrlLibelleExterne+"</a>"
							}
					LienFichier=""
					if (CartoDocumentFichier!="") {
					LienFichier="<br>> <a href=\""+UrlWebDev+"/"+NomRubrique+"/fichiers/"+CartoDocumentFichier+"\">"+CartoDocumentNom+"</a>("+CartoDocumentType+")"
							}
			
				var infotabs = [ 
				new GInfoWindowTab("Infos", '<div style="width:300px;  text-align:center; font: 14px \'trebuchet ms\',verdana, helvetica, sans-serif;overflow:auto">' +
					'<br /><b>'+nom+'</b><br />' +CartoDate+'<br />' +CartoChapeau+imag+'<br /></div><div style="text-align:left"> '+LienInterne+''+LienExterne+LienFichier+
					'</div>'), 
				new GInfoWindowTab("Détails",'<div style="width:300px; height:300px; margin-top:8px;text-align:left; background:'+couleurfond[i]+'; font: 12px \'trebuchet ms\',verdana, helvetica, sans-serif;overflow:auto">' +
					''+CartoTexte+'<br /> '+
					'</div>')
				]; 
					

					
					var marker = createMarker(point,type,nom, i, infotabs);
					//map.addOverlay(marker);  // ne pas utiliser si clustering
					
											// si on vient d'une fiche à l'init on simule le click et on ouvre l'info bulle correspondante :
	
				if (id_ficheCible==id_fiche && initcarte==1){
							map.addOverlay(marker) // on affiche le marker sélectionné
							GEvent.trigger(marker,"click");
							initcarte=0;
						}
						
			if(type=='Equipements sportifs'){
			markersArray1.push(marker);
			} 
			if(type=='Bâtiments communautaires'){
			markersArray2.push(marker);
			} 
			
		if(type=='Ecoles'){
			markersArray3.push(marker);
			} 
			if(type=='Travaux'){
			markersArray4.push(marker);
			} 

			//cluster.fitMapToMarkers();
					
}
}
			// génération des clusters
			//cluster.removeMarkers();
			if(categorieselec=='Equipements sportifs'){
			cluster1.removeMarkers();
			cluster1.addMarkers(markersArray1);
			cluster1.refresh(true);
			} 
			if(categorieselec=='Bâtiments communautaires'){
		cluster2.removeMarkers();
			cluster2.addMarkers(markersArray2);
			cluster2.refresh(true);
			} 
						if(categorieselec=='Ecoles'){
		cluster3.removeMarkers();
			cluster3.addMarkers(markersArray3);
			cluster3.refresh(true);
			} 
						if(categorieselec=='Travaux'){
		cluster4.removeMarkers();
			cluster4.addMarkers(markersArray4);
			cluster4.refresh(true);
			} 
			
			
});
}
				
				if(val.checked==false){ <!-- Si la case est décochée ... -->
				GDownloadUrl(urlChMark, function(json) {
					//var markers = eval('(' + json + ')');
					var markers = eval(json);
				//var markers = xml.documentElement.getElementsByTagName('marker');
				//for (var i = 0; i < markers.length; i++) {
				for(i in markers) {
				var type = markers[i].type;

				if(type == categorieselec){ <!-- ... les marqueurs correspondant à la catégorie ... -->
				map.removeOverlay(TousMesMarqueurs[i]);<!-- ... sont masqués -->
			if(categorieselec=='Equipements sportifs'){
			cluster1.removeMarkers();
			markersArray1=[];
			} 
			if(categorieselec=='Bâtiments communautaires'){
			cluster2.removeMarkers();
			markersArray2=[];
			} 
						if(categorieselec=='Ecoles'){
			cluster3.removeMarkers();
			markersArray3=[];
			} 
			if(categorieselec=='Travaux'){
			cluster4.removeMarkers();
			markersArray4=[];
			} 
			//	cluster.removeMarkers();
				}
			}
		});
}

}


//**************************************************************** Fonction permettant la création du marker //
							function createMarker(point,type,nom, i, infotabs) {
								var baseIcon = new GIcon();
	baseIcon.iconSize=new GSize(28,28);
	baseIcon.shadowSize=new GSize(40,28);
	baseIcon.iconAnchor=new GPoint(9,26);
	baseIcon.infoWindowAnchor=new GPoint(5,5);
	//baseIcon.iconSize=new GSize(40,40);
	//baseIcon.shadowSize=new GSize(37,34);
	//baseIcon.iconAnchor=new GPoint(9,34);
	//baseIcon.infoWindowAnchor=new GPoint(9,2);
	baseIcon.shadow = myRacineSite+"/gmap/icones/sign_shadow.png";
	var equipementS = new GIcon(baseIcon, myRacineSite+'/gmap/icones/marker_sport.png', null);
	var equipementC = new GIcon(baseIcon, myRacineSite+'/gmap/icones/marker_equip.png', null);
	var Ecoles = new GIcon(baseIcon, myRacineSite+'/gmap/icones/marker_ecole.png', null);
	var Travaux = new GIcon(baseIcon, myRacineSite+'/gmap/icones/marker_travaux.png', null);
						if(type=='Equipements sportifs'){var icone = equipementS;}
						if(type=='Bâtiments communautaires'){var icone = equipementC;}
						if(type=='Ecoles'){var icone = Ecoles;}
						if(type=='Travaux'){var icone = Travaux;}
						
								titlemark=nom;
						  var marker = new GMarker(point,
								{icon:icone,
								title: titlemark});
						
						
						
						TousMesMarqueurs[i]=marker;
						


						GEvent.addListener(marker, 'click', function() { <!-- En cas de click sur le marqueur ... -->
						//map.setCenter(marker.getPoint(),14);
						map.setMapType(G_NORMAL_MAP);
						marklat=marker.getPoint().lat()+0.0005;
						//marklat=marker.getPoint().lat();
						marklng=marker.getPoint().lng();
							map.setCenter(new GLatLng(marklat, marklng),17); // pour décaler un peu vers le bas pour l'info bulle
							marker.openInfoWindowTabsHtml(infotabs); // pour fenetre à onglet
							//marker.openInfoWindowHtml(infotabs);
						});

							//retour à la valeur initiale on rezoom sur le point en question
							GEvent.addListener(marker, 'infowindowclose', function() {
							map.setCenter(new GLatLng(marker.getPoint().lat(), marker.getPoint().lng()), 17);
						});	
				
								return marker;
							}



    //]]>