/**
 * @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;
}


/**
 * Fonction qui permet d'afficher sous la carte la liste des résultats.
 * La liste est active.
 * @param {Object} obj_asso
 */
function drawListeResultat ( obj_asso, nb, erase )
{
	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 fillSelectDep ()
{
	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 );
	}
	dep_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, {} );
		}
	});
}


/**
 * Méthode qui permet de remplir les listes déroulantes du moteur de recherche
 */
function loadListeActivite ()
{
	var sel_culturelle = document.getElementById ('list_acti_culturelle');
	sel_culturelle.options [ sel_culturelle.options.length ] = new Option ( "--Culturel, expression--", "-1" );
	
	var sel_educative = document.getElementById ('list_acti_educative');
	sel_educative.options [ sel_educative.options.length ] = new Option ( "--Educative et sociale--", "-1" );
	
	var sel_sport = document.getElementById ('list_acti_sport');
	sel_sport.options [ sel_sport.options.length ] = new Option ( "--Sport et plein air--", "-1" );

	var sel_service = document.getElementById ('list_acti_service');
	sel_service.options [ sel_service.options.length ] = new Option ( "--Services--", "-1" );

	var sel_festive = document.getElementById ('list_acti_festive');
	//sel_festive.options [ sel_festive.options.length ] = new Option ( "--Récréative et festive--", "-1" );

	var sel_divers = document.getElementById ('list_acti_divers');
	sel_divers.options [ sel_divers.options.length ] = new Option ( "--Divers--", "-1" );

	loading.start();
	
	jQuery.ajax({
        type: "GET",
        url: prefix_php + "php/loadListeActivite.php",
        data: '',
		dataType:'xml',
        success: function(xml)
		{
			jQuery(xml).find("acti").each ( function()
			{
				var id = jQuery(this).attr ('id');
				var parent = parseInt(jQuery(this).attr ('parent'));
				var code = jQuery(this).attr ('code');
				var nom = parsefromXML(jQuery(this).attr ('nom'));
				
				switch ( parent )
				{
					//culture
					case 1:
						sel_culturelle.options [ sel_culturelle.options.length ] = new Option ( nom, code );
					break;
					//sport
					case 2:
						sel_sport.options [ sel_sport.options.length ] = new Option ( nom, code );
					break;
					//festive
					case 3:
						sel_festive.options [ sel_festive.options.length ] = new Option ( nom, code );
					break;
					//social
					case 4:
						sel_educative.options [ sel_educative.options.length ] = new Option ( nom, code );
					break;
					//service
					case 5:
						sel_service.options [ sel_service.options.length ] = new Option ( nom, code );
					break;
					//divers
					case 6:
						sel_divers.options [ sel_divers.options.length ] = new Option ( nom, code );
					break;
				}
				
			});
			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 ();
	if ( layer_dep != null )
	{
		layer_dep.remove_all();
	}
	
	var asso_res = {};
	/**/
	if ( jQuery('#moteur_recherche #list_dep').val() == "-1" &&
		jQuery('#moteur_recherche #list_acti_culturelle').val() == "-1" &&
		jQuery('#moteur_recherche #list_acti_educative').val() == "-1" &&
		jQuery('#moteur_recherche #list_acti_sport').val() == "-1" &&
		jQuery('#moteur_recherche #list_acti_service').val() == "-1" &&
		jQuery('#moteur_recherche #list_acti_festive').val() == "-1" &&
		jQuery('#moteur_recherche #list_acti_divers').val() == "-1" 
	)
	{
		alert("Vous devez filtrer votre recherche");
		return false;
	}
	
	if ( jQuery('#moteur_recherche #list_dep').val() != "-1" &&
		jQuery('#moteur_recherche #list_acti_culturelle').val() == "-1" &&
		jQuery('#moteur_recherche #list_acti_educative').val() == "-1" &&
		jQuery('#moteur_recherche #list_acti_sport').val() == "-1" &&
		jQuery('#moteur_recherche #list_acti_service').val() == "-1" &&
		jQuery('#moteur_recherche #list_acti_festive').val() == "-1" &&
		jQuery('#moteur_recherche #list_acti_divers').val() == "-1" 
	)
	{
		loadAssoFromDep ( jQuery('#moteur_recherche #list_dep').val(), true );
		return false;
	}
	
	var cpt = 0;
	loading.start();
	jQuery.ajax({
        type: "POST",
        url: prefix_php + "php/loadAssoFromSearch.php",
        data: jQuery('#moteur_recherche').serialize()+
				"&year="+new Date().getFullYear()+
				"&type_struct="+type_struct+
				"&code_struct="+code_struct+
				"&max_query="+max_query,
		dataType:'xml',
        success: function(xml)
		{
			jQuery(xml).find("asso").each ( function()
			{
				readXmlAsso ( this, asso_res);		
				cpt ++;
			});
			loading.stop();
			
			if ( cpt == max_query )
			{
				alert( "Votre recherche renvoie plus de " + max_query + " association(s). Toutes ne sont pas affichées." )
			}
			
			//Appel de la fonction de rendu
			//console.log(layer_dep.get ( dep ).getLatLng());
			drawAssociation ( asso_res, new GLatLng (46.72480037466717,2.04345703125), true );
			
			
			//Appel de la fonction de mise à jour de la liste des résultats
			drawListeResultat ( asso_res, cpt, true );
        },
		error:function (XMLHttpRequest, textStatus, errorThrown)
		{
			alert(textStatus); 
			console.log (errorThrown);
		}
    });
}


/**
 * 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()
{
	removeAllMarqueurs ();
	emptyListeResultat ();
	
	if ( layer_dep != null )
	{
		for ( var i in layer_dep._obj )
		{
			var o = layer_dep._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 ) );
		
	}*/
	map.setCenter ( new GLatLng (46.72480037466717,2.04345703125), 6);	
	
}

/**
 * Remise à zéro du formulaire de recherche
 */
function razSearch()
{
	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;
	document.getElementById ( "moteur_recherche" ).reset();
	
	emptyListeResultat ();
	jQuery("#list-result").css ("display", "none");
	
	removeAdresse ();
	if ( externeModule == 0 )
	{
		initMapAgain ();
	}
	else if ( externeModule == 1 )
	{
		if ( type_struct == 1 )
		{
			
			loadAssoFromDep ( jQuery('#moteur_recherche #list_dep').val(), true );
		}
		else if ( type_struct == 2 )
		{
			
			drawAssociation ( asso_res_reg, null, true );
			drawListeResultat ( 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;
	
	
}


