/*#############################
## Gestion du menu de la map ##
#############################*/

/*
Création des marqueurs pour l'affichage sur la map
*/
greenIcon = new GIcon(G_DEFAULT_ICON);
greenIcon.iconSize = new GSize(32,32);
greenIcon.image = "ressources/icones/green-dot.png";
greenIcon.shadow = "ressources/icones/shadow50.png";
whiteIcon = new GIcon(G_DEFAULT_ICON);
whiteIcon.iconSize = new GSize(32,32);
whiteIcon.image = "ressources/icones/white-dot.png";
whiteIcon.shadow = "ressources/icones/shadow50.png";
redIcon = new GIcon(G_DEFAULT_ICON);
redIcon.iconSize = new GSize(32,32);
redIcon.image = "ressources/icones/red-dot.png";
redIcon.shadow = "ressources/icones/shadow50.png";
blueIcon = new GIcon(G_DEFAULT_ICON);
blueIcon.iconSize = new GSize(32,32);
blueIcon.image = "ressources/icones/blue-dot.png";
blueIcon.shadow = "ressources/icones/shadow50.png";
yellowIcon = new GIcon(G_DEFAULT_ICON);
yellowIcon.iconSize = new GSize(32,32);
yellowIcon.image = "ressources/icones/yellow-dot.png";
yellowIcon.shadow = "ressources/icones/shadow50.png";
mauveIcon = new GIcon(G_DEFAULT_ICON);
mauveIcon.iconSize = new GSize(32,32);
mauveIcon.image = "ressources/icones/mauve-dot.png";
mauveIcon.shadow = "ressources/icones/shadow50.png";
greyIcon = new GIcon(G_DEFAULT_ICON);
greyIcon.iconSize = new GSize(32,32);
greyIcon.image = "ressources/icones/grey-dot.png";
greyIcon.shadow = "ressources/icones/shadow50.png";
greenIcon_F = new GIcon(G_DEFAULT_ICON);
greenIcon_F.iconSize = new GSize(32,32);
greenIcon_F.image = "ressources/icones/green-fdot.png";
greenIcon_F.shadow = "ressources/icones/shadow50.png";
whiteIcon_F = new GIcon(G_DEFAULT_ICON);
whiteIcon_F.iconSize = new GSize(32,32);
whiteIcon_F.image = "ressources/icones/white-fdot.png";
whiteIcon_F.shadow = "ressources/icones/shadow50.png";
redIcon_F = new GIcon(G_DEFAULT_ICON);
redIcon_F.iconSize = new GSize(32,32);
redIcon_F.image = "ressources/icones/red-fdot.png";
redIcon_F.shadow = "ressources/icones/shadow50.png";
blueIcon_F = new GIcon(G_DEFAULT_ICON);
blueIcon_F.iconSize = new GSize(32,32);
blueIcon_F.image = "ressources/icones/blue-fdot.png";
blueIcon_F.shadow = "ressources/icones/shadow50.png";
yellowIcon_F = new GIcon(G_DEFAULT_ICON);
yellowIcon_F.iconSize = new GSize(32,32);
yellowIcon_F.image = "ressources/icones/yellow-fdot.png";
yellowIcon_F.shadow = "ressources/icones/shadow50.png";
mauveIcon_F = new GIcon(G_DEFAULT_ICON);
mauveIcon_F.iconSize = new GSize(32,32);
mauveIcon_F.image = "ressources/icones/mauve-fdot.png";
mauveIcon_F.shadow = "ressources/icones/shadow50.png";
greyIcon_F = new GIcon(G_DEFAULT_ICON);
greyIcon_F.iconSize = new GSize(32,32);
greyIcon_F.image = "ressources/icones/grey-fdot.png";
greyIcon_F.shadow = "ressources/icones/shadow50.png";
greenIconC = new GIcon(G_DEFAULT_ICON);
greenIconC.iconSize = new GSize(32,44);
greenIconC.image = "ressources/icones/green-cdot.png";
greenIconC.shadow = "ressources/icones/shadow50.png";
whiteIconC = new GIcon(G_DEFAULT_ICON);
whiteIconC.iconSize = new GSize(32,44);
whiteIconC.image = "ressources/icones/white-cdot.png";
whiteIconC.shadow = "ressources/icones/shadow50.png";
redIconC = new GIcon(G_DEFAULT_ICON);
redIconC.iconSize = new GSize(32,44);
redIconC.image = "ressources/icones/red-cdot.png";
redIconC.shadow = "ressources/icones/shadow50.png";
blueIconC = new GIcon(G_DEFAULT_ICON);
blueIconC.iconSize = new GSize(32,44);
blueIconC.image = "ressources/icones/blue-cdot.png";
blueIconC.shadow = "ressources/icones/shadow50.png";
yellowIconC = new GIcon(G_DEFAULT_ICON);
yellowIconC.iconSize = new GSize(32,44);
yellowIconC.image = "ressources/icones/yellow-cdot.png";
yellowIconC.shadow = "ressources/icones/shadow50.png";
mauveIconC = new GIcon(G_DEFAULT_ICON);
mauveIconC.iconSize = new GSize(32,44);
mauveIconC.image = "ressources/icones/mauve-cdot.png";
mauveIconC.shadow = "ressources/icones/shadow50.png";
greyIconC = new GIcon(G_DEFAULT_ICON);
greyIconC.iconSize = new GSize(32,44);
greyIconC.image = "ressources/icones/grey-cdot.png";
greyIconC.shadow = "ressources/icones/shadow50.png";
greenIcon_FC = new GIcon(G_DEFAULT_ICON);
greenIcon_FC.iconSize = new GSize(32,44);
greenIcon_FC.image = "ressources/icones/green-fcdot.png";
greenIcon_FC.shadow = "ressources/icones/shadow50.png";
whiteIcon_FC = new GIcon(G_DEFAULT_ICON);
whiteIcon_FC.iconSize = new GSize(32,44);
whiteIcon_FC.image = "ressources/icones/white-fcdot.png";
whiteIcon_FC.shadow = "ressources/icones/shadow50.png";
redIcon_FC = new GIcon(G_DEFAULT_ICON);
redIcon_FC.iconSize = new GSize(32,44);
redIcon_FC.image = "ressources/icones/red-fcdot.png";
redIcon_FC.shadow = "ressources/icones/shadow50.png";
blueIcon_FC = new GIcon(G_DEFAULT_ICON);
blueIcon_FC.iconSize = new GSize(32,44);
blueIcon_FC.image = "ressources/icones/blue-fcdot.png";
blueIcon_FC.shadow = "ressources/icones/shadow50.png";
yellowIcon_FC = new GIcon(G_DEFAULT_ICON);
yellowIcon_FC.iconSize = new GSize(32,44);
yellowIcon_FC.image = "ressources/icones/yellow-fcdot.png";
yellowIcon_FC.shadow = "ressources/icones/shadow50.png";
mauveIcon_FC = new GIcon(G_DEFAULT_ICON);
mauveIcon_FC.iconSize = new GSize(32,44);
mauveIcon_FC.image = "ressources/icones/mauve-fcdot.png";
mauveIcon_FC.shadow = "ressources/icones/shadow50.png";
greyIcon_FC = new GIcon(G_DEFAULT_ICON);
greyIcon_FC.iconSize = new GSize(32,44);
greyIcon_FC.image = "ressources/icones/grey-fcdot.png";
greyIcon_FC.shadow = "ressources/icones/shadow50.png";

/*
->Affiche la map selon les infos contenues dans JSON
->lance printMarkers
->Ajout le contenu de liste_resume (la liste des professions, assos...) au div concerné
->loadMenuProfessions
->le booléen boolRecherche permet de savoir si on doit ou pas supprimer les résultats de la recherche
*/
function printMap(json, boolRecherche){
	zone = json.type;
	idAffichage = json.idAffichage;
	var lat = Number(json.lat);
	var lng = Number(json.lng);
	var point = new GLatLng(lat,lng);
	map = new GMap2(document.getElementById("contain_map"));
	$("#contain_map").attr('class','done');
	map.setMapType(G_HYBRID_MAP);
	map.addControl(new GMapTypeControl());
	map.addControl(new GScaleControl());
	map.addControl(new GLargeMapControl());
	map.enableContinuousZoom();
	arrayMarkers = new Array();
	if(zone == 'commune'){
		map.setCenter(point, 15);
	}else if(zone == 'departement'){
		map.setCenter(point, 9);
	}else if(zone == 'region'){
		map.setCenter(point, 8);
	}else if(zone == 'pays'){
		map.setCenter(point, 6);
	}
	if(json.boucle==0){
		printMarkers(json);
		printMapEnd(json.nombre_markers, boolRecherche);	
	}else{
		$.facebox('<div id="progresstext">'+ChargementPoint+'</div><div class="progressbar" id="progressbar">'+ChargementEnCourt+'</div>','loader_points');
		printMarkers(json);
		boucleProfession(json.boucle,json.nombre_markers,'map', boolRecherche);
	}
	$("#showOn").html(json.texte);//Texte spécifiant ce que l'on voit actuellement
	$("#type").html(json.affiche);
	return true;
}//printMap

/*
->Fin de la fonction printMap
->executée par boucleProfession()
->Permet d'executer le code APRES l'execution de boucleProfession
*/
function printMapEnd(nombre_markers,boolRecherche){
	$.post("inc/ajax/liste_resume.php5",
		   function(reponse){
			  $("#resume_2").html(reponse);
		   });//post
	showResume('menuresume_1');
	var id = $("#md_contenu .actif").attr('id');
	var splitId = id.split('_');
	loadInfoMenu(splitId[1]);
	loadMenuProfessions();
	$("#nb_points").html(nombre_markers);
	if(boolRecherche!=true){
		$("#form_recherche #complement_recherche").attr('value','');
		$("#form_recherche #texte_recherche").attr('value','');
		$("#resultat_recherche").empty();
		$("#champs_recherche").show();//On réinitialise les résultats de recherche pour éviter les bugs (ex : affichage mairie de castelnau après avoir changé de ville)
		$("#menu_recherche").css('display','none');
	}
	boundsMap();
	return true;
}//printMapEnd

/*
->Recentre la map selon les markers affichés
->executée par showProfession()
->Vérifie le zoom, et dézoome si nécessaire
*/
function boundsMap(){
	var bounds = new GLatLngBounds();
	for(var i=0;i<arrayMarkers.length;i++){
		if(arrayMarkers[i].isHidden()==false){
			bounds.extend(arrayMarkers[i].point);
		}
	}//for
	var zMap = map.getZoom();
	var zBounds = map.getBoundsZoomLevel(bounds);
	var zo = zBounds-1;
	if(arrayMarkers.length>=1){
		if(zMap>=zBounds){
			map.setZoom(zo);
		}
		map.panTo(bounds.getCenter());
	}
	return true;
}//boundsMap

/*
->Crée arrayMarkers -> Tableau contenant tout les marqueurs affichés sur la map
->lance createMarker()
->Recentre la carte et redéfinis le zoom selon la position de tout les marqueurs (barycentre)
*/
function printMarkers(json){
	for(var i=0;i<json.pointeurs.length;i++){
		var point = new GLatLng(json.pointeurs[i].lat, json.pointeurs[i].lng);
		var marker = createMarker(point, json.pointeurs[i]);
		map.addOverlay(marker);
		arrayMarkers.push(marker);
	}
	return true;
}//printMarkers

/*
->Crée un marqueur selon les coodonnées de 'point' et les infos contenues dans 'json'
->ajoute un listener au marqueur sur l'évènement 'click' => loadFiche
*/
function createMarker(point, json) {
	var iconParam = 'icon:'+json.icon;
	if(json.fiche != 0){
		iconParam = iconParam+'_F';
	}
	var markerOptions = eval(iconParam);
	var marker = new GMarker(point,markerOptions);
	marker.point = point;
	marker.idFiche = json.fiche;
	marker.id = json.id;
	marker.icon = json.icon;
	marker.profession = json.profession;
	marker.id_profession = json.id_profession;
	marker.nom = json.nom;
	marker.type = json.type;
	marker.id_type = json.id_type;
	marker.etat = json.etat;
	marker.test = json.test;
	marker.site = json.site;
	GEvent.addListener(marker, "click", function() {
			loadFiche(marker.idFiche,marker.id);
	});
  return marker;
}//createMarker

/*
->Vérifie la couleur de chaque marqueur contenu dans arrayMarkers selon le tableau listMarkers
->Lance loadInfoMenu()
*/
function verifMarkers(listMarkers){
	var taille = arrayMarkers.length;
	for(var i=0;i<taille;i++){
		if(listMarkers[i]){
			if(arrayMarkers[i].icon != listMarkers[i].icon){
				map.removeOverlay(arrayMarkers[i]);
				map.addOverlay(listMarkers[i]);
				if(arrayMarkers[i].isHidden()==true){
					listMarkers[i].hide();
				}
				arrayMarkers[i] = listMarkers[i];
			}
		}
	}
	//On recharge le résumé pour y apporter les modifs
	var resumePart = $(".menuResume_actif").attr('id');
	showResume(resumePart);
}//verifMarkers

/*
->Cache tout les div de class .resumePart de l'onglet Résumé du menu droit
->Affiche le div id 'resumePart'
->Definit comme actif (.menuResume_actif) le lien menant au div id 'resumePart'
->ou Définit un style css
*/
function showResume(resumePart){
   	var id = resumePart.substring(4,12);
	$(".resumePart").hide();
	$("#"+id).show();
	$("#menuResume li").each(function(){
				$(this).attr('class','menuResume');
									  });
	$("#menu"+id).attr('class','menuResume_actif');
	if(id=='resume_1'){
		var reponse = loadResume();
		$("#resume_1 #dot_vert").text(reponse.vert);
		$("#resume_1 #dot_rouge").text(reponse.rouge);
		$("#resume_1 #dot_bleu").text(reponse.bleu);
		$("#resume_1 #dot_jaune").text(reponse.jaune);
		$("#resume_1 #dot_mauve").text(reponse.mauve);
		$("#resume_1 #dot_blanc").text(reponse.blanc);
	}
}

/*
->Affiche tout les marqueurs dont l'icone est 'icon'
*/
function showMarkers(icon){
	for(var i=0;i<arrayMarkers.length;i++){
		if(arrayMarkers[i].icon == icon){
			arrayMarkers[i].show();
		}
	}
}//showMarkers

/*
->Cache tout les marqueurs dont l'icone est 'icon'
*/
function hideMarkers(icon){
	for(var i=0;i<arrayMarkers.length;i++){
		if(arrayMarkers[i].icon == icon){
			arrayMarkers[i].hide();
		}
	}
}//hideMarkers

/*
->Montre tout les marqueurs dont le type est 'type' (administration, commerce, ...)
*/
function showType(id_type){
	var arrayID = id_type.split('_');
	var id = arrayID[1];
	var taille = arrayMarkers.length;
	for(var i=0;i<taille;i++){
		if(arrayMarkers[i].id_type == id){
			arrayMarkers[i].show();
		}
	}
}//showType
/*
->Cache tout les marqueurs dont le type est 'type' (administration, commerce, ...)
*/
function hideType(id_type){
	var arrayID = id_type.split('_');
	var id = arrayID[1];
	var taille = arrayMarkers.length;
	for(var i=0;i<taille;i++){
		if(arrayMarkers[i].id_type == id){
			arrayMarkers[i].hide();
		}
	}
}//hideType

/*
->Affiche la profession d'id id_profession ou le type id_type ou le mélange des deux
->Si l'onglet resumé est actif on le recharge
->Lance boundsMap()
*/
function showProfession(data){
	var splitData = data.split('_');
	var id_profession = splitData[0];
	var id_type = splitData[1];
	id_profession = id_profession=='all' ? 0 : id_profession;
	id_type = id_type=='all' ? 0 : id_type;
	map.clearOverlays();
	arrayMarkers = new Array();
	//On temporarise le chargement des marqueurs
	$.post("inc/ajax/load_profession.php5",
	   {id_profession : id_profession, id_type : id_type},
	   function (reponse){
			//removeFromMap('marker');
			var json = eval('('+reponse+')');
			$("#showOn").html(json.texte);//Texte spécifiant ce que l'on voit actuellement
			if(json.boucle==0){
				printMarkers(json);
				showProfessionEnd(json.nombre_markers);
			}else{
				$.facebox('<div id="progresstext">'+ChargementPoint+'</div><div class="progressbar" id="progressbar">'+ChargementEnCourt+'</div>','loader_points');
				printMarkers(json);
				boucleProfession(json.boucle,json.nombre_markers,'profession');
			}
	   }//function
	);//post
}//showProfession

function showProfessionEnd(nombre_markers){
	$("#nb_points").html(nombre_markers);//Texte spécifiant le nombre de marker
	var resumePart = $(".menuResume_actif").attr('id');
	showResume(resumePart);
	boundsMap();
	return true;
}

/*
->
*/
function boucleProfession(boucle,nombre_markers,callback, boolRecherche){
	var test = $("#facebox").css('display');
	if(test=='block'){
		$.post("inc/ajax/load_profession.php5",
			{boucle : boucle},
			function(reponse){
				var json = eval('('+reponse+')');
				printMarkers(json);
			}
		);//post
		$('.progressbar').progression({ 
			Current: (boucle+1)*20,
			Background: '#000',
			TextColor : '#fff',
			aBackgroundImg:'ressources/progression.png',
			Maximum: nombre_markers
		});
		var nombreactuel = (boucle*20)-1;
		if(nombreactuel<nombre_markers){
			var newboucle = boucle+1;
			setTimeout("boucleProfession("+newboucle+","+nombre_markers+",'"+callback+"',"+boolRecherche+")",100);
		}else{
			if(callback=='map'){
				printMapEnd(nombre_markers, boolRecherche);
			}else if(callback=='profession'){
				showProfessionEnd(nombre_markers);
			}
			jQuery(document).trigger('close.facebox');
			return true;
		}
	}else{
		if(callback=='map'){
			printMapEnd(nombre_markers, boolRecherche);
		}else if(callback=='profession'){
			showProfessionEnd(nombre_markers, boolRecherche);
		}
	}
}//boucleProfession

/*
->Affiche le marker id
->Si l'onglet resumé est actif on le recharge
->Lance boundsMap()
*/

function afficheMarker(id){
	$.post("inc/ajax/load_marker.php5",
		   {id : id},
		   function (reponse){
			   	var json = eval('('+reponse+')');
				//showProfession(json.pointeurs[0].id_profession+'_all');
				loadFiche(json.pointeurs[0].fiche,json.pointeurs[0].id);
		   }
	);//post
	var resumePart = $(".menuResume_actif").attr('id');
	showResume(resumePart);
	boundsMap();//Recentre la map
}//showProfession

/*
->Change les valeurs de la session pour permettre l'affichage des points
->Lancée par les clics après une recherche
*/
function afficheMapMarker(id){
	$.post("inc/ajax/affichage.php5",
		   {id_point : id, marker : false}
	);//post
}//afficheMapMarker

/*
->supprime le paramètre envoyé de l'instance map
*/
function removeFromMap(param){
	if(param=='marker'){
		var taille = arrayMarkers.length;
		for(var i=0;i<taille;i++){
			map.removeOverlay(arrayMarkers[i]);
		}
	}
}//removeFromMap


/*################################
## Gestion du menu des communes ##
################################*/

/*
->Exécutée par un 'change' du menu des communes
->Executes ajaxMenu
*/
function majInput(e,valeurPrec){
	var valeur = e.attr('value');
	var idElement = e.attr('id');
	ajaxMenu(idElement,valeur,valeurPrec);
	$("#autocomplete_commune").attr('value','');//On vide le champ d'auto-complétion pour éviter à l'utilisateur un doute sur la ville affichée
}//majInput

/*#########################
## Gestion du menu droit ##
#########################*/

/*
->Affiche idInfo dans le menu droit:
supprime la classe 'actif' des onglets
rajoute la class 'actif' à l'onglet correspondant à 'idInfo'
cache tout les div de class 'panel'
affiche le div id 'idInfo'
--> Si idInfo = fiche => 
					on affiche la réponse en cas d'aucun marker choisi
					si idMarker est défini, on cache le div noMarker, et on affiche les infos
*/
function loadInfoMenu(idInfo,idMarker,json){
	$("#liste_droit li").removeClass();
	$("#md_contenu .actif").each(function(){
		$(this).fadeOut("slow", function(){
			$("#md_contenu .actif").addClass('panel');
			$("#md_contenu .panel").each(function(){ $(this).hide(); });
			$("#"+idInfo).addClass('actif');
			if(idInfo == 'fiche'){
				for(var i=0;i<arrayMarkers.length;i++){
					if(arrayMarkers[i].flag===true){
						var icon = arrayMarkers[i].icon;
						if(arrayMarkers[i].idFiche != 0){
							icon = icon+'_F';
						}
						arrayMarkers[i].setImage(eval(icon+'.image'));
						arrayMarkers[i].flag = false;
					}
				}
				
				$("#Marker").hide();
				if($("#noMarker").attr('class')!='fiche'){
					$("#noMarker").show();
				}
				if(idMarker){
					$("#noMarker").hide();
					$("#Marker").show();
					$("#noMarker").attr('class','fiche'); //Si une fiche a été vue, le div noMarker ne s'affichera plus, pour qu'on voit la dernière fiche vue
					$("#Marker tr").each(function(){
						$(this).hide();
												  });//each
					for(var i=0;i<arrayMarkers.length;i++){
						if(arrayMarkers[i].id == idMarker){
							var t = arrayMarkers[i].id_profession;
							arrayMarkers[i].flag = true;
							var icon = arrayMarkers[i].icon;
							if(arrayMarkers[i].idFiche != 0){
								icon = icon+'_F';
							}
							icon = icon+'C';
							arrayMarkers[i].setImage(eval(icon+'.image'));
							$("#nomMarker th").html(arrayMarkers[i].nom);
							$("#nomMarker").show();
							$("#typeMarker span").html(arrayMarkers[i].type);
							$("#typeMarker").show();
							$("#professionMarker span").html(arrayMarkers[i].profession);
							$("#professionMarker").show();
							$("#lienProfMarker").show();
							$("#lienProfMarker a").click(function(){
								showProfession(t+'_all');
								return false;
							});//click
							/*if(arrayMarkers[i].icon == 'mauveIcon' || arrayMarkers[i].icon == 'mauveIcon_F'){
								var horaire = InfoMenuAucuneInfo;
							}else{*/
								var matin = json.horaires.matin;
								var aprem = json.horaires.aprem;
								if(json.horaires.ouvert==1){
									if(json.horaires.ouvert_24 != null){
										var horaire = json.horaires.ouvert_24;
									}else if(json.horaires.journee != null){
										var horaire = json.horaires.journee;
									}else{
										var horaire = matin + ' <br /> '+ aprem;
									}
								}else if(json.horaires.ferme==1){
									var horaire = InfoMenuFerme;
								}else if(json.horaires.aucun==1){
									var horaire = InfoMenuAucuneInfo;
								}
							//}
							$("#horaireMarker span").html(horaire);
							$("#horaireMarker").show();
							if(arrayMarkers[i].idFiche != 0){
								for(prop in json.fiche){
									if(json.fiche[prop] != '' && prop != 'id_photo' && prop != 'promo' && prop != 'adresse_site'){
										if(prop == 'telephone' || prop == 'fax'){
											var valeur = json.fiche[prop];
										}else if(prop == 'handicape'){
											var valeur = json.fiche[prop] == 1 ? InfoMenuOui : InfoMenuNon;
										}else{
											var valeur = json.fiche[prop];
										}
										$("#"+prop+"Marker span").html(valeur);
										$("#"+prop+"Marker").show();
									}else if(prop == 'id_photo' && json.fiche[prop] != '0'){
										$("#photoMarker td a").attr('href','ressources/clients/'+json.photos[0]);
										$("#photoMarker td a").attr('rel','facebox');
										$("#photoMarker td img").attr('src','ressources/clients/miniatures/'+json.photos[0]);
										$("#photoMarker").show();
									}else if(prop == 'promo' && json.fiche[prop] != null){
										var promo = json.fiche[prop];
		
										$("#promoMarker td").html('<p>'+PromoEnCours+'</p>');
										$("#promoMarker").show();
									}
								}
								$("#ficheMarker .facebox").attr('href',json.fiche['adresseFiche']+'_inc.html');
								$("#ficheMarker .facebox").attr('rel','facebox[.plein_ecran]');
								$("#ficheMarker .facebox").attr('title',arrayMarkers[i].nom);
								$("#ficheMarker").show(); //Affiche le lien pour la popup like
							}else{
								$("#ficheMarker").hide(); //Cache le lien pour la popup like
							}
						}
					}//for
				}else if($("#noMarker").attr('class')=='fiche'){//Si aucun idMarker n'a été envoyé, on affiche la dernière fiche demandée
					$("#Marker").show();
				}
			}//fin if(idInfo=='fiche')
			$("#md_contenu #div_"+idInfo).fadeIn("slow");			   
		});//fadeOut
	});//each
}//loadInfoMenu

function loadResume(){
	var markerCount 	= new Object();
	markerCount.vert 	= 0;
	markerCount.rouge 	= 0;
	markerCount.bleu 	= 0;
	markerCount.jaune 	= 0;
	markerCount.mauve 	= 0;
	markerCount.blanc 	= 0;
	
	for(var i=0; i<arrayMarkers.length; i++){
		//On vérifie si le marker est affiché, s'il ne l'est pas on vérifie si il correspond à ce que le visiteur demande à afficher
		if(arrayMarkers[i].icon == 'redIcon' || arrayMarkers[i].icon == 'redIcon_F'){
			markerCount.rouge++;
		}else if(arrayMarkers[i].icon == 'blueIcon' || arrayMarkers[i].icon == 'blueIcon_F'){
			markerCount.bleu++;
		}else if(arrayMarkers[i].icon == 'yellowIcon' || arrayMarkers[i].icon == 'yellowIcon_F'){
			markerCount.jaune++;
		}else if(arrayMarkers[i].icon == 'greenIcon' || arrayMarkers[i].icon == 'greenIcon_F'){
			markerCount.vert++;
		}else if(arrayMarkers[i].icon == 'whiteIcon' || arrayMarkers[i].icon == 'whiteIcon_F'){
			markerCount.blanc++;
		}else if(arrayMarkers[i].icon == 'mauveIcon' || arrayMarkers[i].icon == 'mauveIcon_F'){
			markerCount.mauve++;
		}
	}
	return markerCount;
}//loadResume

/*#####################
## Les requetes AJAX ##
#####################*/

function loadMenuProfessions(){
	$("#msg_erreur_recherche").remove();
	$.post("inc/ajax/liste_professions.php5",
		   function(reponse){
			   $("#mb_contenu").empty();
			   $("#mb_contenu").append(reponse);
			   
				$(".lienProfessions").each(function(){
					$(this).click(function(){
						showProfession($(this).attr('id'));
						return false;
					});//click
				});//Listener sur les liens Professions du footer
		   });
}//loadMenuProfession


/*
->RechercheCount
->Lance la recherche sur inc/ajax/recherche.php5
->Si plusieurs professions sont retournées, ouvre une popup proposant des checkbox pour choisir quelles professions afficher
->Si une seule profession est trouvée renvoie sur la page carte.php5 avec les paramètres nécessaires pour afficher les résultats sur la carte et dans la partie des résultats de recherche
?->Si le lieu (complément de recherche) n'existe pas dans la BDD, propose des choix qui ressemble 
*/
function rechercheCount(recherche, complement){
	jQuery(document).trigger('close.facebox');
	$("#msg_erreur_recherche").remove();
	if(recherche != '' && recherche.length>=3){
		$("#loader_recherche").css('padding','35px');
		$("#loader_recherche").css('margin-top','15px');
		$("#loader_recherche").append('<div style="text-align:center"><img src="ressources/spinner.gif" /></div>');
		$.post("inc/ajax/recherche2.php5?action=count",
			   {recherche : recherche, complement : complement},
			   function(json){
				   	json = eval('('+json+')');
					//Si plusieurs localisations sont retournées :
					if(json.localisations==1){
						$.facebox('<div id="popup_recherche" class="popup_recherche"></div>','popup_recherche');
						$(".popup_recherche").append('<p>'+PreciserRecherche+'</p>');
						$(".popup_recherche").append('<div id="popup_localisations" style="margin-left:10%; width:80%; float=\'left\'"></div>');
						$(".popup_recherche #popup_localisations").append('<form id="form_localisations" name="form_localisations" method="post"></form>');
						for(var i=0;i<json.lieux.length;i++){
							$(".popup_recherche #form_localisations").append("<input type=\"radio\" name='lieu' value='"+json.lieux[i].zone+"_"+json.lieux[i].id+"' />"+json.lieux[i].nom+" <br />");
						}
						$(".popup_recherche #form_localisations").append('<input type="hidden" id="texte_recherche" name="texte_recherche" value="'+json.texte_recherche+'" />');
						$(".popup_recherche #form_localisations").append('<br /> <input type="submit" value="'+Valider+'" />');
						$(".popup_recherche #form_localisations").submit(function(){
							jQuery(document).trigger('close.facebox');
							var texte = $(".popup_recherche #form_localisations #texte_recherche").attr('value');
							var lieu = $(".popup_recherche #form_localisations input[@type=radio]:checked").attr('value');
							rechercheCount(texte,lieu);
							return false;
						});//submit
					//Si plusieurs professions sont retournées :
					}else if(json.popup==1){
						$.facebox('<div id="popup_recherche" class="popup_recherche" style="margin:auto"></div>','popup_recherche');
						$(".popup_recherche").append('<p style="text-indent:10px">'+ChoisirListeProfession+'</p>');
						$(".popup_recherche").append('<form id="form_profession" name="form_profession" method="post"></form>');
						$(".popup_recherche #form_profession").append('<div id="popup_profession_1" style="margin-left:3%; width:250px; float:left"></div>');
						$(".popup_recherche #form_profession #popup_profession_1").before("<div style=\"width:100%; margin-left:3%; margin-bottom:20px\"><input type=\"checkbox\" name='all' value='0' id=\"allprof\" />"+CocherTout+"</div>");
						var i=0;
						var j=1;
						var tmp=1;
						var resolution = $("#facebox .content").width();
						var colonne = resolution/250;
						colonne = parseInt(colonne);
						var taille = colonne*250;
						taille += 100;
						$(".popup_recherche #form_profession").append('<div style="clear:both; width:'+taille+'px" id="colonne_'+tmp+'"></div>');
								$(".popup_recherche #form_profession #colonne_"+tmp).append('<div id="popup_profession_'+tmp+'_'+j+'" style="width:250px; margin-bottom:20px; border: 1px #eee dashed;  float:left"></div>');
						for(profession in json.professions){
							var testDix = i/10;
							//Creation du div 
							
							if(testDix==1){
								j++;
								i=0;
								if(j>colonne){
									tmp++;
									j=1;
									$(".popup_recherche #form_profession").append('<div style="clear:both">&nbsp;</div>');
									$(".popup_recherche #form_profession").append('<div style="clear:both; width:'+taille+'px" id="colonne_'+tmp+'"></div>');
								}
								$(".popup_recherche #form_profession #colonne_"+tmp).append('<div id="popup_profession_'+tmp+'_'+j+'" style="width:250px; margin-bottom:20px; border: 1px #eee dashed;  float:left; margin:5px; padding:5px"></div>');
							}else{
								i++;
							}	
							//Ajout de la checkbox
							$(".popup_recherche #form_profession #colonne_"+tmp+" #popup_profession_"+tmp+"_"+j).append("<div  style=\"margin-bottom:10px\"><input type=\"checkbox\" name='profession_"+profession+"' value='"+profession+"' class=\"checkprof\" />"+json.professions[profession]+" </div>");
						}//for
						
						$(".popup_recherche #form_profession").append('<input type="hidden" id="texte_recherche2" name="texte_recherche2" value="'+json.texte_recherche+'" />');
						$(".popup_recherche #form_profession").append('<div style="width:300px; clear:both; margin-left:80px; margin-top:20px" id="fin_formulaire"><input type="hidden" id="complement_recherche2" name="complement_recherche2" value="'+json.complement_recherche+'" /></div>');
						
						$(".popup_recherche #form_profession #fin_formulaire").append('<br /><input type="submit" value="'+Valider+'" />');
						$(".popup_recherche #form_profession #allprof").click(function(){
								var testCheck = $(this).attr('checked');
							$(".popup_recherche #form_profession .checkprof").each(function(){
								if(testCheck==true){
									$(this).attr('checked','checked');
								}else{
									$(this).removeAttr('checked');
								}
							});
						});
						$(".popup_recherche #form_profession").submit(function(){
							jQuery(document).trigger('close.facebox');
							var texte = $(".popup_recherche #form_profession #texte_recherche2").attr('value');
							var lieu = $(".popup_recherche #form_profession #complement_recherche2").attr('value');
							var listeProfessions = ''
							$(".popup_recherche #form_profession input[@type=checkbox]:checked").each(function(){
								listeProfessions += $(this).attr('value')+'_';
							});//each
							rechercheCarte(texte,lieu,listeProfessions);
							return false;
						});//submit
					}else if(json.popup==0){
					//Si il n'y a qu'une seule profession retournée ou aucun résultat :
						if(json.no_result==1){
							var profession = null;
						}else if(json.no_result==0){
							for(prof in json.professions){
								var profession = prof;
							}
						}
						rechercheCarte(json.texte_recherche, json.complement_recherche, profession);
					}
				$("#div_recherche").show();
				$("#loader_recherche").hide();
			}//fonction(json)
		);//post
	}else{
		$("#champ_recherche").hide();
		$("#champ_recherche").css("border","1px ridge red");
		$("#champ_recherche").css("padding","10px");
		 if(recherche == ''){
			$("#champ_recherche").append('<p id="msg_erreur_recherche" style="background-color:#FFBFBF">'+RechercheErreur+'</p>');
		 }else{
			 $("#champ_recherche").append('<p id="msg_erreur_recherche" style="background-color:#FFBFBF">'+RechercheCourt+'</p>');
		 }
		$("#champ_recherche").fadeIn("slow");
	}
}//rechercheCount

function rechercheCarte(recherche, complement, listeProfession){
	jQuery(document).trigger('close.facebox');
//	loadInfoMenu('recherche');
	$("#msg_erreur_recherche").remove();
	if(recherche != ''){
		var testMenu = $("#menu_recherche").css('display');
		if(testMenu != 'block'){
			$("#div_recherche").prepend('<div id="menu_recherche" style="margin-bottom:10px"><ul><li id="MR_gauche" class="mr_actif">'+Resultat+'</li><li id="MR_droit" class="mr_inactif"><a href="#" class="toggle_recherche" id="affiche_champs_recherche">'+NouvelleRecherche+'</a></li></ul></div>');
		}
		$("#menu_recherche .toggle_recherche").click(function (){toggleRecherche(); return false;});
		$("#resultat_recherche").empty();
		$("#resultat_recherche").append('<div style="text-align:center"><img src="ressources/spinner.gif" /></div>');
		$.post("inc/ajax/recherche2.php5?action=carte",
			   {recherche : recherche, complement : complement, listeProfession : listeProfession},
			   function(json){
					$("#resultat_recherche").empty();
					$("#resultat_recherche").addClass('recherche_actif');
					$("#champs_recherche").hide();
					$("#champs_recherche").addClass('recherche_inactif');
					$("#resultat_recherche").show();
					json = eval('('+json+')');
				   if(json.no_result==0){
					   if(json['resultat'].length<9){
						   $("#resultat_recherche").append('<div id="div_resultat" style="overflow-y:scroll; clear:both" class="recherche_profession"></div>');
					   }else{
						   $("#resultat_recherche").append('<div id="div_resultat" style="height:550px; overflow:auto; clear:both" class="recherche_profession"></div>');
					   }
					
						for(var i=0; i<json['resultat'].length;i++){
							$("#resultat_recherche #div_resultat").append('<div class="resultat"><a href="#" id="'+json['resultat'][i].id+'" title="'+json['resultat'][i].infosuppl+'" class="lienNoms">'+json['resultat'][i].nom+'</a> <br /> <div class="resultat_info"><span class="resultat_profession">'+json['resultat'][i].profession+'</span> <br /> <span class="resultat_commune">'+json['resultat'][i].commune+' ( '+json['resultat'][i].code_postal+' )</span></div></div>');
						}
						//map.clearOverlays();
							
						//Création du format json à envoyer à printMap :
						var sendJson = new Object;
					   sendJson.type = json.zone;
					   sendJson.idAffichage = json.affichage;
					   sendJson.lat = json.lat;
					   sendJson.lng = json.lng;
					   sendJson.nombre_markers = json.nombre_markers;
					   sendJson.boucle = json.boucle;
					   sendJson.pointeurs = json.resultat;
					   sendJson.texte = json.texte+' : <br /> "'+json.texte_recherche+'"';
					   printMap(sendJson, true);
					   //boundsMap();
				   }else if(json.no_result==1){
					   $("#resultat_recherche").append('<p id="msg_erreur_recherche" style="background-color:#FFBFBF; margin-top: 100px; padding: 20px 0;">'+RechercheNoResult+'</p>');
				   }
			   
				$(".lienProfessions").each(function(){
					$(this).click(function(){
						showProfession($(this).attr('id'));
						return false;
					});//click
				});//Listener sur les liens Professions du footer
				
				//Efface les résultats pour permettre une nouvelle recherche
				$("#menu_recherche #clean_recherche").click(function(){
					$("#form_recherche #complement_recherche").attr('value','');
					$("#form_recherche #texte_recherche").attr('value','');
					$("#resultat_recherche").empty();
					$("#champs_recherche").show();
					$("#menu_recherche").css('display','none');
					return false;
				});
				
				$(".lienNoms").each(function(){
					$(this).click(function(){
						var id = $(this).attr('id');
						afficheMapMarker(id);
						afficheMarker(id);
						return false;
				   });//click
				});//Listener sur les résultats de la recherche
			}//fonction(json)
		);//post
	}else{
		$("#champ_recherche").hide();
		$("#champ_recherche").css("border","1px ridge red");
		$("#champ_recherche").css("padding","10px");
		$("#champ_recherche").append('<p id="msg_erreur_recherche" style="background-color:#FFBFBF">'+RechercheErreur+'</p>');
		$("#champ_recherche").fadeIn("slow");
	}
}//rechercheCarte

function toggleRecherche(){
	$("#div_recherche #resultat_recherche").hide();
	$('#div_recherche #champs_recherche').fadeIn('slow');
	$("#menu_recherche").remove();
};//toggleRecherche

function loadFiche(idFiche, idMarker){
	$.post("inc/ajax/affichage.php5",
		   {idMarker : idMarker, idFiche : idFiche},
		   function (reponse){
			  var rep = eval('('+reponse+')');
			  loadInfoMenu('fiche', idMarker, rep);
		   }
	);//post
}//loadFiche

function loadMap(idPays,idRegion,idDepartement,idCommune){
	$("#contain_map #loaderMap").css('display','inline');
	arrayMarkers = new Array();
	$.post("inc/ajax/affichage.php5", 
		   {idPays: idPays, idRegion: idRegion, idDepartement: idDepartement, idCommune: idCommune},
		   function(reponse) {
			  	var reponse=eval('('+reponse+')');
				printMap(reponse);
				$("#contain_map #loaderMap").css('display','none');
   			} 
   );//post
}//loadMap

function loadMarkers(){
	$.post("inc/ajax/load_profession.php5", 
	   {session : 1},
	   function(reponse) {
			var reponse=eval('('+reponse+')');
			var listMarkers = new Array();
			for(var i=0;i<reponse.pointeurs.length;i++){
				var point = new GLatLng(reponse.pointeurs[i].lat, reponse.pointeurs[i].lng);
				var marker = createMarker(point, reponse.pointeurs[i]);
				listMarkers.push(marker);
			}
			verifMarkers(listMarkers);
		} 
   );//post
}//loadMarkers

function ajaxMenu(identifiant,valeur,valeurPrec){
	if(identifiant != 'commune'){
		$("#boutonSubmit input").css('display','none');
		$("#boutonSubmit img").css('display','inline');
	}
$.post("inc/ajax/classement.php5", {depart: identifiant, valeur: valeur, valeurPrec: valeurPrec}, function(xml){
	var buffer = xml.split('</td>');
	
	var tables = new Array('pays','region','departement','commune');
	for(i=0;i<tables.length;i++){
		if(identifiant==tables[i]){
			position = i;
		}
	}
	for(var i=0;i<buffer.length-1;i++){
		var index = buffer[i].indexOf('>');
		var fin = buffer[i].length;
		var reponse = buffer[i].substring(index+1,fin);
		$('#contain_'+tables[position+i]).html(reponse);
		$(this).find(".valeurChoix").change(function(){
			if($(this).attr('id')!='pays'){
				var valeurPrec = $(this).parent().prev().find(".valeurChoix").attr('value');
			}else{
				var valeurPrec = 1;
			}
			majInput($(this),valeurPrec);
		});
		$('#contain_'+tables[position+i]).addClass('menu_select');
	}
	if(identifiant != 'commune'){
		$("#boutonSubmit img").css('display','none');
		$("#boutonSubmit input").css('display','inline');
	}
});
}//ajaxMenu


/*###############
 AUTO COMPLETION
################*/


function lookup(inputString) {
	if(inputString.length == 0) {
		$('#suggestions').hide();
	}else{
		$.post("inc/ajax/autocomplete.php5?act=commune", {queryString: inputString}, function(data){
			if(data.length>0) {
				$('#suggestions').show();
				$('#autoSuggestionsList').html(data);
			}
			$('.lien_suggest').click(function(){
					var splitid = $(this).attr('id').split('_');
					var id = splitid[1];
					fill(id,$("#"+$(this).attr('id')+" .AC_result").html());
					return false;
			});
		});//post
	}
} // lookup

function lookupSearch(inputString) {
	if(inputString.length == 0) {
		$('#suggestions_recherche').hide();
	}else{
		$.post("inc/ajax/autocomplete.php5?act=all", {queryString: inputString}, function(data){
			if(data.length>0) {
				$('#suggestions_recherche').show();
				$('#autoSuggestionsListRecherche').html(data);
			}
			$('.lien_suggest').click(function(){
					var id = $(this).attr('id');
					var valeur = $("#"+id+" .AC_result").html();
					fillSearch(valeur);
					return false;
			});
		});//post
	}
} // lookup

function fill(id,commune) {
	$('#autocomplete_commune').val(commune);
	$.post("inc/ajax/autocomplete.php5", {id_commune : id },
	   function(reponse){
		$('.menu_select').each(function(){
			if($(this).attr('id') != 'boutonSubmit'){
				$(this).remove();
			}
		});//each
		$('#boutonSubmit').before(reponse);
		$(".valeurChoix").each(function(){
			$(this).change(function(){
				if($(this).attr('id')!='pays'){
					var valeurPrec = $(this).parent().prev().find(".valeurChoix").attr('value');
				}else{
					var valeurPrec = 1;
				}
				majInput($(this),valeurPrec);
			});//change
		});//Listener des select
	   });//post
	setTimeout("$('#suggestions').hide();", 200);
}
function fillSearch(commune) {
	$('#complement_recherche').val(commune);
	setTimeout("$('#suggestions').hide();", 200);
}
