﻿/********************************************************************************************************************************
/*                                                                Code traitant de l'affichage sur la map                                                                                                                           *
/*                                                                                                                                                                                                                                                             *
********************************************************************************************************************************/


// Verification de la compatibilite du navigateur
if (GBrowserIsCompatible()) {
	var map = null;
	var gdir = null;
	var marker = null;
	var xml = null;
	
	var TousMesMarqueurs = new Array;
	var clicked = new Array();
	
	// Fonction de chargement des donnees XML
	function loadXML(file)
	{
		GDownloadUrl(file, function(data) {
			xml = GXml.parse(data);
			if(!xml || typeof xml != 'object') 
			{
				alert("Fichier de données Invalide");
				return;
			}
		});
	}
	
	// Fonction executee au chargement de la page
	function load() 
	{	
		// Initialisation de la carte google
		map = new GMap2(document.getElementById("map_canvas"), {mapTypes:[G_NORMAL_MAP,G_SATELLITE_MAP,G_HYBRID_MAP,G_PHYSICAL_MAP]});
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GOverviewMapControl());
		map.setCenter(new GLatLng(46.84563407472693,0.5445098876953125), 10);
		
		// Initialisation du generateur d'itineraire
		gdir = new GDirections(map, document.getElementById("direction_canvas"));
		GEvent.addListener(gdir, "error", handleErrors);
		
		// Chargement de la zone representant l'agglo de chatellerault
		//var gx = new GGeoXml("capc.kml");
		//map.addOverlay(gx);
		
		// Chargement des donnees XML
		loadXML('file_new.xml');
		
		// Gestionnaire d'erreurs pour la generation d'itineraire
		function handleErrors()
		{
			if(gdir == null){return;}
		   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
			 alert("Une des adresse indiqu\u00E9e est introuvable.\nCode erreur: " + gdir.getStatus().code);
		   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
			 alert("La requ\u00EAte n'a pas pu \u00EAtre soumise.\nError code: " + gdir.getStatus().code);
		   
		   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
			 alert("Une des adresse sp\u00E9cifi\u00E9e n'est pas valide.\nCode erreur: " + gdir.getStatus().code);
			 
		   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
			 alert("La clef logiciel n'est pas valide. \nCode erreur: " + gdir.getStatus().code);

		   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
			 alert("Le format de l'adresse n'est pas valide.\nCode erreur: " + gdir.getStatus().code);
			
		   else alert("Une erreur inconnu est survenue.");
		   
		}
		
	}
	
	// Fonction execute lors de l'appui sur une des checkbox
	function EnvoiLoisir(val){
		// Verification des objets necessaire au fonctionnement de la fonction
		if(map == null){return;}
		if(val == null){return;}
		if(xml == null){return;}
		
		// Initialisation des variables contenant les informations XML
		var loisirselec=val.value;
		var point = new GLatLng(46.84563407472693,0.5445098876953125);
		var nom = "";
		var adresse = "";
		var codepostal = "";
		var ville = "";
		var telephone = "";
		var courriel = "";
		var siteweb = "";
		var type = "";
		var media = "";
		var texte = "";
		
		// Dans le cas ou une checkbox est cochee
		if(val.checked==true){
			var markers = xml.documentElement.getElementsByTagName('marker');
			for (var i = 0; i < markers.length; i++) {
				type = markers[i].getAttribute('service');				
				if(type == loisirselec){
					point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng')));
					nom = markers[i].getAttribute('site');
					adresse = markers[i].getAttribute('adresse');
					codepostal = markers[i].getAttribute('codepostal');
					ville = markers[i].getAttribute('commune');
					telephone = markers[i].getAttribute('telephone');
					courriel = markers[i].getAttribute('courriel');
					siteweb = markers[i].getAttribute('siteinternet');
					media = markers[i].getAttribute('image');
					texte = markers[i].getAttribute('texte');
					marker = CreationDuMarqueur(point, nom, adresse, codepostal, ville, telephone, courriel, siteweb, type, media, texte, i);
					// PS: si longitude et latitude non defini dans la base de donnees, plantage de internet explorer
					map.addOverlay(marker);
				}
			}			
			// Lors d'un clic sur une checkbox on genere le détail
			genMenu(loisirselec);
		}
		
		// dans le cas ou une checkbox est decochee
		if(val.checked==false){
			var markers = xml.documentElement.getElementsByTagName('marker');
			for (var i = 0; i < markers.length; i++) {
				type = markers[i].getAttribute('service');
				if(type == loisirselec){
						map.removeOverlay(TousMesMarqueurs[i]);
				}
			}
			delMenu(loisirselec);
		}	

	}
	
	// Fonction permettant de personnaliser les marqueurs (onglets, image ...)
	function CreationDuMarqueur(point, nom, adresse, codepostal, ville, telephone, courriel, siteweb, type, media, texte, i) { 
		// Verification des objets necessaire au fonctionnement de la fonction
		if (map == null) {return;}
		
		
		if(type=='Hébergement'){var fond = "hebergement";} 
		if(type=='Restauration'){var fond = "restauration";} 
		if(type=='Patrimoine et visites'){var fond = "patrimoine";} 
		if(type=='Loisirs et activités de plein air'){var fond = "loisir";}
		if(type=='Nature et Paysage'){var fond = "nature";}
		if(type=='Artisanat et terroir'){var fond = "artisanat";}
		if(type=='Informations'){var fond = "information";}
		// Onglet Principal dans google map (adresse, nom...)
		function genOnglet1(nom, adresse, codepostal, ville, telephone, courriel, siteweb, texte)
		{
			var str = null;
			str = '<div id="info"><p class="'+fond+'"><strong>'+ nom + '</strong></p>'
					+'<p>'+ adresse + ' '+ '-' + ' '
					+ codepostal + ' ' 
					+ ville + '<br/>'
					+ telephone + '<br/>'
					+ '<a href ="mailto:'+courriel+'"/>'+courriel+ '<br/>'
					+ '<a href ="http://'+siteweb+'" target="_blank"/>'+siteweb + '<br/>'
					+'</p></div>';
			return str;
		}
		
		// Onglet Itineraire dans google map
		function genOnglet2(point, nom)
		{
			var str = null;
			str = 	'<div id="info"><p class="'+fond+'"><strong>'+ nom + '</strong></p>'
					+'<p><form action="javascript:setDirection()" method="post">'
					+'<strong>D&eacute;part:</strong> '
					+'<input type="text" id="from" /><br />'
					+'<input type="hidden" id="to" value="'+nom+'@'+ point.lat() + ',' + point.lng() + '" /><br />'
					+'<input type="submit" value="Itin&eacute;raire" />'
					+'</form></p></div>';
					
			return str;
		}
		
		// Onglet detail dans google map (image)
		function genOnglet3(nom,media)
		{
			var str = null;
			if ((media != null) && (media != " "))
				str = 	'<div id="info"><p class="'+fond+'"><strong>'+ nom + '</strong></p>'
						+'<p align="center"><img src="'+ media +'" width="200" height="110"></p></div>';
			else
				str = 	'<div id="info"><p class="'+fond+'"><strong>'+ nom + '</strong></p></div>';
			return str;
		}
		
		// Onglet detail dans google map (texte)
		function genOnglet4(nom,texte)
		{
			var str = null;
			if ((texte != null) && (texte != " "))
				str = 	'<div id="info"><p class="'+fond+'"><strong>'+ nom + '</strong></p>'
						+'<p align="center">'+ texte +'</p></div>';
			else
				str = 	'<div id="info"><p class="'+fond+'"><strong>'+ nom + '</strong></p></div>';
			return str;
		}
		
		// Initialisation des graphismes des marqueurs
		var baseIcon = new GIcon();
		baseIcon.iconSize=new GSize(41,45);
		baseIcon.shadowSize=new GSize(20,22);
		baseIcon.iconAnchor=new GPoint(6,20);
		baseIcon.infoWindowAnchor=new GPoint(15,30);
		var Hebergement = new GIcon(baseIcon, 'img/carte/pic_hebergement.gif', null, 'http://labs.google.com/ridefinder/images/mm_20_shadow.png');
		var Restauration = new GIcon(baseIcon, 'img/carte/pic_resto.gif', null, 'http://labs.google.com/ridefinder/images/mm_20_shadow.png');
		var Patrimoine = new GIcon(baseIcon, 'img/carte/pic_patrimoine.gif', null, 'http://labs.google.com/ridefinder/images/mm_20_shadow.png');
		var Activites = new GIcon(baseIcon, 'img/carte/pic_loisirs.gif', null, 'http://labs.google.com/ridefinder/images/mm_20_shadow.png');
		var Nature = new GIcon(baseIcon, 'img/carte/pic_nature.gif', null, 'http://labs.google.com/ridefinder/images/mm_20_shadow.png');
		var Artisanat = new GIcon(baseIcon, 'img/carte/pic_terroir.gif', null, 'http://labs.google.com/ridefinder/images/mm_20_shadow.png');
		var Pointi = new GIcon(baseIcon, 'img/carte/pic_pointi.gif', null, 'http://labs.google.com/ridefinder/images/mm_20_shadow.png');
		if(type=='Hébergement'){var icone = Hebergement;} 
		if(type=='Restauration'){var icone = Restauration;} 
		if(type=='Patrimoine et visites'){var icone = Patrimoine;} 
		if(type=='Loisirs et activités de plein air'){var icone = Activites;}
		if(type=='Nature et Paysage'){var icone = Nature;}
		if(type=='Artisanat et terroir'){var icone = Artisanat;}
		if(type=='Informations'){var icone = Pointi;}
		
		// Creation des marqueurs
		var marker = new GMarker(point,{icon:icone, title:nom}); 
		var infotabs = [new GInfoWindowTab("Adresse", genOnglet1(nom,adresse,codepostal,ville,telephone,courriel,siteweb,texte)),
						new GInfoWindowTab("Détails", genOnglet4(nom,texte)),
						new GInfoWindowTab("Images", genOnglet3(nom,media)),
						new GInfoWindowTab("Itinéraire", genOnglet2(point, nom))];
		TousMesMarqueurs[i]=marker;
		// Listener sur ouverture de fenetre d'information
		GEvent.addListener(marker, 'infowindowopen', function() {
		map.setCenter(marker.getPoint(),15);
		}); 
		// Listener sur click sur marqueur
		GEvent.addListener(marker, 'click', function(overlay) {
			marker.openInfoWindowTabsHtml(infotabs);
		}); 
		// Listener sur fermeture de fenetre d'information
		GEvent.addListener(marker, 'infowindowclose', function() {
			var markers = xml.documentElement.getElementsByTagName('marker');
			map.setCenter(new GLatLng(46.84563407472693,0.5445098876953125), 10); 
			gdir.clear();
			
			// Parcours des balises xml
			for (var i = 0; i < markers.length; i++) {
				// Si service correspondant
				if(type == markers[i].getAttribute('service'))
				{
					TousMesMarqueurs[i].show();
				}
			}
		});
		return marker; 
	}
	
	// Creation d'itineraire
	function setDirection()
	{
		if(gdir == null){return;}
		if(marker == null){return;}
		var from = document.getElementById("from").value;
		var to = document.getElementById("to").value;
		gdir.load("from: "+from+" to: "+to, {locale: "fr_FR"});
	}
	

/********************************************************************************************************************************
*                                                                     Code de la recherche affinee                                                                                                                                       *
*                                                                                                                                                                                                                                                              *
********************************************************************************************************************************/	

	
	// Eneleve les doublons dans un tableau
	function Doublons(TabInit){
		NvTab= new Array();
		var q=0;
		var LnChaine= TabInit.length;
		 for(x=0;x<LnChaine;x++)
			{
			for(i=0;i<LnChaine;i++)
				{
				if(TabInit[x]==  TabInit[i] && x!=i) TabInit[i]='faux';
				}
			if(TabInit[x]!='faux'){  NvTab[q] = TabInit[x]; q++}
			}
		return NvTab;
	}
	
	// Generation du menu de recherche affiner par categorie
	function genMenu(type)
	{
		// Initialisation des variables
		var categories = new Array();
		var menu = document.getElementById("listeCategorie");
		var markers = xml.documentElement.getElementsByTagName('marker');
		
		// Pour chaque balise de la base de donnee correspondant au service a affiner on recupere sa categorie
		for (var i = 0; i < markers.length; i++) {
			if (type == markers[i].getAttribute('service'))
				categories.push(markers[i].getAttribute('categorie'));
		}
		// Trie de la categorie avec enlevement des doublons
		categories = Doublons(categories.sort());
		
		if(!document.getElementById(type.substr(0,2)))
			menu.innerHTML += "<div id=\""+type.substr(0,2)+"\"></div>";
			
		menu = document.getElementById(type.substr(0,2));
		
		// Generation du code HTML
		if(type=='Hébergement'){			
			menu.innerHTML = "<span class=\"Lieu\">Hébergement</span><br /><img src=\"img/carte/ligne.jpg\" width=\"240\" height=\"22\" /><br />";
		} 
		if(type=='Restauration'){
			menu.innerHTML = "<span class=\"Lieu\">Restauration</span><br /><img src=\"img/carte/ligne.jpg\" width=\"240\" height=\"22\" /><br />";
		} 
		if(type=='Patrimoine et visites'){
			menu.innerHTML = "<span class=\"Lieu\">Patrimoine et visites</span><br /><img src=\"img/carte/ligne.jpg\" width=\"240\" height=\"22\" /><br />";		
		} 
		if(type=='Loisirs et activités de plein air'){
			menu.innerHTML = "<span class=\"Lieu\">Loisirs et activités de plein air</span><br /><img src=\"img/carte/ligne.jpg\" width=\"240\" height=\"22\" /><br />";		
		}
		if(type=='Nature et Paysage'){
			menu.innerHTML = "<span class=\"Lieu\">Nature et Paysage</span><br /><img src=\"img/carte/ligne.jpg\" width=\"240\" height=\"22\" /><br />";		
		}
		if(type=='Artisanat et terroir'){
			menu.innerHTML = "<span class=\"Lieu\">Artisanat et terroir</span><br /><img src=\"img/carte/ligne.jpg\" width=\"240\" height=\"22\" /><br />";		
		}
		if(type=='Informations'){
			menu.innerHTML = "<span class=\"Lieu\">Points et informations</span><br /><img src=\"img/carte/ligne.jpg\" width=\"240\" height=\"22\" /><br />";		
		}
		
		for(var i = 0; i<categories.length; i++)
		{
			// initialisation du tableau permettant de savoir si une categorie a ete cliquer
			var index = categories[i].substr(0,1)+i;
			clicked[index] = false;
			// liens vers la generation du menu avec noms
			menu.innerHTML += 	"<a href=\"javascript:genSubMenu('"+type.replace(/\'/, "\\'")+"','"+categories[i].replace(/\'/, "\\'")+"','"+i+"');\" class=\"GroupeLieu\">"+categories[i]+"</a>";
			menu.innerHTML += "<div id=\""+categories[i].substr(0,1)+i+"\"></div>";
		}
		menu.innerHTML += "<img src=\"img/carte/ligne.jpg\" width=\"240\" height=\"22\" /><br />";
	}
	
	// Generation du menu de recherche affiner avec noms
	function genSubMenu(type, categ, i)
	{
		// Recuperation de l'emplacement ou afficher les noms
		var menu = document.getElementById(categ.substr(0,1)+i);
		var index = categ.substr(0,1)+i;
		
		// Si premier clique sur categorie
		// On affiche les sous categories
		if ( !clicked[index] )
		{
			// Initialisation des variables
			var noms = new Array();
			var markers = xml.documentElement.getElementsByTagName('marker');
			
			// Pour chaque balise de la base de donnee correspondant au service et a la categorie a affiner, on recupere le nom
			for (var i = 0; i < markers.length; i++) {
				if (type == markers[i].getAttribute('service'))
				{
					if (categ == markers[i].getAttribute('categorie'))
						noms.push(markers[i].getAttribute('site'));
				}
			}
			// Trie des noms avec enlevement des doublons
			noms = Doublons(noms.sort());
			
			// Generation du HTML
			menu.innerHTML = "";
			for(var i = 0; i<noms.length; i++)
			{
				menu.innerHTML += 	"<a href=\"javascript:EnvoiAffiner('"+type.replace(/\'/, "\\'")+"','"+categ.replace(/\'/, "\\'")+"','"+noms[i].replace(/\'/, "\\'")+"');\" class=\"Lieu\">"+noms[i]+"</a><br />";
			}
			
			menu.innerHTML += "<img src=\"img/carte/ligne.jpg\" width=\"240\" height=\"22\" /><br />";
			
			clicked[index] = true;
		}
		// Sinon on efface les sous categories
		else
		{
			var menu = document.getElementById(categ.substr(0,1)+i);
			menu.innerHTML = "";
			clicked[index] = false;
		}
	}
	
	// Affichage des marqueurs en fonction du type, de la categorie et du nom
	function EnvoiAffiner(type,categ,nom)
	{
		if(map == null){return;}
		if(xml == null){return;}
		var point = "";
		var adresse = "";
		var codepostal = "";
		var ville = "";
		var telephone = "";
		var courriel = "";
		var siteweb = "";
		var media = "";
		
		var markers = xml.documentElement.getElementsByTagName('marker');
		// Parcours des balises xml
		for (var i = 0; i < markers.length; i++) {
			// Si service correspondant
			if(type == markers[i].getAttribute('service'))
			{
				// Effacement des marqueurs deja places
				TousMesMarqueurs[i].hide();
				// Si categorie correspondante
				if(categ == markers[i].getAttribute('categorie')){
					// Si nom correspondant
					if(nom == markers[i].getAttribute('site')){
						// Affichage du ou des marqueurs
						TousMesMarqueurs[i].show();
						GEvent.trigger(TousMesMarqueurs[i], "click");
					}
				}
			}
		}
	}
	
	// Effacement du menu
	function delMenu(type)
	{
		var menu = document.getElementById(type.substr(0,2));
		menu.innerHTML = "";
	}
}