/**
 * @author apellet
 */

/**
 * Permet de passer la page en mode fullscreen
 */

/*L'icone reprï¿½sentant l'adresse*/
var icon_adresse = null;

var save_map_width;
var save_map_height;
var save_all_height;

function fullScreen()
{
	//On revient en mode d'affichage standard
	if ( fullscreen )
	{
		var center = map.getCenter();
		jQuery("#map").css ('width', save_map_width);
		jQuery("#map").css ('height', save_map_height);
		jQuery("#all_map").css ('width', save_map_width);
		
		jQuery('#undermap').css('display', 'block');
		jQuery('#'+div_fullscreen).css ( "display", "block" );
		map.checkResize();
		map.setCenter(center);
		
		document.getElementById("full_map").appendChild(document.getElementById("all_map"));
		
		jQuery("#a-fullscreen").html ( "[Plein &eacute;cran]" );
		loading.setPosition ();
		fullscreen = false;
		pan_control.updatePosition ();
		jQuery("body").css ("overflow", "auto");
	}
	//On passe on mode plein ï¿½cran
	else
	{
		var center = map.getCenter();
		var winW = 0; 
		var winH = 0;
		if (window.innerWidth && window.innerHeight) {
			winW = window.innerWidth;
			winH = window.innerHeight;
		} else if (document.documentElement && document.documentElement.clientWidth && document.documentElement.clientHeight) {
			winW = document.documentElement.clientWidth;
			winH = document.documentElement.clientHeight;
		} else if (document.body) {
			winW = document.body.clientWidth;
			winH = document.body.clientHeight;
		}
		
		jQuery('#undermap').css('display', 'none');
		
		save_map_width = jQuery("#map").width();
		save_map_height = jQuery("#map").height();
		save_all_height = jQuery("#all_map").height();
		
		jQuery("#all_map").css ( "width", winW-2 );
		jQuery("#map").css ( "width", winW-2 );
		jQuery("#map").css ( "height", winH-(35+0)/*tool bar*//*jQuery('#undermap').height()*//*texte sous la carte*/ );
		
		document.body.appendChild(document.getElementById("all_map"));
		
		
		jQuery('#'+div_fullscreen).css ('display', "none");
		map.checkResize();
		
		map.setCenter(center);
		
		jQuery("#a-fullscreen").html ( "[Ecran normal]" );
		loading.setPosition ();
		fullscreen = true;
		pan_control.updatePosition ();
		jQuery("body").css ("overflow", "hidden");
	}
}



/**
 * Classe qui gere le gif de chargement
 */
Loading = function ()
{
	this.init ();
};
Loading.prototype = 
{
	el_loading : null,
	w : 200,
	h : 200,
	
	init : function ()
	{
		
		this.el_loading = document.createElement("div");
		this.el_loading.id = "el_loading";	
		document.getElementById("map").appendChild(this.el_loading);
		
		
		el_div_wait = document.createElement ("DIV");
		el_div_wait.id = "el_div_wait";
		document.getElementById("el_loading").appendChild(el_div_wait);
		
		el_div_wait.style.position = "absolute";
		el_div_wait.style.left = "66px";
		el_div_wait.style.top = "66px";
		
		el_wait = document.createElement ("IMG");
		el_wait.src = prefix_php + "images/load.gif"	;
		document.getElementById("el_div_wait").appendChild(el_wait);
		
		this.setPosition ();
		
		
		
		this.el_loading.style.display = "none";
	},
	setPosition :function ()
	{
		var m_w = jQuery("#map").width() ;
		var m_h = jQuery("#map").height() ;
		
		this.el_loading.style.position = "absolute";
		this.el_loading.style.left = (m_w - this.w) / 2 + "px" ;
		this.el_loading.style.top = (m_h - this.h) / 2 + "px" ;
		this.el_loading.style.width = this.w + "px";
		this.el_loading.style.height = this.h + "px";
		this.el_loading.style.backgroundColor = "transparent";
	},
	stop : function ()
	{
		this.el_loading.style.visibility="hidden";
		this.el_loading.style.display = "none";
	},
	start : function ()
	{
		if ( this.el_loading.style.display == "block" ){
		//return;
		}
		
		this.el_loading.style.visibility="visible";
		this.el_loading.style.display = "block";
	}
};



/**
 * Methode qui crï¿½ï¿½e un tableau d'objet json destinï¿½s ï¿½ initialiser la lï¿½gende active.
 */
function createJsonLegend ()
{
	//
	var o = new Array ();
	o.push ( {image:prefix_php+'images/carto/asso_f.png', code:'F', title:'Foyer rural ou association'} );
	
	o.push ( {image:prefix_php+'images/carto/asso_d.png', code:'D', title:'F&eacute;d&eacute;ration d&eacute;partementale des foyers ruraux'} );
	
	o.push ( {image:prefix_php+'images/carto/asso_cd.png', code:'CD', title:'Comit&eacute; d&eacute;partemental du sport en milieu rural'} );
	
	o.push ( {image:prefix_php+'images/carto/asso_r.png', code:'R', title:'Union r&eacute;gionale des foyers ruraux'} );
	
	o.push ( {image:prefix_php+'images/carto/asso_cr.png', code:'CR', title:'Comit&eacute; r&eacute;gional du sport en milieu rural'} );

	o.push ( {image:prefix_php+'images/carto/asso_n.png', code:'N', title:'Structures nationales'} );

	
	/*o.push ( {image:'./images/carto/asso_f.png', code:'F', title:'Foyer rural ou association'} );
	
	o.push ( {image:'./images/carto/asso_d.png', code:'D', title:'F&eacute;d&eacute;ration d&eacute;partementale des foyers ruraux'} );
	
	o.push ( {image:'./images/carto/asso_cd.png', code:'CD', title:'Comit&eacute; d&eacute;partemental du sport en milieu rural'} );
	
	o.push ( {image:'./images/carto/asso_r.png', code:'R', title:'Union r&eacute;gionale des foyers ruraux'} );
	
	o.push ( {image:'./images/carto/asso_cr.png', code:'CR', title:'Comit&eacute; r&eacute;gional du sport en milieu rural'} );

	o.push ( {image:'./images/carto/asso_n.png', code:'N', title:'Structures nationales'} );
	*/
	return o;
}


/**
 * 
 */
function createIconAdresse ()
{
	icon_adresse = new GIcon ();
	icon_adresse.iconSize = new GSize ( 30, 30 );
	icon_adresse.iconAnchor = new GPoint  ( 15, 30 );
	icon_adresse.infoWindowAnchor = new GPoint  ( 15, 0 );
	icon_adresse.shadowSize = new GSize ( 45, 30 );
	icon_adresse.image = prefix_php + "images/carto/adresse.png";
	icon_adresse.shadow = prefix_php + "images/carto/adresse_sh.png";
}

/**
 * Methode qui crï¿½ï¿½e les icons pour les marqueurs des associations.
 */
function createIconAssoc ()
{
	var basic_icon = new GIcon ();
	basic_icon.iconSize = new GSize ( 20, 20 );
	basic_icon.iconAnchor = new GPoint  ( 12, 20 );
	basic_icon.infoWindowAnchor = new GPoint  ( 12, 0 );
	basic_icon.shadowSize = new GSize ( 30, 20 );
	
	var icon_1 = new GIcon ( basic_icon );
	icon_1.image = prefix_php + "images/carto/asso_f.png";
	icon_1.shadow = prefix_php + "images/carto/asso_f_sh.png";
	
	var icon_2 = new GIcon ( basic_icon );
	icon_2.image = prefix_php + "images/carto/asso_cr.png";
	icon_2.shadow = prefix_php + "images/carto/asso_cr_sh.png";
	
	var icon_3 = new GIcon ( basic_icon );
	icon_3.image = prefix_php + "images/carto/asso_cd.png";
	icon_3.shadow = prefix_php + "images/carto/asso_cd_sh.png";
	
	var icon_4 = new GIcon ( basic_icon );
	icon_4.image = prefix_php + "images/carto/asso_d.png";
	icon_4.shadow = prefix_php + "images/carto/asso_d_sh.png";

	var icon_5 = new GIcon ( basic_icon );
	icon_5.image = prefix_php + "images/carto/asso_n.png";
	icon_5.shadow = prefix_php + "images/carto/asso_n_sh.png";
	
	var icon_6 = new GIcon ( basic_icon );
	icon_6.image = prefix_php + "images/carto/asso_r.png";
	icon_6.shadow = prefix_php + "images/carto/asso_r_sh.png";

	icon_asso['F'] = icon_1;
	icon_asso['CR'] = icon_2;
	icon_asso['CD'] = icon_3;
	icon_asso['D'] = icon_4;
	icon_asso['N'] = icon_5;
	icon_asso['R'] = icon_6;
}

function createIconRegion ()
{
	var basic_icon = new GIcon ();
	basic_icon.iconSize = new GSize ( 30, 30 );
	basic_icon.iconAnchor = new GPoint  ( 15, 30 );
	basic_icon.infoWindowAnchor = new GPoint  ( 15, 0 );
	//basic_icon.shadowSize = new GSize ( 24, 30 );
	
	icon_region = new GIcon ( basic_icon );
	icon_region.image ="images/carto/circle.png";
	//icon_acteur.shadow = prefix_php + "images/carto/asso_f_sh.png";	
}


function createIconActeur ()
{
	var basic_icon = new GIcon ();
	basic_icon.iconSize = new GSize ( 32, 32 );
	basic_icon.iconAnchor = new GPoint  ( 16, 32 );
	basic_icon.infoWindowAnchor = new GPoint  ( 16, 0 );
	//basic_icon.shadowSize = new GSize ( 24, 30 );
	
	icon_acteur = new GIcon ( basic_icon );
	icon_acteur.image ="images/carto/structure.png";
	//icon_acteur.shadow = prefix_php + "images/carto/asso_f_sh.png";

	icon_etat = new GIcon ( basic_icon );
	icon_etat.image ="images/carto/structure.png";
}

/*function createIconActeur ()
{
	var basic_icon = new GIcon ();
	basic_icon.iconSize = new GSize ( 16, 30 );
	basic_icon.iconAnchor = new GPoint  ( 8, 30 );
	basic_icon.infoWindowAnchor = new GPoint  ( 8, 0 );
	//basic_icon.shadowSize = new GSize ( 24, 30 );
	
	icon_acteur = new GIcon ( basic_icon );
	icon_acteur.image ="images/carto/structure.png";
	//icon_acteur.shadow = prefix_php + "images/carto/asso_f_sh.png";

	icon_etat = new GIcon ( basic_icon );
	icon_etat.image ="images/carto/etat.png";
}*/

/**
 * Fonction qui permet d'afficher sous la carte la liste des rï¿½sultats.
 * La liste est active.
 * @param {Object} obj_asso
 */
function drawListeResultatActeur ( obj_asso, nb, erase )
{
	//En attente
	/*var ul_1 = jQuery("ul#list_1");
	var ul_2 = jQuery("ul#list_2");
	var cur_nb = 0;
	
	if ( erase == true )
	{
		emptyListeResultat ();
		cur_nb = 0;
	}
	else
	{
		var t = jQuery("#aff_nb_asso").html ();
		if ( t == "" )
		{
			cur_nb = 0;
		}
		else
		{
			cur_nb = parseInt(t) ;
		}
	}
	var cpt = 0;
	
	
	
	for ( var i in obj_asso )
	{
		var o = obj_asso[i];
		if ( cpt % 2 == 0 )
		{
			ul_1.append ( tmpl_elementList, o );
		}
		else if ( cpt % 2 == 1 )
		{
			ul_2.append ( tmpl_elementList, o );
		}
		cpt++;
	}
	jQuery("#aff_nb_asso").html (cpt+cur_nb);
	
	if ( externeModule == 0 )
	{
		jQuery("#list-result").css ('display', 'block' );
	}
	else if ( externeModule == 1 && show_liste_resultat == 1 )
	{
		jQuery("#list-result").css ('display', 'block' );
	}*/
	
}

function emptyListeResultat ()
{
	var ul_1 = jQuery("ul#list_1");
	var ul_2 = jQuery("ul#list_2");
	
	ul_1.html ('');
	ul_2.html ('');
}
/**
 * Mï¿½thode qui remplie la liste dï¿½roulante des dï¿½partements
 */
function fillSelectDepartement ( id_region )
{
	jQuery.ajax
	({
		type: "POST",
		url: "./php/__load_departement_select.php",
		data: {clause:' where id_region='+id_region},
		dataType:'xml',
		
		success: function(obj)
		{
			clearSelect ('list_departement');
			jQuery('#list_departement').append(jQuery("<option></option>").attr("value","-1").text("Choisissez un d\351partement"));
			jQuery(obj).find("annuaire_departement").each ( function ()
			{				
				jQuery('#list_departement').append(jQuery("<option></option>").attr("value",jQuery(this).attr('id')).text(jQuery(this).attr('libelle')));
			});
			departement_loaded = true;
		},
		error:function (XMLHttpRequest, textStatus, errorThrown)
		{
			alert(textStatus);
		}
	});
				
				
	/*var sel = document.getElementById ('list_dep');
	sel.options [ sel.options.length ] = new Option ( "---------", "-1" );
	for ( var i in obj_dep )
	{
		sel.options [ sel.options.length ] = new Option ( obj_dep[i].num + " - " + obj_dep[i].lib, i );
	}*/
	
} 

function fillSelectRegion ()
{
	var sel = document.getElementById ('list_region');
	sel.options [ sel.options.length ] = new Option ( "Choisissez une r\351gion", "-1" );
	for ( var i in obj_reg )
	{
		sel.options [ sel.options.length ] = new Option ( obj_reg[i].lib, i );
	}
	region_loaded = true;
} 

/**
 * Mï¿½thode qui ouvre la boite d'information dï¿½taillï¿½e
 */
function openDlgInfo()
{
	dlg_info = jQuery('#block-popup').modal({
		onShow: function(){
			//jQuery("#block-popup .dlg-body").append ( tmpl_maxiInfo, {} );
		}
	});
}




function loadListMission ()
{
	loading.start();
	jQuery.ajax({
        type: "GET",
        url: "./php/__load_missions.php",
        data: '',
		dataType:'xml',
        success: function(xml)
		{
			jQuery(xml).find("annuaire_mission").each ( function()
			{
				var id = parseInt(jQuery(this).attr ('id'));
				var lib = jQuery(this).attr ('libelle');
				
				jQuery('#list_missions').append(jQuery("<li><input name='struct_mission_ids[]' id='struct_mission_ids[]' type='checkbox' value='"+ id +"'>" + lib + "</input></li>"));
			});
			jQuery('#list_missions').append(jQuery("<li><input name='struct_mission_ids[]' id='struct_mission_ids[]' type='checkbox' value='-1'>" + 'Autres' + "</input></li>"));

			acti_loaded = true;
			loading.stop();
			
			
			
        },
		error:function (XMLHttpRequest, textStatus, errorThrown)
		{
			alert(textStatus); 
		}
    });
}



/**
 * Mï¿½thode qui execute la recherche d'association issue du moteur de recherche.
 */
function execSearch ()
{
	removeAdresse ();
	removeAllMarqueursActeur ();
	if ( layer_reg != null )
	{
		//layer_reg.remove_all();
	}
	
	var acteur_res = {};
	
	
	//Aucune valeur saisie
	if ( 	jQuery('#moteur_recherche #list_region').val() == "-1" &&
			jQuery('#moteur_recherche #list_departement').val() == "-1" &&
			!IsMissionCheck ()
		)
	{
		alert("Vous devez filtrer votre recherche");
		return false;
	}
	
	
	//Uniquement une région choisie
	if ( 	jQuery('#moteur_recherche #list_region').val() != "-1" &&
			jQuery('#moteur_recherche #list_departement').val() == "-1" &&
			!IsMissionCheck ()
		)
	{
		var reg = jQuery('#moteur_recherche #list_region').val();
		
		loadActeurFromDep ( obj_reg[reg].liste_dep, false, reg );
		return false;
	}
	
	//Uniquement un departement choisi
	if ( 	jQuery('#moteur_recherche #list_region').val() != "-1" &&
			jQuery('#moteur_recherche #list_departement').val() != "-1" &&
			!IsMissionCheck ()
		)
	{
		var reg = jQuery('#moteur_recherche #list_region').val();
		
		loadActeurFromDep ( jQuery('#moteur_recherche #list_departement').val(), 
							false, 
							jQuery('#moteur_recherche #list_region').val() );
		return false;
	}
	
	var data = jQuery('#moteur_recherche').serialize()+
				"&year="+new Date().getFullYear()+
				"&type_struct="+type_struct+
				"&code_struct="+code_struct+
				"&max_query="+max_query;
				
	
	var cpt = 0;
	loading.start();
	jQuery.ajax({
        type: "POST",
        url: prefix_php + "php/__load_acteur_from_search.php",
        data: data,
		dataType:'xml',
        success: function(xml)
		{
			jQuery(xml).find("annuaire_acteur").each ( function()
			{
				readXmlActeur ( this, acteur_res);		
				cpt ++;
			});
			loading.stop();
			
			if ( cpt == max_query )
			{
				alert( "Votre recherche renvoie plus de " + max_query + " acteur(s). Tous ne sont pas affich\351es." )
			}
			
			//Appel de la fonction de rendu
			//console.log(layer_dep.get ( dep ).getLatLng());
			drawActeur ( acteur_res, new GLatLng (46.72480037466717,2.04345703125), true );
			
			
			//Appel de la fonction de mise ï¿½ jour de la liste des rï¿½sultats
			drawListeResultatActeur ( acteur_res, cpt, true );
        },
		error:function (XMLHttpRequest, textStatus, errorThrown)
		{
			alert(textStatus); 
			console.log (errorThrown);
		}
    });
}


function IsMissionCheck ()
{
	var b = false;
	
	jQuery("ul#list_missions input").each (function ()
	{		
		if ( jQuery(this).attr('checked') == true )
		{
			b = true;
		}
	})
	
	/*if ( b == false )
	{
		if ( jQuery("ul#list_services input[value=100]").attr('checked') )
		{
			b = true;
		}
	}*/
	return b;
}

/**
 * Mï¿½thode utilisï¿½e pour "dï¿½sencodï¿½e" une chaine issu d'un xml AJAX, encodï¿½ en php
 * @param {Object} xmlStr
 */
function parsefromXML(xmlStr) 
{
	xmlStr = xmlStr.replace(/&lt;/g,'<'); // 60 3C
	xmlStr = xmlStr.replace(/&gt;/g,'>'); // 62 3E
	xmlStr = xmlStr.replace(/&quot;/g,'"'); // 62 3E
	xmlStr = xmlStr.replace(/&#39;/g,"'"); // 62 3E
	xmlStr = xmlStr.replace(/&amp;/g,'#'); // 62 3E

	return xmlStr; 
} 

function initMapAgain()
{
	removeAllMarqueursActeur ();
	emptyListeResultat ();
	
	if ( layer_reg != null )
	{
		for ( var i in layer_reg._obj )
		{
			var o = layer_reg._obj[i];
			o.isHidden = 0;
			o.show();
		}
	}
	
	/*layer_dep = new Layer ({_map:map, _zoom:zoom_dep, _min_max:'max', _name:'departements'});
	jQuery("#list-result").css ('display', 'block' );
	
	for ( var i in obj_dep )
	{
		var o = obj_dep[i];
		var latlng = new GLatLng ( parseFloat ( o.lat ), parseFloat ( o.lng ) );
		var m_dep = new GMarker ( latlng , {icon:class_circle.getCircle ( o.nb_asso ), title:o.lib} );
		
		
		//map.addOverlay ( m_dep );
		layer_dep.add ( m_dep, o.num );
		
		GEvent.addListener ( m_dep, "click", GEvent.callbackArgs ( window, window.openInfoDepartement, m_dep, {lib:o.lib, nb_asso:o.nb_asso, dep:o.num} ) );
		GEvent.addListener ( m_dep, "dblclick", GEvent.callbackArgs ( window, window.loadAssoFromDep, o.num, false ) );
		
	}*/
	
	
	
	if ( externeModule == 0 )
	{
		map.setCenter ( new GLatLng (46.72480037466717,2.04345703125), 6);
	}
	else if ( externeModule == 1 )
	{
		if ( type_struct == 1 )
		{
			map.returnToSavedPosition() ;
		}
		else if ( type_struct == 2 )
		{
			map.returnToSavedPosition() ;
		}
	}
	
		
	
}

/**
 * Remise ï¿½ zï¿½ro du formulaire de recherche
 */
function razSearch()
{
	removeAllMarqueursActeur ();
	try
	{
		jQuery('#list_region option[@value=-1]').attr("selected", "selected");
	}
	catch(error){}
	
	try
	{
		jQuery('#list_departement option[@value=-1]').attr("selected", "selected");
	}
	catch(error){}
	
	jQuery('#list_missions input').each (function()
	{
		jQuery(this).attr('checked', false );
	});

	jQuery('#list_services input').each (function()
	{
		jQuery(this).attr('checked', false );
	});
	
	
	//emptyListeResultat ();
	//jQuery("#list-result").css ("display", "none");
	
	removeAdresse ();
	if ( externeModule == 0 )
	{
		initMapAgain ();
	}
	else if ( externeModule == 1 )
	{
		if ( type_struct == 1 )
		{			
			loadActeurFromDep ( code_struct , true, -1 );
		}
		else if ( type_struct == 2 )
		{		
			loadActeurFromDep ( obj_reg[code_struct].liste_dep , true, -1 );
			
			//drawListeResultatActeur ( asso_res_reg, cpt_asso_reg, true );
		}
	}
	
}

/**
 * Mï¿½thode appellï¿½e lorsqu'une liste dï¿½roulante est activï¿½e
 * @param {Object} value
 * @param {Object} id
 */
function onChangeSelect(value, id)
{
	//alert(value + " " + id);
	value = parseInt (value);
	if ( value == -1 )
	{		
		document.getElementById ( "list_acti_culturelle" ).disabled = false;
		document.getElementById ( "list_acti_educative" ).disabled = false;
		document.getElementById ( "list_acti_sport" ).disabled = false;
		document.getElementById ( "list_acti_service" ).disabled = false;
		document.getElementById ( "list_acti_festive" ).disabled = false;
		document.getElementById ( "list_acti_divers" ).disabled = false;
		/*jQuery("select[name^='list_acti_']").each(function( i, o )
		{		
			jQuery(o).attr('disabled', 'false');
		});*/
	}
	else
	{
		document.getElementById ( "list_acti_culturelle" ).disabled = true;
		document.getElementById ( "list_acti_educative" ).disabled = true;
		document.getElementById ( "list_acti_sport" ).disabled = true;
		document.getElementById ( "list_acti_service" ).disabled = true;
		document.getElementById ( "list_acti_festive" ).disabled = true;
		document.getElementById ( "list_acti_divers" ).disabled = true;
		
		/*jQuery("select[name^='list_acti_']").each(function( i, o )
		{
		
			
				jQuery(o).attr('disabled', 'true');
			
		});*/
		
	
		
		
	}
	document.getElementById ( id ).disabled = false;
	
	
}

			function clearSelect ( id )
			{
				document.getElementById (id).options.length = 0;
			}
