var url_profil_index = "";
var current_form_id = null;

var SearchProfile = Class.create({
	initialize: function(instance_name, url, root_id, page_id) {
		this.root_id = root_id;
		this.page_id = page_id;
		this.url = url;
		this.instance = instance_name;
		this.json = null; // parmis : LISTE, ICONES, IMAGES
		this.json_connected = null;
		this.order = "creation_date"; // sens du tri parmis : ASC ou DESC
		this.direction = "DESC";
		this.callback_load = SearchProfile.prototype.load_callback.bind(this);
		this.pagination = new Pagination(null, page_id, this);
		var cbEnLigne = $('en_ligne');
		this.connect_status = cbEnLigne && cbEnLigne.checked;
		this.date_field = "status_date";//Nom du champ date à afficher dans les résultats
		this.criteres = null;
	},

	load_callback: function(json) {
		if(json != null){
			this.json = json;
			this.json_connected = new Array();
			for(var i = 0; i<this.json.length ; i++){
				if(this.json[i].is_connected==1){
					this.json_connected.push(this.json[i]);}
			}
			this.switch_connected();
		}
	},

	notify: function()
	{
		this.display();
	},

	search: function(search_terms) {
		var search_url = this.url;
		var callback = this.callback_load;
		var postdata = "data[Annuaire][search_type]=normal&data[Annuaire][search_terms]=" + search_terms;
		new Ajax.Request(search_url, {
			method: 'post',
			postBody: postdata,
			evalJS: false,
			onSuccess: function(transport) {
				var json;
				try {
					json = transport.responseText.evalJSON(true);
				} catch(e) {
					if(js_debug > 0)
						alert("SearchProfile : " + e);
					json = null;
				}
				callback(json);
			}
		});
	},
	search_by_letter: function(alpha) {
		//2010-11-29
		couleur_lettre_en_cours(alpha.charCodeAt(0));

		var search_url = this.url;
		var callback = this.callback_load;
		var postdata = "data[Annuaire][search_type]=letter&data[Annuaire][letter]=" + alpha.toLowerCase();
		new Ajax.Request(search_url, {
			method: 'post',
			postBody: postdata,
			evalJS: false,
			onSuccess: function(transport) {
				var json;
				try {
					json = transport.responseText.evalJSON(true);
				} catch(e) {
					if(js_debug > 0)
						alert("SearchProfile : " + e);
					json = null;
				}
				callback(json);
			}
		});
	},
	search_all: function() {
		var search_url = this.url;
		var callback = this.callback_load;
		var postdata = "data[Annuaire][search_type]=all";
		new Ajax.Request(search_url, {
			method: 'post',
			postBody: postdata,
			evalJS: false,
			onSuccess: function(transport) {
				var json;
				try {
					json = transport.responseText.evalJSON(true);
				} catch(e) {
					if(js_debug > 0)
						alert("SearchProfile : " + e);
					json = null;
				}
				callback(json);
			}
		});
	},

	build_postdata: function() {
		if (!this.criteres) {
			return null;
		}
		var postdata = "data[Annuaire][search_type]=multiple";
		this.criteres.each(function(c){
			postdata += "&data[Annuaire]["+c.key+"]="+c.value;
		});
		return postdata;
	},

	search_detailed: function(criteres) {
		this.criteres = criteres;
		var search_url = this.url;
		var callback = this.callback_load;
		var postdata = "data[Annuaire][search_type]=multiple";

		criteres.each(function(c){
			postdata += "&data[Annuaire]["+c.key+"]="+c.value;
		});

		new Ajax.Request(search_url, {
			method: 'post',
			postBody: postdata,
			evalJS: false,
			onSuccess: function(transport) {
				var json;
				try {
					var result = transport.responseText;
					if(!isNaN(result)){
						//la réponse est un nombre => le nombre de résultats dépasse le nombre de résultats max par recherche => affichage d'une alerte js
						alert("Les résultats de cette recherche comportent plus de "+result+" profils. Veuillez affiner vos critères.");
						return;
					}else{
						//la réponse n'est pas très volumineuse
						json = eval('(' + result + ')');//evalJSON manuel pour essayer de gagner en performance
						if (json && json.length > 0) {
							/*Affichage des options. Ex: export CSV*/
							var btn_extraction_csv = $("extraction_btns");
							if (btn_extraction_csv) {
								btn_extraction_csv.update('<div class="buttons_container" style="padding-right: 5px;">'+
									'<div id="adm_search_extraction_button" class="button_action" onclick="javascript: search_2.adm_search_extraction(); return false;">'+
										'<span>Effectuer une extraction des résulats au format CSV</span>'+
									'</div>'+
								'</div>');
							}
						}
						callback(json);
					}

				} catch(e) {
					if(js_debug > 0)
						alert("SearchProfile error : " + e);
					json = null;
				}
			}
		});
	},

	display: function() {
		if(this.json){
			this.sort_objects();

			var i;
			var html = "";
			var clas = "";
			for(i = this.pagination.begin; i<this.pagination.end; i++){
				if(this.connect_status){
					html+= this.display_item(this.json_connected[i], clas);
				}else{
					html+= this.display_item(this.json[i], clas);
				}
			}
			html_entete = this.make_header();
			html="<table cellspacing=\"0\" id='result'>" + html_entete + html + "</table>";
			$(this.root_id).update(html);
		}
	},
	show_profile: function(id)
	{
		 var pop_up = window.open(url_profil_index + '/' + id, 'fiche_membre','width=800, height=600, resizable=yes,scrollbars');
		pop_up.focus();
	},
	display_item: function(object, clas) {
		var result = "";
		var dom_id = this.dom_id_item(object.id);
		var template_ressource_liste = new Template("<tr id='" + dom_id + "' class='"+clas+"'><td class='border_r_blanc'>#{nom_prenom}</td><td class='border_r_blanc'>#{statut}</td><td class='border_r_blanc'>#{promotion}</td><td class='border_r_blanc'>#{site_promo}</td><td class='border_r_blanc'>#{annee}</td></tr>");
		//si le statut contient "non inscrit" (membre accepté en fait), pas de lien vers sa fiche
		if (object.statut && object.statut.indexOf("non inscrit") == -1) {
			//Membre inscrit
			object.nom_prenom = "<a href='javascript:" + this.instance + ".show_profile(" + object.id + ");' class='item_bleu' >" + object.nom_marital.capitalize() + " "  +object.prenom.capitalize()+"</a>";
		} else {
			object.nom_prenom = object.nom_marital.capitalize() + " "  +object.prenom.capitalize();
		}

		object.is_online = "";
		object.promotion = object.lib_promo.capitalize();
		object.annee = object.annee_promo;
		if(object.promotion == "")		object.promotion = "&nbsp;";
		if(object.annee == "")			object.annee = "&nbsp;";
		if(object.site_promo == "")		object.site_promo = "&nbsp;";
		result = template_ressource_liste.evaluate(object);
		return result;
	},

	// id de l'objet dom dans la liste
	dom_id_item: function(id) {
		return("id_user_" + id);
	},

	// suppr de l'objet affiché (le <tr>)
	/*dom_item_delete: function(object){
		id = dom_id_item(object.id);
		//$(id).remove();
	},*/

	// suppr de l'objet
	delete_item: function(id){
		// retirer l'objet de la liste
		i = this.find_rang_item_by_id(id);
		if(i < 0)
			return;
		this.json.splice(i, 1);
		// effacer son <tr>
		dom_id = this.dom_id_item(id);
		$(dom_id).remove();
	},

	// màj de l'objet et de son affichage
	modify_item: function(id, property, value){
		var object = this.object_from_id(id);
		if(!object)
			return;
		object[property] = value;

		dom_id = this.dom_id_item(object.id);
		dom_obj = $(dom_id);
		html = this.display_item(object, "");
		/*dom_obj.insert({before: html});
		dom_obj.remove();*/
		dom_obj.replace(html);
	},

	object_from_id: function (id) {
		var i = this.find_rang_item_by_id(id);
		if(i<0)
			return(null);

		return(this.json[i]);
	},

	find_rang_item_by_id: function(id) {
		var i, N, o;
		json = this.json;
		if(!json) return -1;

		N = json.length;
		for(i=0; i<N; i++)
			{
			o = json[i];
			if(o.id == id)
				return(i);
			}
		return(-1);
	},



	make_header: function() {
		var html="";
		
		html+=this.format_cell("Nom", "nom_marital", "26%");
		html+=this.format_cell("Statut", "statut", "17%");
		html+=this.format_cell("Titre", "lib_promo", "23%");
		html+=this.format_cell("Site", "site_promo", "23%");
		html+=this.format_cell("Annee", "annee", "10%");
		html+='</thead><tr>';

		return(html);
	},

	format_cell: function(title, field, width) {
		var template_entete_ordre = new Template("<th class='border_r_blanc' width='#{width}' valign='middle' nowrap onclick=\"#{instance}.change_sort('#{champ_ordre}');\"><span #{classe}>#{titre}</span><img id='ordre_#{champ_ordre}' src='" + url_img_path + "#{direction}'/></th></th>");
		var template_entete_simple = new Template("<th class='border_r_blanc' width='#{width}' valign='middle' nowrap><span>#{titre}</span></th>");
		var o = new Object();
		o.instance = this.instance;
		o.titre = title;
		o.champ_ordre = field;
		o.width = width;

		var result = "";

		if(field != "") {
			if(field == this.order) {
				o.direction = (this.direction == "ASC" ? "tri_bas_vert.gif" : "tri_haut_vert.gif");
				o.classe = "class='colonne_verte'";
			} else {
				o.direction = "tri_bas.gif";
			}
			result = template_entete_ordre.evaluate(o);
		} else
			result = template_entete_simple.evaluate(o);

		return(result);


	},

	sort_objects: function() {
		this.json.sortCharOrder = new Array('àa_','çc_','ée_','èe_','êe_','ëe_','ïi_','îi_','ùu_');
		this.json.sortIgnoreCase = true;
		var i;
		if (this.order=='is_online' && this.direction=="DESC")
			this.json=this.json.objSort("is_online",-1, "nom_marital", -1);
		if (this.order=='nom_marital' && this.direction=="DESC")
			this.json=this.json.objSort("nom_marital", -1, "prenom", -1);
		if (this.order=='nom_marital' && this.direction=="ASC")
			this.json=this.json.objSort("nom_marital", "prenom");
		if (this.order=='statut' && this.direction=="ASC")
			this.json=this.json.objSort("statut", "nom_marital");
		if (this.order=='statut' && this.direction=="DESC")
			this.json=this.json.objSort("statut", -1, "nom_marital");
		if (this.order=='lib_promo' && this.direction=="ASC")
			this.json=this.json.objSort("lib_promo", "nom_marital");
		if (this.order=='lib_promo' && this.direction=="DESC")
			this.json=this.json.objSort("lib_promo", -1, "nom_marital");
		if (this.order=='site_promo' && this.direction=="ASC")
			this.json=this.json.objSort("site_promo", "nom_marital");
		if (this.order=='site_promo' && this.direction=="DESC")
			this.json=this.json.objSort("site_promo", -1, "nom_marital");
		if (this.order=='annee' && this.direction=="ASC")
			this.json=this.json.objSort("annee_promo", "nom_marital");
		if (this.order=='annee' && this.direction=="DESC")
			this.json=this.json.objSort("annee_promo", -1, "nom_marital");
	},
	change_sort: function(field) {
		if(this.order == field) {
			if(this.direction == "ASC") {
				this.direction = "DESC";
			} else {
				this.direction = "ASC";
			}
		} else {
			this.order = field;
			this.direction = "ASC";
		}
		this.display();
	},

	switch_connected: function() {
		var cbEnLigne = $('en_ligne');
		this.connect_status = cbEnLigne && cbEnLigne.checked;
		if(this.connect_status){
			this.pagination.set_json(this.json_connected);
		}else{
			this.pagination.set_json(this.json);
		}
	},

	/*Ouvre l'extracteur de résultats d'une recherche*/
	adm_search_extraction: function() {
		Modalbox.show(this.extraction_url + "/adm_search", {title:"Extraction des résultats de la recherche", width: 700});
	},

	/*Ouvre l'extracteur CNSIF*/
	cnisf_extraction: function() {
		//Modalbox.show(this.extraction_url + "/cnisf", {title:"EXTRACTION DES DIPLÔMÉS CNISF", width: 700});
		window.location = this.extraction_url + "/cnisf";
		alert("L'extraction CSV est en cours...Cela peut prendre quelques secondes.");
	},

	/*Ouvre l'extracteur AICESI*/
	aicesi_extraction: function() {
		window.location = this.extraction_url + "/aicesi";
		alert("L'extraction CSV est en cours...Cela peut prendre quelques secondes.");
		//Modalbox.show(this.extraction_url + "/aicesi", {title:"EXTRACTION DES DIPLÔMÉS AICESI", width: 700});
	},

	/*Annule l'export*/
	cancel_extraction: function() {
		Modalbox.hide();
	}
});

var SearchProfileAdmin = Class.create(SearchProfile, {
	initialize: function($super, instance_name, url, root_id, page_id) {
		$super( instance_name, url, root_id, page_id);
		this.extraction_url = null;
	},
	display_item: function(object, clas) {
		var result = "";
		var dom_id = "id_user_" + object.id;
		var template_ressource_liste = new Template(
			"<tr id='" + dom_id + "' class='"+clas+"'>"+
				"<td class='border_r_blanc'>#{code_personne_affiche}</td>"+
				"<td class='border_r_blanc'>#{nom_prenom}</td>"+
				"<td class='border_r_blanc'>#{statut}</td>"+
				"<td class='border_r_blanc'>#{date}</td>"+
			"</tr>");

		//on affiche la suspension après le statut
		if(object.suspendu == "1" && object.statut.indexOf("SUSPENDU") == -1)
			object.statut = object.statut + " - SUSPENDU";

		if (object.statut == '')
			object.statut = '&nbsp;';

		//Nom + prénom: 2009-11-09: vérification de la nullité du nom et du prénom
		object.nom_prenom = "<a href='javascript:" + this.instance + ".edit_user(" + object.id + ");' class='item_bleu' title='afficher la fiche publique'>" +
			(object.nom ? object.nom.capitalize() : "") + " "  + (object.prenom ? object.prenom.capitalize() : "") +
		"</a>";

		//Code personne
		object.code_personne_affiche = "<a href='javascript:" + this.instance + ".edit_user_admin(" + object.id + ");' class='item_bleu' title=\"afficher la fiche d'administration\">" +
			(object.code_personne == "0" ? "--- vide ---" : object.code_personne)+
		"</a>";

		result = template_ressource_liste.evaluate(object);
		return result;
	},


	edit_user_admin: function(id) {
		ouvrir_fiche_profil_admin(this, id);
	},

	edit_user: function(id) {
		this.show_profile(id);
	},

	/**
	 * @lastmodified 2010-03-09 remplacement de la colonne "Statut" par la colonne "Profil" dans le cadre de la recherche par profil
	 */
	make_header: function() {
		var html = "";
		html += '<thead><tr>';
		html += this.format_cell("Code Personne", "code_personne", "13%");
		html += this.format_cell("Nom", "nom", "26%");

		var subform = $('RechercheParProfil');
		if (subform != null && subform.visible()) {
			html += this.format_cell("Profil", "fonction", "24%");//recherche par profil => affichage de la colonne "Profil"
		} else {
			html += this.format_cell("Statut", "statut", "24%");
		}

		/*2010-03-10: libellé de la colonne "date" en fonction des critères de recherche*/
		var cell_text;
		if (this.criteres && (typeof(this.criteres.get('annee_debut_session')) != 'undefined'))
			cell_text = 'Date de début';//date de début de la promo
		else if (this.criteres && typeof(this.criteres.get('annee_fin_session')) != 'undefined')
			cell_text = 'Date de fin';	//date de fin de la promo
		else
			cell_text = 'Depuis';
		html += this.format_cell(cell_text, "sortable_date", "13%");
		/**/

		html += '</thead><tr>';
		return html;
	},

	sort_objects: function() {
		this.json.sortCharOrder = new Array('àa_','çc_','ée_','èe_','êe_','ëe_','ïi_','îi_','ùu_');
		this.json.sortIgnoreCase = true;
		var i;
		if (this.order=='nom' && this.direction=="DESC")
			this.json=this.json.objSort("nom", -1, "prenom", -1);
		if (this.order=='nom' && this.direction=="ASC")
			this.json=this.json.objSort("nom", "prenom");
		if (this.order=='statut' && this.direction=="ASC")
			this.json=this.json.objSort("statut", "nom");
		if (this.order=='statut' && this.direction=="DESC")
			this.json=this.json.objSort("statut", -1, "nom");
		if (this.order=='code_personne' && this.direction=="ASC")
			this.json=this.json.objSort("code_personne", "nom");
		if (this.order=='code_personne' && this.direction=="DESC")
			this.json=this.json.objSort("code_personne", -1, "nom");
		if (this.order=='sortable_date' && this.direction=="ASC")
			this.json=this.json.objSort("sortable_date", "nom");
		if (this.order=='sortable_date' && this.direction=="DESC")
			this.json=this.json.objSort("sortable_date", -1, "nom");
	},

	/*
	 *Lance la création du fichier CSV
	 *@param bool insert_criteria Dit si on tient compte des critères de recherche dans l'extraction
	 */
	start_extraction: function(type) {
		var _form = $("ExtractionForm");
		if (!_form){return;}
		var forward_criteria = type == "adm_search";
		if (forward_criteria) {
			this.criteres = build_detailed_search_admin();
			if (!this.criteres) {
				alert("Vous devez renseigner au moins un des critères.");
				return;
			}
		}
		if (forward_criteria) {
			_form.insert("<input id='AnnuaireSearchType' type='hidden' name='data[Annuaire][search_type]' value='multiple' />");
			this.criteres.each(function(c){
				_form.insert("	<input id='annuaire_"+c.key+"' type='hidden' name='data[Annuaire]["+c.key+"]' value='" +c.value + "' />");
			});
		}
		_form.submit();
		Modalbox.hide({afterHide: function() { alert("L'extraction CSV est en cours...Cela peut prendre quelques secondes."); } });
	},

	/**
	*Coche tous les choix de colonnes de l'extracteur
	IE7 OK (2010-01-15)
	IE8 OK (2010-01-15)
	*/
	auto_select: function() {
		var selector = $("auto_select");
		var rel = selector.readAttribute("id");
		selector.form.descendants("input[type=checkbox]").each(function(choice){
			if (choice.readAttribute("rel") == rel) {
				choice.checked = selector.checked ? "checked" : "";
				var td = choice.up("td.cat");
				if (td) {
					td.setStyle({backgroundColor: choice.checked ? "#ACD7BB" : "#FAACAA"});
				}
			}
		});
	}

});

var SearchProfileCommunaute = Class.create(SearchProfile, {
	initialize: function($super, instance_name, url, root_id, page_id) {
		$super( instance_name, url, root_id, page_id);
		this.order = "date_inscription_en";
		this.direction = "DESC";
	},
	display_item: function(object, clas) {
		var result = "";
		var template_ressource_liste = new Template("<tr class='"+clas+"'><td class='border_r_blanc'>#{nom_prenom}</td><td class='border_r_blanc'>#{statut}</td><td class='border_r_blanc'>#{promotion}</td><td class='border_r_blanc'>#{site_promo}</td><td class='border_r_blanc'>#{annee}</td><td class='border_r_blanc'>#{date_inscription}</td></tr>");

		//si le statut contient "non inscrit" (membre accepté en fait), pas de lien vers sa fiche
		if(object.statut.indexOf("non inscrit") == -1 )
			object.nom_prenom = "<a href='javascript:" + this.instance + ".show_profile(" + object.id + ");' class='item_bleu' >" + object.nom_marital.capitalize() + " "  +object.prenom.capitalize()+"</a>";
		else
			object.nom_prenom = object.nom_marital.capitalize() + " "  +object.prenom.capitalize();
		object.is_online = "";
		object.promotion = object.lib_promo.capitalize();
		if(object.promotion == "")		object.promotion = "&nbsp;";
		object.annee = object.annee_promo;
		if(object.annee == "")			object.annee = "&nbsp;";
		if(object.site_promo == "")		object.site_promo = "&nbsp;";
		object.statut = object.statut;
		result = template_ressource_liste.evaluate(object);
		return result;
	},
	make_header: function() {
		var html="";

		html+='<thead><tr>';
		html+=this.format_cell("Nom", "nom_marital", "20%");
		html+=this.format_cell("Statut", "statut", "14%");
		html+=this.format_cell("Titre", "lib_promo", "19%");
		html+=this.format_cell("Site", "site_promo", "23%");
		html+=this.format_cell("Année", "annee", "10%");
		html+=this.format_cell("Date inscr.", "date_inscription_en", "14%");
		html+='</thead><tr>';

		return(html);
	},
	sort_objects: function() {
		this.json.sortCharOrder = new Array('àa_','çc_','ée_','èe_','êe_','ëe_','ïi_','îi_','ùu_');
		this.json.sortIgnoreCase = true;
		var i;
		if (this.order=='is_online' && this.direction=="DESC")
			this.json=this.json.objSort("is_online",-1, "nom_marital", -1);
		if (this.order=='nom_marital' && this.direction=="DESC")
			this.json=this.json.objSort("nom_marital", -1, "prenom", -1);
		if (this.order=='nom_marital' && this.direction=="ASC")
			this.json=this.json.objSort("nom_marital", "prenom");
		if (this.order=='statut' && this.direction=="ASC")
			this.json=this.json.objSort("statut", "nom_marital");
		if (this.order=='statut' && this.direction=="DESC")
			this.json=this.json.objSort("statut", -1, "nom_marital");
		if (this.order=='lib_promo' && this.direction=="ASC")
			this.json=this.json.objSort("lib_promo", "nom_marital");
		if (this.order=='lib_promo' && this.direction=="DESC")
			this.json=this.json.objSort("lib_promo", -1, "nom_marital");
		if (this.order=='site_promo' && this.direction=="ASC")
			this.json=this.json.objSort("site_promo", "nom_marital");
		if (this.order=='site_promo' && this.direction=="DESC")
			this.json=this.json.objSort("site_promo", -1, "nom_marital");
		if (this.order=='annee' && this.direction=="ASC")
			this.json=this.json.objSort("annee_promo", "nom_marital");
		if (this.order=='annee' && this.direction=="DESC")
			this.json=this.json.objSort("annee_promo", -1, "nom_marital");
		if (this.order=='date_inscription_en' && this.direction=="ASC")
			this.json=this.json.objSort("date_inscription_en", "nom_marital");
		if (this.order=='date_inscription_en' && this.direction=="DESC")
			this.json=this.json.objSort("date_inscription_en", -1, "nom_marital");
	}
});

var SearchProfileCollaborateursCESI = Class.create(SearchProfile, {
	initialize: function($super, instance_name, url, root_id, page_id) {
		$super( instance_name, url, root_id, page_id);
		this.order = "nom_marital";
		this.direction = "ASC";
	},

	display: function() {
		if(this.json){
			this.sort_objects();

			var i;
			var html = "";
			var clas = "";
			for(i = this.pagination.begin; i<this.pagination.end; i++){
				html+= this.display_item(this.json[i], clas);
			}

			html_entete=this.make_header();
			html="<table cellspacing=\"0\" id='result' style='width: 100%'>" + html_entete + html + "</table>";

			$(this.root_id).update(html);
		}
	},

	display_item: function(object, clas) {
		var result = "";
		var dom_id = this.dom_id_item(object.id);
		var template_ressource_liste = new Template("<tr id='" + dom_id + "' class='"+clas+"'><td class='border_r_blanc'>#{nom_prenom}</td></tr>");
		//si le statut contient "non inscrit" (membre accepté en fait), pas de lien vers sa fiche
		if (object.statut && object.statut.indexOf("non inscrit") == -1) {
			//Membre inscrit
			object.nom_prenom = "<a href='javascript:" + this.instance + ".show_profile(" + object.id + ");' class='item_bleu' >" + object.nom_marital.capitalize() + " "  +object.prenom.capitalize()+"</a>";
		} else {
			object.nom_prenom = object.nom_marital.capitalize() + " "  +object.prenom.capitalize();
		}

		if(object.site_promo == "")		object.site_promo = "&nbsp;";
		result = template_ressource_liste.evaluate(object);
		return result;
	},

	make_header: function() {
		var html="";

		html+='<thead><tr>';
		html+=this.format_cell("Nom", "nom_marital", "100%");
		html+='</thead><tr>';

		return(html);
	},
	
	sort_objects: function() {
		this.json.sortCharOrder = new Array('àa_','çc_','ée_','èe_','êe_','ëe_','ïi_','îi_','ùu_');
		this.json.sortIgnoreCase = true;
		var i;
		
		if (this.order=='nom_marital' && this.direction=="DESC")
			this.json=this.json.objSort("nom_marital", -1, "prenom", -1);
		if (this.order=='nom_marital' && this.direction=="ASC")
			this.json=this.json.objSort("nom_marital", "prenom");
		
		if (this.order=='site_promo' && this.direction=="ASC")
			this.json=this.json.objSort("site_promo", "nom_marital");
		if (this.order=='site_promo' && this.direction=="DESC")
			this.json=this.json.objSort("site_promo", -1, "nom_marital");
	}
});

var SearchProfileInvestigation = Class.create(SearchProfile, {
	initialize: function($super, instance_name, url, root_id, page_id) {
		$super( instance_name, url, root_id, page_id);
		this.order = "nom";
		this.direction = "DESC";
	},

	display: function() {
		if(this.json){
			this.sort_objects();

			var i;
			var html = "";
			var clas = "";
			for(i = this.pagination.begin; i<this.pagination.end; i++){
				html+= this.display_item(this.json[i], clas);
			}

			html_entete=this.make_header();
			html="<table cellspacing=\"0\" id='result'>" + html_entete + html + "</table>";

			$(this.root_id).update(html);
		}
	},

	delete_item: function(id){
		// retirer l'objet de la liste
		i = this.find_rang_item_by_id(id);
		if(i < 0)
			return;
		this.json.splice(i, 1);
		// effacer son <tr>
		dom_id = this.dom_id_item(id);
		$(dom_id).remove();
	},

	// id de l'objet dom dans la liste
	dom_id_item: function(id) {
		return("id_candidat_"+id);
	},

	display_item: function(object, clas) {
		var result = "";
		var template_ressource_liste = new Template("<tr id='id_candidat_#{id}' class='"+clas+"'><td class='border_r_blanc'>#{nom_prenom}</td><td class='border_r_blanc'>#{produit}</td><td class='border_r_blanc'>#{etablissement}</td><td class='border_r_blanc'>#{annee_obtention}</td><td class='border_r_blanc'>#{date}</td><td class='border_r_blanc'>#{traite_label}</td></tr>");

		object.nom_prenom = "<a href='javascript:" + this.instance + ".edit_investigation(" + object.id + ");' class='item_bleu' >" + object.nom.capitalize() + " "  +object.prenom.capitalize()+"</a>";
		if(object.traite == "1")
			object.traite_label = "oui";
		else
			object.traite_label = "non";
		result = template_ressource_liste.evaluate(object);
		return result;
	},

	edit_investigation: function(id)
	{
		ouvrir_fiche_candidat(this, id);
	},

	make_header: function() {
		var html="";

		html+='<thead><tr>';
		html+=this.format_cell("Nom", "nom", "20%");
		html+=this.format_cell("Titre", "produit", "27%");
		html+=this.format_cell("Etablissement", "etablissement", "27%");
		html+=this.format_cell("Année", "annee_obtention", "10%");
		html+=this.format_cell("Date demande", "created", "10%");
		html+=this.format_cell("Traité", "traite", "6%");
		html+='</thead><tr>';

		return(html);
	},
	sort_objects: function() {
		this.json.sortCharOrder = new Array('àa_','çc_','ée_','èe_','êe_','ëe_','ïi_','îi_','ùu_');
		this.json.sortIgnoreCase = true;
		var i;
		if (this.order=='nom' && this.direction=="DESC")
			this.json=this.json.objSort("nom", -1, "prenom", -1);
		if (this.order=='nom' && this.direction=="ASC")
			this.json=this.json.objSort("nom", "prenom");
		if (this.order=='produit' && this.direction=="ASC")
			this.json=this.json.objSort("produit", "nom");
		if (this.order=='produit' && this.direction=="DESC")
			this.json=this.json.objSort("produit", -1, "nom");
		if (this.order=='etablissement' && this.direction=="ASC")
			this.json=this.json.objSort("etablissement", "nom");
		if (this.order=='etablissement' && this.direction=="DESC")
			this.json=this.json.objSort("etablissement", -1, "nom");
		if (this.order=='created' && this.direction=="ASC")
			this.json=this.json.objSort("created", "nom");
		if (this.order=='created' && this.direction=="DESC")
			this.json=this.json.objSort("created", -1, "nom");
		if (this.order=='annee_obtention' && this.direction=="ASC")
			this.json=this.json.objSort("annee_obtention", "nom");
		if (this.order=='annee_obtention' && this.direction=="DESC")
			this.json=this.json.objSort("annee_obtention", -1, "nom");
		if (this.order=='traite' && this.direction=="ASC")
			this.json=this.json.objSort("traite", "nom");
		if (this.order=='traite' && this.direction=="DESC")
			this.json=this.json.objSort("traite", -1, "nom");

	}
});

var SearchProfileAnnuairePerso = Class.create(SearchProfile, {
	initialize: function($super, instance_name, url, root_id, page_id) {
		$super( instance_name, url, root_id, page_id);
		this.order = "nom";
		this.direction = "DESC";
		this.selected_ids = new Array();
		this.toggle_recipient_url = "";
		this.toggle_many_recipients_url = "";
		this.supprimer_contact_url = "";
		this.recipientsListDiv = "recipients";
		this.recipientsListContactForm = "destinataires_contact";
		this.recipientsListInvitForm = "destinataires_invit";
		this.recipientsListFwdPa = "destinataires_fwd_pa";
	},

	add2recipientsList: function(profil_id){
		var person = this.getInfos(profil_id);
		var close_button = new Element('img', {	src:		url_img_path+"pictocapacite_supprimer.gif",
												onclick:	"javascript:"+this.instance+".toggle_recipient("+profil_id+");",
												alt:		"supprimer ce contact des destinataires du message",
												title:		"supprimer ce contact des destinataires du message"}).addClassName("close_button");
		var recipientElement = new Element('span', {id:"recipient_"+profil_id}).update(person.nom_marital.toUpperCase()+" "+person.prenom.truncate(2,".").capitalize()).insert({bottom:close_button}).addClassName('recipient');
		//s'il n'existe pas déjà, on le rajoute
		if($(this.recipientsListDiv).select("span#recipient_"+profil_id).size() == 0)
			$(this.recipientsListDiv).insert({bottom: recipientElement});
		this.synchroniseRecipients();

		var person = new Object({id: profil_id, checked: true});
		this.check_box(person);
	},

	check_box: function(person){
		var checked = person.checked;
		var checkBoxElement = $('cb_'+person.id);
		if(checkBoxElement)		checkBoxElement.checked = checked;
	},

	deleteFromRecipientsList: function(profil_id){
		//s'il existe, on le supprime
		var recipientToDelete = $(this.recipientsListDiv).select("span#recipient_"+profil_id);
		if(recipientToDelete.size() != 0){
			recipientToDelete[0].remove();
		}
		this.synchroniseRecipients();

		var person = new Object({id: profil_id, checked: false});
		this.check_box(person);
	},

	display: function() {
		if(this.json){
			this.sort_objects();

			var i;
			var html = "";
			var clas = "";
			for(i = this.pagination.begin; i<this.pagination.end; i++){
				html+= this.display_item(this.json[i], clas);
			}

			html_entete=this.make_header();
			html="<table cellspacing=\"0\" id='result'>" + html_entete + html + "</table>";
			$(this.root_id).update(html);

			for(i = this.pagination.begin; i<this.pagination.end; i++){
				this.check_box(this.json[i]);
			}
		}
	},

	delete_item: function(id){
		// retirer l'objet de la liste
		i = this.find_rang_item_by_id(id);
		if(i < 0)
			return;
		this.json.splice(i, 1);
		// effacer son <tr>
		dom_id = this.dom_id_item(id);
		$(dom_id).remove();
	},

	// id de l'objet dom dans la liste
	dom_id_item: function(id) {
		return("id_candidat_"+id);
	},

	display_item: function(object, clas) {
		var result = "";
		var dom_id = this.dom_id_item(object.id);
		var template_ressource_liste = new Template("<tr id='" + dom_id + "' class='"+clas+"'><td class='border_r_blanc'><input type='checkbox' id='cb_#{id}' onchange='javascript:"+this.instance+".toggle_recipient(#{id});'/></td><td class='border_r_blanc'>#{nom_prenom}</td><td class='border_r_blanc etoile'>#{favori_img}</td><td class='border_r_blanc'>#{promotion}</td><td class='border_r_blanc'>#{site_promo}</td><td class='border_r_blanc'>#{annee}</td><td><img src='"+url_img_path+"supprimer_contact.gif' alt='supprimer de mon annuaire personnel' title='supprimer de mon annuaire personnel' class='supprimer_contact' onclick='javascript:"+this.instance+".deleteContact(#{id});'/></td></tr>");
		object.is_online = "";
		object.promotion = object.lib_promo.capitalize();
		object.annee = object.annee_promo;
		//si le statut contient "non inscrit" (membre accepté en fait), pas de lien vers sa fiche
		if (object.statut && object.statut.indexOf("non inscrit") == -1) {
			//Membre inscrit
			object.nom_prenom = "<a href='javascript:" + this.instance + ".show_profile(" + object.id + ");' class='item_bleu' >" + object.nom_marital.capitalize() + " "  +object.prenom.capitalize()+"</a>";
		} else {
			object.nom_prenom = object.nom_marital.capitalize() + " "  +object.prenom.capitalize();
		}
		if(object.promotion == "")		object.promotion = "&nbsp;";
		if(object.annee == "")			object.annee = "&nbsp;";
		if(object.site_promo == "")		object.site_promo = "&nbsp;";

		if(object.favori)				object.favori_img = "<img src='"+url_img_path+"icones/etoile_fd_blanc.gif' alt='Cette personne fait partie de vos favoris' title='Cette personne fait partie de vos favoris' />";
		else							object.favori_img = "&nbsp;";

		result = template_ressource_liste.evaluate(object);

		if(object.checked)				this.add2recipientsList(object.id);
		else							this.deleteFromRecipientsList(object.id);

		return result;
	},

	edit_investigation: function(id)
	{
		ouvrir_fiche_candidat(this, id);
	},

	format_cell: function(title, field, width, cls) {
		var class_name = (cls != null) ? cls : "";
		var template_entete_ordre = new Template("<th class='border_r_blanc "+cls+"' width='#{width}' valign='middle' nowrap onclick=\"#{instance}.change_sort('#{champ_ordre}');\"><span #{classe}>#{titre}</span><img id='ordre_#{champ_ordre}' src='" + url_img_path + "#{direction}'/></th></th>");
		var template_entete_simple = new Template("<th class='border_r_blanc "+cls+"' width='#{width}' valign='middle' nowrap><span>#{titre}</span></th>");
		var o = new Object();
		o.instance = this.instance;
		o.titre = title;
		o.champ_ordre = field;
		o.width = width;

		var result = "";
		if(field != "") {
			if(field == this.order) {
				o.direction = (this.direction == "ASC" ? "tri_bas_vert.gif" : "tri_haut_vert.gif");
				o.classe = "class='colonne_verte'";
			} else {
				o.direction = "tri_bas.gif";
			}
			result = template_entete_ordre.evaluate(o);
		} else
			result = template_entete_simple.evaluate(o);

		return(result);


	},

	getInfos: function(profil_id){
		var person = new Object();
		this.json.each(function(p){
			if(p.id == profil_id)	person = p;
		});
		return person;
	},

	make_header: function() {
		var html="";
		html+='<thead><tr>';
		html+=this.format_cell("<input type='checkbox' id='check_all' onclick='javascript:"+this.instance+".tick_all_checkboxes();'/>", "", "4%", null);
		html+=this.format_cell("Nom", "nom", "20%", null);
		html+=this.format_cell("<img src='"+url_img_path+"icones/etoile_fd_beige.gif' onclick='javascript:"+this.instance+".change_sort(\"favori\");' />", "", "4%", "center");
		html+=this.format_cell("Titre", "produit", "27%", null);
		html+=this.format_cell("Etablissement", "etablissement", "25%", null);
		html+=this.format_cell("Année", "annee_obtention", "10%", null);
		html+=this.format_cell("", "", "5%", "noborder");
		html+='</thead><tr>';

		return(html);
	},
	sort_objects: function() {
		this.json.sortCharOrder = new Array('àa_','çc_','ée_','èe_','êe_','ëe_','ïi_','îi_','ùu_');
		this.json.sortIgnoreCase = true;
		var i;
		if (this.order=='nom' && this.direction=="DESC")
			this.json=this.json.objSort("nom", -1, "prenom", -1);
		if (this.order=='nom' && this.direction=="ASC")
			this.json=this.json.objSort("nom", "prenom");
		if (this.order=='produit' && this.direction=="ASC")
			this.json=this.json.objSort("produit", "nom");
		if (this.order=='produit' && this.direction=="DESC")
			this.json=this.json.objSort("produit", -1, "nom");
		if (this.order=='etablissement' && this.direction=="ASC")
			this.json=this.json.objSort("etablissement", "nom");
		if (this.order=='etablissement' && this.direction=="DESC")
			this.json=this.json.objSort("etablissement", -1, "nom");
		if (this.order=='annee_obtention' && this.direction=="ASC")
			this.json=this.json.objSort("annee_obtention", "nom");
		if (this.order=='annee_obtention' && this.direction=="DESC")
			this.json=this.json.objSort("annee_obtention", -1, "nom");
		if (this.order=='favori' && this.direction=="ASC")
			this.json=this.json.objSort("traite", "nom");
		if (this.order=='favori' && this.direction=="DESC")
			this.json=this.json.objSort("traite", -1, "nom");

	},

	deleteContact: function(id){
		var person = this.getInfos(id);
		var displayedName = person.nom_marital.capitalize() + " " + person.prenom.capitalize();
		if(!confirm("Vous êtes sur le point de supprimer "+displayedName+" de votre annuaire personnel, continuer ?"))		return false;
		var url = this.supprimer_contact_url + id;
		var callBack = this.search_all.bind(this);
		new Ajax.Request(url, {evalJS: "force", onComplete: callBack});
	},

	emptyRecipients: function(){
		return $(this.recipientsListDiv).innerHTML.empty();
	},

	getRecipientsNumber: function(){
		return $(this.recipientsListDiv).childElements().size();
	},

	//duplique la liste principale (masquée) des destinataires dans les 3 formulaires
	synchroniseRecipients: function(){
		var listUpToDate = $(this.recipientsListDiv).innerHTML;
		$(this.recipientsListContactForm).update(listUpToDate);
		$(this.recipientsListInvitForm).update(listUpToDate);
		$(this.recipientsListFwdPa).update(listUpToDate);
	},

	// inverse la sélection des cases à cocher
	tick_all_checkboxes: function(){
		var tick_all = $('check_all').checked;
		var ids = new Array();
		$('result').getElementsBySelector("input[type=checkbox]").each(function(checkbox){
			checkbox.checked = tick_all;
			if(checkbox.id != "check_all")	ids.push(checkbox.id.sub("cb_",""));
		});

		var add = ($('check_all').checked) ? "1" : "0";
		var url = this.toggle_many_recipients_url+add;	// si check_all est coché on ajoute tout le monde, sinon on les vire
		if(url == "")		return false;
		var post = "data[ContactsProfil][recipients]="+Object.toJSON(ids);

//		if(!watchIfAjaxAlreadyRunning(0)){
//			registerAjax(0)
			new Ajax.Request(url, {	postBody: post, evalJS: "force" });
//			unregisterAjax(0);
//		}
	},

	toggle_recipient: function(id){
		var url = this.toggle_recipient_url + id;
		if( url == "")		return false;

//		if(!watchIfAjaxAlreadyRunning(id)){
//			registerAjax(id);
			new Ajax.Request(url, {	evalJS:	 "force" });
//			unregisterAjax(id);
//		}
	}
});

/*Annuaire Public*/
var SearchProfileAnnuairePublic = Class.create(SearchProfile, {
	initialize: function($super, instance_name, url, root_id, page_id)
	{
		$super(instance_name, url, root_id, page_id);
		this.json = null;
		this.order = "nom";
		this.direction = "DESC";
	},

	display: function()
	{
		if(!this.json){
			return;
		}
		this.sort_objects();
		
		var i;
		var html = "";
		var clas = "";
		var divResults = $(this.root_id);
		
		for(i = this.pagination.begin; i<this.pagination.end; i++){
			html+= this.display_item(this.json[i], clas);
		}
		if(html == ""){
			//pas de résultats : affichage du message "Aucun résultat" et camouflage des éléments de pagination
			html = "<center>Aucun résultat</center>";
			divResults.update(html);
			var divPagination = divResults.next('div');
			if(divPagination)
				divPagination.hide();
		}else{
			html_entete = this.make_header();
			html = "<table cellspacing=\"0\" id='result' style='width: 100%'>" + html_entete + html + "</table>";
			divResults.update(html);
		}
		Modalbox.resizeToContent();
	},
	
	display_item: function(object, clas)
	{
		var result = "";
		var dom_id = this.dom_id_item(object.id);
		var template_ressource_liste = new Template("<tr id='" + dom_id + "' class='"+clas+"'><td class='border_r_blanc'>#{nom_prenom}</td><td class='border_r_blanc'>#{promotion}</td><td class='border_r_blanc'>#{annee_promo}</td><td class='border_r_blanc'>#{site_promo}</td></tr>");
		object.nom_prenom = object.nom_marital.capitalize() + " "  +object.prenom.capitalize();
		object.promotion = object.lib_promo.capitalize();
		if(object.promotion == "")		object.promotion = "&nbsp;";
		if(object.site_promo == "")		object.site_promo = "&nbsp;";
		result = template_ressource_liste.evaluate(object);
		return result;
	},

	make_header: function()
	{
		var html="";
		html+='<thead><tr>';
		html+=this.format_cell("Nom", "nom_marital", "30%");
		html+=this.format_cell("Titre", "lib_promo", "40%");
		html+=this.format_cell("Année", "annee", "15%");
		html+=this.format_cell("Centre", "site_promo", "15%");
		html+='</thead><tr>';
		return(html);
	},
	
	search_detailed: function(criteres) {
		//ouverture de la modalbox dès le lancement de la recherche pour que l'utilisateur voit que sa demande est en cours de traitement
		Modalbox.show($('annuaire_public_search_results'), {title:"Annuaire : Résultats de la recherche", width: 700});
		
		//recherche des résultats et mise à jour de la modalbox
		this.criteres = criteres;
		var search_url = this.url;
		var callback = this.callback_load;
		var postdata = "data[Annuaire][search_type]=multiple";

		criteres.each(function(c){postdata += "&data[Annuaire]["+c.key+"]="+c.value});

		new Ajax.Request(search_url, {
			method: 'post',
			postBody: postdata,
			evalJS: false,
			onSuccess: function(transport) {
				var json;
				try {
					var result = transport.responseText;
					if(!isNaN(result)){
						//la réponse est un nombre => le nombre de résultats dépasse le nombre de résultats max par recherche => affichage d'une alerte js
						alert("Les résultats de cette recherche comportent plus de "+result+" profils. Veuillez affiner vos critères.");
						return;
					}else{
						//la réponse n'est pas très volumineuse => affichage des résultats
						json = eval('(' + result + ')');//evalJSON manuel pour essayer de gagner en performance
						callback(json);
					}
				} catch(e) {
					if(js_debug > 0)
						alert("SearchProfile error : " + e);
					json = null;
				}
			}
		});
	}
});

/* ---surveillance des ajax ---*/

var table_urls = [];

function registerAjax(url){
	table_urls.push(url);
}

function unregisterAjax(url){
	var nouveau = [];
	var N = table_urls.length ;
	for(i=0 ; i < N;  i++)
	{
		str = table_urls[i];
		if(str != url)			nouveau.push(str);
	}
	table_urls = nouveau;
}

function show_urls(){
	var s = "";
	for(i=0 ; i<table_urls.length; i++)
	{
		s += ' ' + table_urls[i];
//		$('recipients2').update(s);
	}
}

function watchIfAjaxAlreadyRunning(url){
	var running = false;
	for(i=0 ; i < table_urls.length;  i++)
	{
		if(table_urls[i] == url){
			running = true; break;
		}
	}
	return running;
}

function check_country(){
	if( $('pays_residence_id').value == '62' || $('pays_residence_id').value == '' ){
		$('region_id').show();
		$('dept_no').show();
		$('dpt_name').update('');
	} else {
		$('region_id').hide();
		$('region_id').value = '';
		$('dept_no').hide();
		$('dept_no').value = '';
		$('dpt_name').update('Les régions et départements sont seulement disponibles pour la France.');
	}
}

function get_dpt_name(){
	$('dpt_name').update(hash_dpt.get($('dept_no').value));
}

function toggle_detailed_search_content(){
	if(	$('detailed_search_content').getStyle('display') == 'none'	){
		$('detailed_search_content').show();
		$('plus_detailed_search').src = url_img_path + "moins.gif";
	} else {
		$('detailed_search_content').hide();
		$('plus_detailed_search').src = url_img_path + "plus.gif";
	}
}

/*@since 2009-12-04: construit les critères de recherche*/
function build_criteria(inputs, checkboxes) {
	var criteres = new Hash();

	/*Inputs*/
	for (j = 0; j < inputs.length; j++) {
		var name = inputs[j];
		if (current_form_id == null) {
			var el = $(name);
		} else {
			//on a un formulaire multicritères => on doit spécifier le nom du sous-formulaire => current_form_id
			var el = $(current_form_id).select('[id="'+name+'"]')[0];
		}
		if(el && el.value != '' && el.value != 'jj/mm/aaaa') {
			criteres.set(name, el.value);
		}
	}

	/*Checkboxes*/
	for (var j = 0; j < checkboxes.length; j++) {
		var name = checkboxes[j];
		if (current_form_id == undefined) {
			var cb = $(name);
		} else {
			//on a un formulaire multicritères => on doit spécifier le nom du sous-formulaire => current_form_id
			var cb = $(current_form_id).select('[id="'+name+'"]')[0];
		}
		if (cb && cb.checked){
			criteres.set(name, cb.value);
		}
	}

	return criteres;
}
function valid_detailed_search(){
	var inputs = new Array("search_content" , "produit_id", "annee", "etablissement_id", "secteur_id", "domaine_id", "pays_residence_id", "region_id", "dept_no", "statut_id", "fonction");
	var checkboxes = new Array("en_ligne");

	var criteres = build_criteria(inputs, checkboxes);
	if (criteres.toArray().length > 0) {
		search_2.search_detailed(criteres);
	} else {
		alert("Vous devez renseigner au moins un des critères.");
	}
}

//2011-09-27: valide le requêteur de l'annuaire public
function validAnnuairePublicSearch(){
	var inputs = new Array("search_content", "prenom", "produit_id", "annee", "etablissement_id");
	var checkboxes = new Array();
	var criteres = build_criteria(inputs, checkboxes);
	if (criteres.toArray().length > 0) {
		search_2.search_detailed(criteres);
	} else {
		alert("Vous devez renseigner au moins un des critères.");
	}
}

//2010-03-08: ajout des profils désormais gérés avec des cases à cocher
function build_detailed_search_admin() {
	var inputs = new Array("search_content", "code_personne", "statut_id", "status_date", "etablissement_id", "annee_debut_session", "annee_fin_session", "produit_id", "code_session", "marque");
	var checkboxes = new Array("suspendu", "en_ligne", "is_cnisf", "is_master_AICESI");
	var criteria = build_criteria(inputs, checkboxes);

	//2010-03-08: profils non membre
	var profilsNomMembre = new Array("cbAdministrateur", "cbWebmaster", "cbAnimateur", "cbCollaborateurCESI", "cbInvite", "cbS2C");
	var j = 0;
	for (p in profilsNomMembre) {
		var cb = $(profilsNomMembre[p]);
		if (cb && cb.checked) {
			criteria.set("fonction][" + j, cb.value);
			j++;
		}
	}

	//2010-03-09: statuts du membre
	var statuts = new Array("cbPreInscrit", "cbNPAI", "cbAccepte", "cbInscrit", "cbAbonne", "cbStagiaireActif", "cbGratuitNouveauDiplome", "cbGratuitAncienDiplome",
	"cbGratuitPeremptionAbonnement", "cbGratuitPrivilege", "cbGratuitAttenteSuppression");
	var j = 0;
	for (s in statuts) {
		var cb = $(statuts[s]);
		if (cb && cb.checked) {
			criteria.set("statut_id][" + j, cb.value);
			j++;
		}
	}

	//2010-03-09: états de diplôme
	// états modifié le 29 nov 2010
	var etats_diplome = new Array("rdEnFormation", "rdEnAttente", "rdAjourne", "rdDiplome");
	for (etat in etats_diplome) {
		var cb = $(etats_diplome[etat]);
		if (cb && cb.checked) {
			criteria.set("etat_diplome", cb.value);
			break;
		}
	}

	return criteria;
}
/*
 *@lastModified 2009-12-04: nommage objectif des champs + factorisation
 */
function valid_detailed_search_admin(){
	var criteres = build_detailed_search_admin();
	if (criteres.toArray().length > 0) {
		search_2.search_detailed(criteres);
	} else {
		alert("Vous devez renseigner au moins un des critères.");
	}
}

var AnnuaireAdminCommunaute = Class.create(SearchProfile, {
	initialize: function($super, instance_name, json, root_id, page_id) {
		$super( instance_name, "", root_id, page_id);
		this.pagination = new Pagination(null, page_id, this);
		this.json = json;
		this.order = "AdhesionCommunaute.id"; // sens du tri parmi : ASC ou DESC
		this.direction = "DESC";
	},

	init_display: function() {
		this.pagination.set_json(this.json);
	},

	display_item: function(object, clas) {
		var result = "";
		var template = "<tr class='"+clas+"'>"+
						"<td class='border_r_blanc'>#{nom_prenom}</td>"+
						"<td class='border_r_blanc'>#{statut}</td>"+
						"<td class='border_r_blanc'>#{statut_demande}&nbsp;</td>"+
						"<td class='border_r_blanc'>#{actions}</td></tr>";

		var template_ressource_liste = new Template(template);
		object.nom_prenom = "<a href='javascript:" + this.instance + ".show_profile(" + object.profil_id + ");' class='item_bleu' >" + object.nom.capitalize() + " "  +object.prenom.capitalize()+"</a>";
		if (object.valide == 1){
			if (object.is_admin == 1){
				if (object.statut == '')
					object.statut = "Administrateur";

				//liste d'actions sur un membre admin: aucune
				object.actions = "&nbsp;";
			} else{
				if (object.statut == '')
					object.statut = "Membre";

				object.actions = "";
				if (object.t_actions) {
					//liste d'actions sur un membre
					object.actions += "<span onclick='"+this.instance+".toggleActions("+object.profil_id+", " + object.communaute_id + ");' class='item_bleu' ><img src='"+url_img_path+"picto-cadenas-petit.gif' style='border:0px solid #000000;' /></span>";
					object.actions += "<ul id='ctxActions_"+object.profil_id+"_"+object.communaute_id+"' class='ctxActions' style='display: none'>";
					//on a une liste d'actions
					for (var j = 0; j < object.t_actions.length; j++)
						object.actions += '<li><a href="#" onclick="javascript: '+this.instance+'.confirmAction(\''+object.t_actions[j].href+'\', \''+object.t_actions[j].message+'\');" class="item_bleu"'+(object.t_actions[j].active == 1 ? '' : ' disabled')+'>'+object.t_actions[j].name+'</a></li>';
					object.actions += "</ul>";
				} else {
					object.actions = "&nbsp;";
				}
			}
		}else{
			object.statut = "En attente de validation";

			//liste d'actions sur un utilisateur non membre
			object.actions  = "<span onclick='"+this.instance+".toggleActions("+object.profil_id+", " + object.communaute_id + ");' class='item_bleu' ><img src='"+url_img_path+"picto-cadenas-petit.gif' style='border:0px solid #000000;' /></span>";
			object.actions += "<ul id='ctxActions_"+object.profil_id+"_"+object.communaute_id+"' class='ctxActions' style='display: none'>";
			//lien "valider une inscription"
			object.actions += "<li><img src='"+url_img_accepter+"' style='border:0px solid #000000' title=\"Valider l\'inscription\" alt=\"Valider l\'inscription\" />&nbsp;<a href='"+url_validation_inscription+object.adhesion_id+"' class='item_bleu'>Valider l'inscription</a></li>";
			//lien "exclure de la communauté"
			object.actions += "<li><img src='"+url_img_refuser+"' style='border:0px solid #000000; margin-right: 7px' title='Exclure de la communauté' alt='Exclure de la communauté' />&nbsp;<a href='#' onclick='javascript: "+this.instance+".supprimer_de_la_communaute("+object.adhesion_id+");' class='item_bleu'>Exclure de la communauté</a></li>";
			object.actions += "</ul>";
		}
		result = template_ressource_liste.evaluate(object);
		return result;
	},
	make_header: function() {
		var html="";

		html+='<thead><tr>';
		html+=this.format_cell("Nom", "nom", "20%");
		html+=this.format_cell("Profil dans la communaute", "statut", "14%");
		html+=this.format_cell("Profil demandé", "statut_demande", "14%");
		html+=this.format_cell("Actions", "", "13%");
		html+='</thead><tr>';

		return(html);
	},
		sort_objects: function() {
		this.json.sortCharOrder = new Array('àa_','çc_','ée_','èe_','êe_','ëe_','ïi_','îi_','ùu_');
		this.json.sortIgnoreCase = true;
		var i;
		if (this.order=='nom' && this.direction=="DESC")
			this.json=this.json.objSort("nom", -1, "prenom", -1);
		if (this.order=='nom' && this.direction=="ASC")
			this.json=this.json.objSort("nom", "prenom");
		if (this.order=='valide' && this.direction=="ASC")
			this.json=this.json.objSort("valide", "nom");
		if (this.order=='valide' && this.direction=="DESC")
			this.json=this.json.objSort("valide", -1, "nom");
	},
	change_sort: function(field) {
		if(this.order == field) {
			if(this.direction == "ASC") {
				this.direction = "DESC";
			} else {
				this.direction = "ASC";
			}
		} else {
			this.order = field;
			this.direction = "ASC";
		}
		this.display();
	},
	supprimer_de_la_communaute: function(adh_id) {
		if(confirm("Voulez-vous supprimer cette adhésion à la communauté ?"))
			window.location = url_desinscription_communaute + adh_id + "/1";
	},
	rendre_administrateur: function(profil_id, communaute_id) {
		if(confirm("Voulez-vous donner l'administration de cette communauté à ce membre ?"))
			window.location = url_donner_administration + profil_id + "/" + communaute_id;
	},
	/*2010-05-03: déplie la liste des actions possibles sur un membre de la communauté*/
	toggleActions: function(profil_id, communaute_id) {
		var ctx = $('ctxActions_' + profil_id + '_' + communaute_id);
		if (!ctx) return;
		if (ctx.visible()) ctx.hide();
		else ctx.show();
	},
	/*2010-05-04*/
	confirmAction: function(url, message) {
		if (window.confirm(message)) {
			window.location = url;
			return true;
		}
		return false;
	}
});



//2010-02-18: lance l'extraction
function start_extraction() {
	if (!search_2) return;
	if ($("extraction_cnisf").checked) {
		search_2.cnisf_extraction();
	} else if ($('extraction_aicesi').checked) {
		search_2.aicesi_extraction();
	}
}
//2010-02-18: extraction: déplie/replie la procédure d'ouverture des fichiers csv avec excel
function toggleProcedureExtraction() {
	var tr = $("consigne_extraction");
	var a = tr.down("td.libelle").down("a");
	var span = tr.down("td.consigne").down("span");
	if (span.visible()) {
		span.hide();
		a.title = "Déplier la procédure";
	} else {
		span.show();
		a.title = "Replier la procédure";
	}
}

//2010-11-29 : factorisée ici
function couleur_lettre_en_cours(id){
	for(var i = 65; i <= 90; i++) {
		var une_lettre = $('lettre' + i);
		if (!une_lettre) return;//si on n'a pas la lettre c'est que l'abécédaire n'est pas dispo => exit
		une_lettre.setStyle({'color': '#105BED'});
	}
	if (id != null) {
		var la_lettre = $('lettre'+id);
		if (la_lettre) la_lettre.setStyle({'color': '#000'});
	}
	var tous = $('tous');
	if (tous) {
		var color = (id != null) ? '#105BED' : '#000';
		tous.setStyle({'color': color});
	}
}
