var autoCompleteAddress = new Class({
	
	Implements : [Options, Events],
	
	options : {
		elCity : null,
		elCode : null,
		elDepartement : null,
		url : null,
		autoCompleteCity : true
	},
	
	
	initialize : function (options) {
		this.setOptions(options);
		
		this._bound = {
			_checkChange : this._checkChange.bind(this),
			_checkResponse : this._checkResponse.bind(this),
			_cityCheckKey : this._cityCheckKey.bind(this),
			_cityOnBlur : this._cityOnBlur.bind(this),
			_checkResponseCity : this._checkResponseCity.bind(this)
		};
		
		if (!this.options.request) {
			this.options.request = new Request.JSON({
				onComplete : this._bound._checkResponse,
				method : 'post'
			});
			if (this.options.url) {
				this.options.request.setOptions({url: this.options.url});
			}
		}
		this._initEvents();
	},
	
	
	setElCode : function (el) {
		this._removeEvent(el);
		this.options.elCode =  $(el);
		this._initEvents();
		return this;
	},
	
	setElCity : function (el) {
		this._removeEvent(el);
		this.options.elCity =  $(el);
		this._initEvents();
		return this;
	},
	
	setElDepartement : function (el) {
		this._removeEvent(el);
		this.options.elDepartement =  $(el);
		this._initEvents();
		return this;
	},
	
	
	/*
	 * Initialise les évènements sur les champs
	 * return autoCompleteAdresse
	 */
	_initEvents : function () {
		var els = [];
		
		if (this.options.elCode) {
			els.push(this.options.elCode);
		}
		
		if (this.options.elCity) {
			els.push(this.options.elCity);
		}
		
		if (this.options.elDepartement) {
			els.push(this.options.elDepartement);
		}
		
		this._removeEvent(els);
		$each(els, function (el) {
			el.addEvent('change', this._bound._checkChange);
		}.bind(this));
		
		this._cityStartAutoComplete();
		
		return this;
	},
	
	_removeEvent : function(els) {
		if ($type(els) != 'array') {
			els = [els];
		}
		$each(els, function (el) {
			el.removeEvent('change', this._bound._checkChange);
		}.bind(this));
	},
	
	
	/*
	 * Contrôle les changements de valeur des champs
	 * return autoCompleteAdresse
	 */
	_checkChange : function (event) {
		//event.stop();
		this._event = event;
		var params = {};
		
		if (this.options.request && this.options.request.running) {
			this.options.request.cancel();
		}
		
		if (event.target == this.options.elDepartement) {
			params.type = 'departement';
		} else if (event.target == this.options.elCity) {
			params.type = 'city';
		} else if (event.target == this.options.elCode) {
			params.type = 'code';
		}
		
		if (['select', 'input'].contains(event.target.get('tag'))) {
			params.value = event.target.get('value').trim();
		}
		
		if (params.value && params.data && this.options.request.options.url) {
			this.options.request.setOptions({data: params});
			this.options.request.send();
		}
		
		return this;
	},
	
	
	/*
	 * Contrôle les informations reçu
	 * return autoCompleteAddress
	 */
	_checkResponse : function (datas) {
		if (!datas.response) {
			return;
		}
		
		var animation = [];
		
		if (datas.response.code && datas.response.code != this.options.elCode.get('value')) {
			if (this.options.elCode.get('value') != '') {
				if (window.confirm('Remplacer votre code postal «'+this.options.elCode.get('value')+'» par «'+datas.response.code+'» ?')) {
					this.options.elCode.set('value', datas.response.code);
					animation.push(this.options.elCode);
				}
			} else {
				this.options.elCode.set('value', datas.response.code);
				animation.push(this.options.elCode);
			}
		}
		
		if (datas.response.city && datas.response.city != this.options.elCity.get('value')) {
			this.options.elCity.set('value', datas.response.city);
			animation.push(this.options.elCity);
		}
		
		if (datas.response.departement && datas.response.departement != this.options.elDepartement.get('value')) {
			this._event.target = this.options.elDepartement;
			this.options.elDepartement.set('value', datas.response.departement).
				fireEvent('change', [this._event]);
			animation.push(this.options.elDepartement);
		}
		
		if (animation.length) {
			$each(animation, function (el) {
				var color = el.getStyle('background-color');
				el.set('tween', {duration: 1000}).tween('background-color', '#0F0', color);
			});
		}
		
		this.fireEvent('data', [datas.type, datas.response]);
		return this;
	},
	
	
	/*********************************************************
	 * Cette partie sert à l'auto-complétion du champ ville  *
	 */
	
	/*
	 * Démarre l'auto-complétion des villes
	 */
	_cityStartAutoComplete : function () {
		if (!this.options.elCity || !this.options.autoCompleteCity) {
			return;
		}
		
		this.options.elCity.addEvents({
			'keyup': this._bound._cityCheckKey,
			'blur': this._bound._cityOnBlur
		});
		
		this._citiesWindow = new Element('div');
		this._citiesWindow.addClass('fenetre-select')
			.setStyle('position', 'absolute');
		
		this.options.requestAutoCompleteCity = new Request.JSON({
			onComplete : this._bound._checkResponseCity,
			method : 'post',
			data : {type: 'searchCities'}
		});
		if (this.options.url) {
			this.options.requestAutoCompleteCity.setOptions({url: this.options.url});
		}
	},
	
	
	_cityCheckKey : function (event) {
		$clear(this._timerCheckCity);
		if (this.options.requestAutoCompleteCity) {
			this.options.requestAutoCompleteCity.cancel();
		}
		this._timerCheckCity = this._getCities.delay(300, this, [event]);
	},
	
	
	/*
	 * Ferme la fenêtre des villes automatiques quand on quitte le champ
	 */
	_cityOnBlur : function (event) {
		$clear(this._timerCloseBlur);
		this._timerCloseBlur = this._closeCitiesWindow.delay(100, this);
	},
	
	
	_checkResponseCity : function (response) {
		var cities, ul;
		
		this._cities = response.cities;
		
		if (!this._cities) {
			return this._closeCitiesWindow();
		}
		
		this._citiesWindow.set('html', '')
			.setStyle('display', 'none') // cache la fenêtre
			.set('tween', {onComplete: $empty}) // configure l'animation
			.tween('opacity', 1, 1) // définit l'opcité à 1;
		
		ul = new Element('ul');
		$each(this._cities, function (city, id) {
			var li = new Element('li', {id: 'city-' + city.id});
			ul.adopt(li.set('text', city.ville + ' (' + city.code + ')'));
		}.bind(this));
		
		cities = ul.getElements('li');
		if (cities.length == 0) {
			return this;
		}
		
		cities.addEvent('click', this._insertCity.bind(this));
		this._citiesWindow.adopt(ul);
		
		this._openCitiesWindow();
		return this;
	},
	
	
	_getCities : function (event) {
		$clear(this.timerLoad);
		var el, value;
		
		el = $(event.target);
		this.fireEvent('beforeLoad', [el]);
		value = el.get('value').trim();
		if (value != '') {
			this.options.requestAutoCompleteCity.setOptions(
				$extend(
					this.options.requestAutoCompleteCity.options.data,
					{city: value}
				)
			);
			this.options.requestAutoCompleteCity.send();
		}
	},
	
	
	_insertCity	: function (event) {
		var el, id, datas;
		
		if (!this._cities) {
			return this;
		}
		
		event.stop();
		el = $(event.target);
		
		id = el.get('id').replace(/[^0-9]*/g, '').toInt();
		if (id > 0) {
			$each(this._cities, function (city) {
				if (id == city.id) {
					datas = {type: 'city', response : {}};
					if (city.code) {
						datas.response.code = city.code;
					}
					if (city.departement) {
						datas.response.departement = city.departement;
					}
					if (city.ville) {
						datas.response.city = city.ville;
					}
					this._checkResponse(datas);
				}
			}.bind(this));
		}
		
		this._closeCitiesWindow();
	},
	
	
	_openCitiesWindow : function () {
		var coordinates, left;
		
		if (!this._citiesWindow.getParent()) {
			coordinates = this.options.elCity.getCoordinates();
			left = coordinates.left + coordinates.width + 5;
			if (Browser.Engine.trident) {
				left += 2;
			}
			
			this._citiesWindow.setStyles({
				'left'	: left + 'px',
				'top'	: coordinates.top + 'px'
			});
			
			document.getElement('body').adopt(this._citiesWindow);
		}
		
		this._citiesWindow.setStyle('display', 'block');
		return this;
	},
	
	
	_closeCitiesWindow : function () {
		$clear(this._timerCloseBlur);
		
		if (this._closeOnProgress || this._citiesWindow.getStyle('display') == 'none') {
			return this;
		}
		
		//if (this._citiesWindow.getParent()) {
			this._closeOnProgress = true;
			this._citiesWindow.set('tween', {onComplete: function (el) {
				this._citiesWindow.setStyle('display', 'none');
				this._closeOnProgress = false;
			}.bind(this)}).tween('opacity', 1, 0);
		//}
		
		return this;
	}
	
});


/**
 * Affichage des infos de liste
 */
var InfosListe = new Class({
	
	Implements : [Options, Events],
	
	options : {
		searchName : 'seach'
	},
	
	initialize	: function (element, options) {
		if (!$(element)) {
			return;
		}
		
		this.setOptions(options);
		
		this._input = $(element);
		this._input.addEvents({
			'keyup' : this.lunchTimer.bind(this),
			'blur' : this._unFocus.bind(this)
		});
		
		this.DIVElement = new Element('div');
		if (this.options.className) {
			this.DIVElement.addClass(this.options.className);
		}
		
		this.DIVElement.setStyle('position', 'absolute');
		this.requestItems = new Request.JSON({
			url : this.options.url,
			data : {searchName: this.options.searchName},
			method : 'post',
			onSuccess : this.update.bind(this)
		});
	},
	
	
	lunchTimer : function (event) {
		$clear(this.timerLoad);
		if (this.requestItems) {
			this.requestItems.cancel();
		}
		this.timerLoad = this._loadItems.delay(300, this, [event]);
	},
	
	
	_unFocus : function (event) {
		$clear(this._timerCloseBlur);
		this._timerCloseBlur = this.closeWindow.delay(100, this);
	},
	
	
	_loadItems : function (event) {
		$clear(this.timerLoad);
		var el = $(event.target);
		this.fireEvent('beforeLoad', [el]);
		var value = el.get('value').trim();
		if (value != '') {
			this.requestItems.setOptions(
				$extend(this.requestItems.options.data, {searchValue: value})
			);
			this.requestItems.send();
		}
	},
	
	
	update	: function (items) {
		this._items = items;
		
		if (!this._items) {
			this.closeWindow();
			return;
		}
		
		this.DIVElement.empty().setStyle('display', 'block')
			.set('tween', {onComplete: $empty})
			.tween('opacity', 1, 1);
		
		var ul = new Element('ul');
		$each(this._items, function (item, id) {
			var li = new Element('li');
			li.set('text', item)
				.addEvent('click', this.insertValue.bind(this));
			ul.adopt(li);
			i++;
		}.bind(this));
		
		if (!this.DIVElement.getParent()) {
			var coordinates = this._input.getCoordinates();
			var left = coordinates.left+coordinates.width+5;
			if (Browser.Engine.trident) {
				left += 2;
			}
			
			this.DIVElement.setStyles({
				'left'	: left+'px',
				'top'	: coordinates.top+'px'
			})
			document.getElement('body').adopt(this.DIVElement);
		}
		this.DIVElement.adopt(ul);
	},
	
	insertValue	: function (event) {
		event.stop();
		var el = $(event.target);
		this._input.set('value', el.get('text'));
		event.target = this._input;
		this._input.fireEvent('change', [event]);
		this.closeWindow();
	},
		
	closeWindow	: function () {
		$clear(this._timerCloseBlur);
		if (this.DIVElement.getParent()) {
			this.DIVElement.set('tween', {onComplete: function () {
				if (this.setStyle) {
					this.setStyle('display', 'none');
				}
			}}).tween('opacity', 1, 0);
			//this.DIVElement.dispose();
		}
	}
});



var formMessagerie = new Class({
	
	initialize : function(form) {
		this._form = $(form);
		
		this._bound = {
			'confirmUpdateDatas': this._confirmUpdateDatas.bind(this),
			'beforeSubmit'		: this._checkSubmit.bind(this)
		};
		
		this._allInputs = this._form.getElements('input')
			.extend(this._form.getElements('select'));
		
		if (this._allInputs.length) {
			this._allInputs.addEvent('change', this._bound.confirmUpdateDatas);
		}
		
		
		if ($('model')) {
			$('model').addEvent('change', this._changeModel.bind(this));
		}
		
		this._initSelectionRecipients();
	},
	
	
	/**
	 * Supprime le message d'alerte en quittant la page
	 * @return void
	 */
	_checkSubmit : function(event) {
		window.onbeforeunload = function () {};
	},
	
	
	/**
	 * Active le message d'alerte en quittant la page
	 * @return void
	 */
	_confirmUpdateDatas : function() {
		this._allInputs.removeEvent('change', this._bound.confirmUpdateDatas);
		
		window.onbeforeunload = function (e) {
			return 'Attention, le message ne sera pas envoyé.';
		};
		this._form.addEvent('submit', this._bound.beforeSubmit);
	},
	
	
	/**
	 * Permet l'insertion de modèle prédéfini
	 * @return void
	 */
	_changeModel : function(event) {
		var value, el, instanceTiny;
		
		instanceTiny = tinyMCE.getInstanceById('message');
		
		if (event.target.get('value') == 0) {
			if (!window.confirm('Le contenu de votre message sera entièrement effacé.\nVoulez-vous continuer ?')) {
				return;
			}
			if (instanceTiny) {
				instanceTiny.getBody().innerHTML = '';
			} else {
				$('message').set('value', '');
			}
			return;
		}
		
		if ($('message')) {
			
			if (instanceTiny) {
				value = instanceTiny.getBody().innerHTML;
			} else {
				value = $('message').get('value');
			}
			
			if (value != '') {
				if (!window.confirm('Le contenu de votre message sera entièrement effacé.\nVoulez-vous continuer ?')) {
					return;
				}
			}
			
			el = $('model' + event.target.get('value'));
			if (el) {
				if (instanceTiny) {
					instanceTiny.getBody().innerHTML = el.get('value');
				} else {
					$('message').set('value', el.get('value'));
				}
			}
		}
	},
	
	/**
	 * Partie sélection de destinataires
	 */
	
	_initSelectionRecipients : function() {
		if (!$('view-recipients') || !$('body')) {
			return;
		}
		
		this._bound.viewRecipients = this._viewRecipientsEvent.bind(this);
		this._bound.closePopup = this._hiddeRecipientsEvent.bind(this);
		this._bound.popupRefreshPosition = this._popupRefreshPosition.bind(this);
		
		this._requestLoadRecipient = new Request.JSON({
			url	: '/actions/messagerie/load-recipients.php',
			onRequest : this._beforeLoadRecipients.bind(this),
			onSuccess : this._afterLoadRecipients.bind(this)
		});
		
		$('view-recipients').addEvent('click', this._bound.viewRecipients);
		
		this._height = 400;
		this._popupRecipients = null;
		//this._viewRecipientsEvent();
		//this._loadRecipients();
	},
	
	
	/**
	 * Affichage de la popup des destinataires
	 * @return void
	 */
	_viewRecipientsEvent : function (event) {
		if (event && event.stop) {
			event.stop();
		}
		
		if (!this._popupRecipients) {
			this._popupRecipients = new Element('div', {id: 'popup-recipients'});
			this._popupRecipients.inject($('body'), 'top');
			this._drawPopup();
			this._loadRecipients();
		}
				
		this._popupRecipients.setStyle('display', 'block');
		this._popupRefreshPosition();
		
		document.addEvent('scroll', this._bound.popupRefreshPosition);
		this._popupRecipients.set('tween', {duration: 250, onComplete: $empty}).tween('opacity', 1);
	},
	
	
	/**
	 * Cache la popup de destinataires
	 * @return void
	 */
	_hiddeRecipientsEvent : function(event) {
		if (event && event.stop) {
			event.stop();
		}
		
		document.removeEvent('scroll', this._bound.popupRefreshPosition);
		this._popupRecipients.set('tween', {onComplete: function (el) {
			el.setStyle('display', 'none');
		}}).tween('opacity', 0);
	},
	
	
	/**
	 * Génère le contenu générique de la popup
	 * @return void
	 */
	_drawPopup : function() {
		var closeButton;
		
		this._popupRecipients.set('html',
			'<div id="bar-popup" class="bar-popup">' +
			'	<h2>Sélection des destinataires du message</h2>' +
			'	<a id="close-popup" href="#" class="close-popup-button">Fermer</a>' +
			'</div>' +
			'<div id="recipients"></div>'
		);
		
		$('close-popup').addEvent('click', this._bound.closePopup);
	},
	
	
	/**
	 * Rafraichi la position de la popup
	 * @return void
	 */
	_popupRefreshPosition : function() {
		var scrollState, heightWindow, heightPopup,
			topPopup, leftPopup;
		
		if (!this._popupRecipients) {
			document.removeEvent('scroll', this._bound.popupRefreshPosition);
		}
		
		scrollState = document.getScroll();
		if (!scrollState) {
			return;
		}
		
		topPopup = 30;
		leftPopup = 30;
		this._popupRecipients.morph({
			left: (scrollState.x + leftPopup)+ 'px',
			top: (scrollState.y + topPopup)+ 'px'
		});
		
		heightPopup = this._popupRecipients.getCoordinates().height + topPopup;
		heightWindow = window.getHeight();
		
		if (this._height < heightWindow) {
			this._popupRecipients.setStyle('height', this._height + 'px');
		} else if (heightPopup > heightWindow) {
			this._popupRecipients.setStyle('height', (heightWindow - topPopup - 30) + 'px');
		}
		
		heightPopup = this._popupRecipients.getStyle('height').toInt();
		
		if ($('recipients')) {
			$('recipients').setStyle('height',
				heightPopup -
				
				$('bar-popup').getCoordinates().height
			);
		}
	},
	
	
	/**
	 * Lancement de la requète de récupération de destinataire
	 * @return void
	 */
	_loadRecipients : function() {
		if (!this._requestLoadRecipient) {
			return;
		}
		
		this._requestLoadRecipient.cancel();
		
		this._requestLoadRecipient.send();
	},
	
	
	/**
	 * Affiche l'animation de chargement
	 * @return void
	 */
	_beforeLoadRecipients : function() {
		var animation, divAnimation;
		
		divAnimation = new Element('div', {id: 'popup-animation'});
		divAnimation.addClass('animation')
			.inject(this._popupRecipients, 'top');
	},
	
	
	/**
	 * Traite les informations reçues
	 * @return void
	 */
	_afterLoadRecipients : function(response) {
		var delegues, bureau, allCheckbox, toutAucun,
			adherentsGroupe, secreataireNational, conseillerTechnique,
			otherDiv, otherDivBox, recipientsContainer;
		
		if ($('popup-animation')) {
			$('popup-animation').dispose();
		}
		
		recipientsContainer = $('recipients');
		if (!response || !recipientsContainer) {
			return;
		}
		recipientsContainer.empty();
		//console.log(response);
		
		var drawCheckbox = function(type, users, container) {
			if (!users) {
				return;
			}
			container.adopt(new Element('span').addClass('clear'));
			$each(users, function(user) {
				var div = new Element('div');
				div.set('html', '<input id="'+type+user.id+'" type="checkbox" value="'+user.id+'"' +
						($('hidden-'+type+'-'+user.id)?'checked="checked"':'') + ' />' +
						'<label for="'+type+user.id+'">'+user.nom + ' ' + user.prenom+'</label>');
				container.adopt(div);
			});
			container.addClass('recipients').adopt(new Element('span').addClass('clear'));
		};
		
		toutAucun = '<span class="tout-aucun">[' +
				'<a href="#" class="tout">Tout</a> / ' +
				'<a href="#" class="aucun">Aucun</a>' +
				']</span>';
		
		if (response.secretaireNational) {
			secretaireNational = new Element('div', {id: 'secreataireNational'}).set('html', '<div class="head"><h2 id="secretaire-national">Secrétaires national</h2> ' + toutAucun + '</div>');
			drawCheckbox('secretaireNational', response.secretaireNational, secretaireNational);
			secretaireNational.inject(recipientsContainer);
		}
		
		if (response.secretaireGenerale) {
			secretaireGenerale = new Element('div', {id: 'secretaireGenerale'}).set('html', '<div class="head"><h2 id="secretaire-generale">Secrétaires général</h2> ' + toutAucun + '</div>');
			drawCheckbox('secretaireGenerale', response.secretaireGenerale, secretaireGenerale);
			secretaireGenerale.inject(recipientsContainer);
		}
		
		if (response.bureauRestreint) {
			bureauRestreint = new Element('div', {id: 'bureauRestreint'}).set('html', '<div class="head"><h2 id="bureau-restreint">Bureau restreint</h2> ' + toutAucun + '</div>');
			drawCheckbox('bureauRestreint', response.bureauRestreint, bureauRestreint);
			bureauRestreint.inject(recipientsContainer);
		}
		
		if (response.adherentsGroupe) {
			adherentsGroupe = new Element('div', {id: 'adherentsGroupe'}).set('html', '<div class="head"><h2 id="adherent-mon-groupe">Adhérent de mon groupe</h2> ' + toutAucun + '</div>');
			drawCheckbox('adherentsGroupe', response.adherentsGroupe, adherentsGroupe);
			adherentsGroupe.inject(recipientsContainer);
		}
		
		if (response.adherentsDelegation) {
			adherentsDelegation = new Element('div', {id: 'adherentsDelegation'}).set('html', '<div class="head"><h2 id="adherent-delegation">Adhérent de ma délégation</h2> ' + toutAucun + '</div>');
			drawCheckbox('adherentsDelegation', response.adherentsDelegation, adherentsDelegation);
			adherentsDelegation.inject(recipientsContainer);
		}
		
		if (response.delegues) {
			delegues = new Element('div', {id: 'delegues'}).set('html', '<div class="head"><h2 id="delegues-groupe">Délégués de groupe</h2> ' + toutAucun + '</div>');
			drawCheckbox('delegue', response.delegues, delegues);
			delegues.inject(recipientsContainer);
		}
		
		if (response.deleguesFonctionnel) {
			deleguesFonctionnel = new Element('div', {id: 'deleguesFonctionnel'}).set('html', '<div class="head"><h2 id="delegues-fonctionnel">Délégués fonctionnel</h2> ' + toutAucun + '</div>');
			drawCheckbox('deleguesFonctionnel', response.deleguesFonctionnel, deleguesFonctionnel);
			deleguesFonctionnel.inject(recipientsContainer);
		}
		
		if (response.bureau) {
			bureau = new Element('div', {id: 'bureaux'}).set('html', '<div class="head"><h2 id="membre-bureau">Membre du bureau</h2> ' + toutAucun + '</div>');
			drawCheckbox('bureau', response.bureau, bureau);
			bureau.inject(recipientsContainer);
		}
		
		if (response.bureauNational) {
			bureauNational = new Element('div', {id: 'bureauNational'}).set('html', '<div class="head"><h2 id="membre-bureau-national">Membre du bureau national</h2> ' + toutAucun + '</div>');
			drawCheckbox('bureauNational', response.bureauNational, bureauNational);
			bureauNational.inject(recipientsContainer);
		}
		
		if (response.conseillerTechnique) {
			conseillerTechnique = new Element('div', {id: 'conseillerTechnique'}).set('html', '<div class="head"><h2 id="conseillers-techniques">Conseillers techniques</h2> ' + toutAucun + '</div>');
			drawCheckbox('conseillerTechnique', response.conseillerTechnique, conseillerTechnique);
			conseillerTechnique.inject(recipientsContainer);
		}
		
		if (response.membreCap) {
			membreCap = new Element('div', {id: 'membreCap'}).set('html', '<div class="head"><h2 id="membre-cap">Membres de la CAP</h2> ' + toutAucun + '</div>');
			drawCheckbox('membreCap', response.membreCap, membreCap);
			membreCap.inject(recipientsContainer);
		}
		
		if (response.listeGroupes) {
			listeGroupes = new Element('div', {id: 'listeGroupes'}).set('html', '<div class="head"><h2 id="liste-groupes">Adhérents de groupe</h2> ' + toutAucun + '</div>');
			listeGroupes.adopt(new Element('span').addClass('clear'));
			$each(response.listeGroupes, function(groupe) {
				var div = new Element('div');
				div.set('html', '<input id="listeGroupes'+groupe.id+'" type="checkbox" value="'+groupe.id+'"' +
						($('hidden-listeGroupes-'+groupe.id)?'checked="checked"':'') + ' />' +
						'<label for="listeGroupes'+groupe.id+'">'+groupe.nom+'</label>');
				listeGroupes.adopt(div);
			});
			listeGroupes.addClass('recipients').adopt(new Element('span').addClass('clear'));
			listeGroupes.inject(recipientsContainer);
		}
		
		if (response.listeDelegations) {
			listeDelegations = new Element('div', {id: 'listeDelegations'}).set('html', '<div class="head"><h2 id="liste-delegations">Adhérents de délégation</h2> ' + toutAucun + '</div>');
			listeDelegations.adopt(new Element('span').addClass('clear'));
			$each(response.listeDelegations, function(delegation) {
				var div = new Element('div');
				div.set('html', '<input id="listeDelegations'+delegation.id+'" type="checkbox" value="'+delegation.id+'"' +
						($('hidden-listeDelegations-'+delegation.id)?'checked="checked"':'') + ' />' +
						'<label for="listeDelegations'+delegation.id+'">'+delegation.nom+'</label>');
				listeDelegations.adopt(div);
			});
			listeDelegations.addClass('recipients').adopt(new Element('span').addClass('clear'));
			listeDelegations.inject(recipientsContainer);
		}
		
		var secretariat;
		if (response.secretariat) {
			secretariat = new Element('div', {id: 'secretariat'}).set('html', '<div class="head"><h2 id="membre-secretariat">Secrétariat</h2> ' + toutAucun + '</div>');
			drawCheckbox('secretariat', response.secretariat, secretariat);
			secretariat.inject(recipientsContainer);
		}
		
		var vcorrespondantFonctionnel;
		if (response.correspondantFonctionnel) {
			correspondantFonctionnel = new Element('div', {id: 'correspondantFonctionnel'}).set('html', '<div class="head"><h2 id="membre-correspondant-fonctionnel">Correspondant fonctionnel</h2> ' + toutAucun + '</div>');
			drawCheckbox('correspondantFonctionnel', response.correspondantFonctionnel, correspondantFonctionnel);
			correspondantFonctionnel.inject(recipientsContainer);
		}
		
		var listeAdherentSn;
		if (response.listeAdherentSn) {
			listeAdherentSn = new Element('div', {id: 'listeAdherentSn'}).set('html', '<div class="head"><h2 id="sn-adherent">Secrétaire national qui suit votre région  : </h2> ' + toutAucun + '</div>');
			drawCheckbox('listeAdherentSn', response.listeAdherentSn, listeAdherentSn);
			listeAdherentSn.inject(recipientsContainer);
		}

		
		if (response.other) {
			otherDiv = new Element('div', {id: 'other'}).set('html', '<div class="head"><h2 id="autres">Autre</h2></div>');
			
			if (response.other.contains('adherent')) {
				otherDivBox = new Element('div');
				otherDivBox.set('html', '<input id="other1" type="checkbox" value="adherent"' +
					($('hidden-other-adherent')?'checked="checked"':'') + ' />' +
						'<label for="other1">Tous les adhérents</label>');
			}
			otherDiv.adopt(otherDivBox);
			
			if (response.other.contains('adherentDoitCotiser')) {
				otherDivBox = new Element('div');
				otherDivBox.set('html', '<input id="other2" type="checkbox" value="adherentDoitCotiser"' +
					($('hidden-other-adherentDoitCotiser')?'checked="checked"':'') + ' />' +
					'<label for="other2">Adhérents devant cotiser</label>');
			}
			otherDiv.adopt(otherDivBox);
			
			otherDiv.addClass('recipients').adopt(new Element('span').addClass('clear'))
				.inject(recipientsContainer);
		}
		
		// active les évènements
		toutAucun = $$('div#popup-recipients div.head a');
		if (toutAucun) {
			toutAucun.addEvent('click', this._checkAllBox.bind(this));
		}
		
		allCheckbox = $$('div#popup-recipients div.recipients input[type=checkbox]');
		if (allCheckbox) {
			allCheckbox.addEvent('click', this._checkRecipientEvent.bind(this));
		}
	},
	
	
	_checkRecipientEvent : function (event)
	{
		this._checkRecipient(event.target, false);
	},
	
	
	/**
	 * Ajoute / Supprime un contact
	 * @return void
	 */
	_checkRecipient : function (checkbox, noDisplayLabel)
	{
		var id, type, hidden, hiddenId, labelAdherent, recipients;
		
		id = checkbox.get('id');
		type = id.replace(/[0-9]*/g, '');
		id = id.replace(/[^0-9]*/g, '');
		
		hiddenId = 'hidden-'+type+'-'+id;
		hidden = $(hiddenId);
		
		labelAdherent = $('label-'+id);
		
		if (checkbox.get('checked')) {
			if (!labelAdherent && !noDisplayLabel) {
				labelAdherent = new Element('span', {id: 'label-'+id})
					.set('text', checkbox.getNext().get('text'))
					.inject($('contacts-selectifs-h3'), 'after');
				$('contacts-selectifs-h3').setStyle('display', 'block');
			}

			if (!hidden) {
				
				hidden = new Element('input', {
					id: hiddenId,
					type: 'hidden',
					name: 'recipients['+type+'][]',
					value: checkbox.get('value')
				});
				hidden.inject($('view-recipients'), 'after');
			}
		} else if (hidden) {
			hidden.dispose();
			if (labelAdherent && !$('destinataires').getElement('input[value='+id+']')) {
				labelAdherent.dispose();
			}
			if ($('contacts-selectifs-h3').getNext().hasClass('clear')) {
				$('contacts-selectifs-h3').setStyle('display', 'none');
			}
			recipients = checkbox.getParent('div.recipients');
			if (recipients && recipients.retrieve('allSelected')) {
				this._updateRecipients(recipients);
				recipients.retrieve('allSelected').dispose();
				recipients.eliminate('allSelected');
				if ($('contacts-globaux-h3').getNext().hasClass('clear')) {
					$('contacts-globaux-h3').setStyle('display', 'none');
				}
			}
		}
		
		//console.log(event.target.get('checked'));
	},
	
	
	_checkAllBox : function(event) {
		var boxs, target, checked, labelAll, idLabel;
		
		if (event && event.stop) {
			event.stop();
		}
		
		target = event.target;
		checked = target.hasClass('tout');
		
		labelAll = target.getParent('span').getPrevious();
		idLabel = 'label-'+labelAll.get('id');
		
		boxs = target.getParent('div').getParent('div').getElements('input[type=checkbox]');
		if (boxs) {
			event.noDisplayLabel = true;
			$each(boxs, function(box) {
				if (checked) {
					box.set('checked', false);
					this._checkRecipient(box, true);
				}
				box.set('checked', checked);
				this._checkRecipient(box, true);
			}.bind(this));
		}
		
		if (checked) {
			labelAll = new Element('span', {id: idLabel})
				.set('text', labelAll.get('text'))
				.inject($('contacts-globaux-h3'), 'after');
			$('contacts-globaux-h3').setStyle('display', 'block');
			target.getParent('div.recipients').store('allSelected', labelAll);
		} else if($(idLabel)) {
			$(idLabel).dispose();
			if ($('contacts-globaux-h3').getNext().hasClass('clear')) {
				$('contacts-globaux-h3').setStyle('display', 'none');
			}
		}
	},
	
	/**
	 * Si un groupe de contact a été sélectionné et qu'un de ces contacts
	 * a été décoché, on met à jour la liste des destinataires
	 */
	_updateRecipients : function (recipient) {
		var checkboxs;
		
		checkboxs = recipient.getElements('input[type=checkbox]');
		if (checkboxs) {
			checkboxs.each(function (checkbox) {
				this._checkRecipient(checkbox, false);
			}.bind(this));
		}
	}
	
	
});


var StatAges = new Class({
	
	initialize : function (form) {
		var els;
		
		this._form = $(form);
		if (!this._form) {
			return;
		}
		
		this._form.set('send', {onComplete: this._updateGraph.bind(this)})
			.addEvent('submit', this._checkForm.bind(this));
		
		this._checkDisplayPas();
		if ($('type-stat')) {
			if ($('export_csv')) {
				$('export_csv').setStyle('display', $('type-stat').get('value') == 'age'?'block':'none');
			}
			if ($('export_png')) {
				$('export_png').setStyle('display', $('type-stat').get('value') == 'age'?'block':'none');
			}
		}
	},
	
	
	_checkDisplayPas : function () {
		if ($('div-pas')) {
			$('div-pas').setStyle('display', $('type-stat').get('value') == 'age'?'inline':'none');
		}
	},
	
	
	/*
	 * Vérification du contenu du formulaire
	 * @return void
	 */
	_checkForm : function (event) {
		event.stop();
		this._checkDisplayPas();
		if (this._checkValues()) {
			$('update').set('disabled', 'disabled').addEvent('click', function (event) {event.stop();});
			this._form.send();
		}
	},
	
	
	/* Met à jour le graph suivant les fonctions
	 * @return void
	 */
	_updateGraph : function () {
		var tmp = new Date();
		var url = $('graph-stat-ages').get('src').replace(/&t=[0-9]*/g, '') + "&t=" + tmp.getTime();
		
		var img = new Asset.image(url, {
			alt : '',
			onload : this._refreshGraph.bind(this)
		});
	},
	
	
	/* Rafraichi l'image du graphe
	 * @return void
	 */
	_refreshGraph : function (newGraph) {
		var container = $('graph-stat-ages').getParent();
		var oldGraph = $('graph-stat-ages').set('id', 'graph-stat-ages-2');
		oldGraph.dispose();
		container.adopt(newGraph.set('id', 'graph-stat-ages').set('opacity', 1));
	
		$('update').removeEvents('click').set('disabled', false);
		if ($('type-stat')) {
			if ($('export_csv')) {
				$('export_csv').setStyle('display', $('type-stat').get('value') == 'age'?'block':'none');
			}
			if ($('export_png')) {
				$('export_png').setStyle('display', $('type-stat').get('value') == 'age'?'block':'none');
			}
		}
		
		/*newGraph.set('tween', {onComplete: function () {
			oldGraph.dispose();
		}}).tween('opacity', 1);*/
	},
	
	_checkValues : function () {
		if (!$('pas')) {
			return true;
		}
		
		var value = $('pas').get('value');
		if (value.replace(/[0-9]*/g, '') != '') {
			window.alert('Information du "pas" invalide.');
			return false;
		}
		
		if (value < 5) {
			window.alert('Information du "pas" invalide.');
			return false;
		}
		
		return true;
	}
	
});


/*
 * Gestion des relations Corps/Grades/Échelons
 */
var relationCorps = new Class({
	
	initialize : function (corps, grade, echelon)
	{
		this._elCorps = $(corps);
		this._elGrade = $(grade);
		this._elEchelon = $(echelon);
		
		relationCorps.corps = null;
		relationCorps.grades = null;
		this._requestPreload = null;
		
		relationCorps.relations = [];
		
		if (this._elCorps) {
			this._elCorps.addEvent('change', this.checkCorps.bind(this));
		}
		
		if (this._elGrade) {
			this._elGrade.addEvent('change', this.checkGrade.bind(this));
		}
		
		
		this._preloadDatas();
	},
	
	
	checkCorps : function (event)
	{
		if (relationCorps.corps == null && relationCorps.requestPreload.running) {
			this.checkCorps.delay(1000, this, [event]);
			return;
		}
		
		var id_corps = this._elCorps.get('value');
		
		if (this._elGrade && relationCorps.grades) {
			var currentGrade = this._elGrade.get('value');
			this._elGrade.set('html', '<option value="0">Sélectionnez votre grade</option>')
				.set('value', '0');
			
			var ids = [];
			$each(relationCorps.grades, function (grade, key) {
				if (id_corps == grade['id_corps']) {
					var option = new Element('option', {value: grade['id']});
					option.set('text', grade['name']);
					this._elGrade.adopt(option);
					ids.push(grade['id']);
				}
			}.bind(this));
			
			if (ids.contains(currentGrade)) {
				this._elGrade.set('value', currentGrade);
			} else {
				this.checkGrade();
			}
		}
	},
	
	
	checkGrade : function (event)
	{
		if (relationCorps.grades == null && relationCorps.requestPreload.running) {
			this.checkGrade.delay(1000, this, [event]);
			return;
		}
		
		var id_grade = this._elGrade.get('value');
		var values = relationCorps.relations[id_grade];
		
		if (this._elEchelon) {
			var currentEchelon = this._elEchelon.get('value');
			this._elEchelon.set('html', '<option value="0">Sélectionnez votre échelon</option>')
				.set('value', '0');
			
			if (values) {
				$each(values, function (echelon, key) {
					var option = new Element('option', {value: echelon});
					option.set('text', relationCorps.echelons[echelon]);
					this._elEchelon.adopt(option);
				}.bind(this));
				
				if (values.contains(currentEchelon.toInt())) {
					this._elEchelon.set('value', currentEchelon.toInt());
				}
			}
		}
	},
	
	
	_preloadDatas : function ()
	{
		if (relationCorps.datasLoaded || relationCorps.requestPreload) {
			this.checkCorps();
			this.checkGrade();
			return;
		}
		relationCorps.requestPreload = new Request.JSON({
			url : '/actions/profil/get-datas-corps.php',
			onComplete : this._registerDatas.bind(this)
		});
		relationCorps.requestPreload.send();
	},
	
	
	_registerDatas : function (datas)
	{
		relationCorps.corps = datas['corps'];
		relationCorps.grades = datas['grades'];
		relationCorps.echelons = datas['echelons'];
		relationCorps.relations = datas['relationsEchelonsGrades'];
		/*this._corps = datas['corps'];
		this._grades = datas['grades'];
		this._echelons = datas['echelons'];
		this._relationsEchelonsGrades = datas['relationsEchelonsGrades'];*/
		relationCorps.datasLoaded = true;
		
		this.checkCorps();
		this.checkGrade();
	}
	
});



var initUpdateStats = function () {
	if ($('s4-form')) {
		$('s4-form').getElement('div.radios').getElements('input').addEvent('click', function (event) {
			$('s4-form').getElements('div.bloc-config').setStyle('display', 'none');
			var item = $('s4-' + this.id);
			if (item) {
				item.setStyle('display', 'block');
			}
			$('s4-form').set('send', {evalResponse: true, onComplete: function () {
				var tmp=new Date();
				$('s4-img').src = $('s4-img').src + "&" + tmp.getTime();
			}}).send();
		});
		
		var updateForm = function () {
			$('s4-groupes').setStyle('display', $('groupes').checked?'block':'none');
			$('s4-delegue').setStyle('display', $('delegue').checked?'block':'none');
		};
		
		$('s4-form').addEvent('submit', function (event) {
			var checkbox;
			event = new Event(event);
			event.stop();
			
			if ($('groupes').get('checked')) {
				checkbox = $$('div#s4-groupes div.checkbox input[checked=1]');
				if (checkbox && checkbox.length > 10) {
					window.alert('Un maximum de 10 groupes peuvent être sélectionnés en même temps.\nMerci de corriger le problème.');
					return;
				}
			}
			updateForm();
			$('s4-form').set('send', {evalResponse: true, onComplete: function () {
				var tmp=new Date();
				$('s4-img').src = $('s4-img').src + "&" + tmp.getTime();
			}}).send();
		});
		updateForm();
	}
	
	
	if ($('s123-form')) {
		$('s123-form').getElement('div.radios').getElements('input').addEvent('click', function (event) {
			$('s123-form').getElements('div.bloc-config').setStyle('display', 'none');
			var item = $('s123-' + this.id);
			if (item) {
				item.setStyle('display', 'block');
			}
			$('s123-form').set('send', {evalResponse: true, onComplete: function () {
				var tmp=new Date();
				$('s1-img').src = $('s1-img').src + "&" + tmp.getTime();
				$('s2-img').src = $('s2-img').src + "&" + tmp.getTime();
				$('s3-img').src = $('s3-img').src + "&" + tmp.getTime();
			}}).send();
		});
		
		var updateForm123 = function () {
			if ($('s123-groupes123') && $('groupes123')) {
				$('s123-groupes123').setStyle('display', $('groupes123').checked?'block':'none');
			}
			if ($('s123-delegue123') && $('delegue123')) {
				$('s123-delegue123').setStyle('display', $('delegue123').checked?'block':'none');
			}
		};
		
		$('s123-form').addEvent('submit', function (event) {
			var checkbox;
			event = new Event(event);
			event.stop();
			
			if ($('groupes123').get('checked')) {
				checkbox = $$('div#s123-groupes div.checkbox input[checked=1]');
				if (checkbox && checkbox.length > 10) {
					window.alert('Un maximum de 10 groupes peuvent être sélectionnés en même temps.\nMerci de corriger le problème.');
					return;
				}
			}
			updateForm123();
			$('s123-form').set('send', {evalResponse: true, onComplete: function () {
				var tmp=new Date();
				$('s1-img').src = $('s1-img').src + "&" + tmp.getTime();
				$('s2-img').src = $('s2-img').src + "&" + tmp.getTime();
				$('s3-img').src = $('s3-img').src + "&" + tmp.getTime();
			}}).send();
		});
		updateForm123();
	}
	
	var statAge = new StatAges($('stat-ages'));
}

/*
var initVilles = function () {
	var el = $$('input.liste-villes');
	if (el.length > 0) {
		el.each(function (el) {
			var ville = new InfosListe(el, {
				url : '/actions/profil/get-datas.php',
				className: 'fenetre-select',
				searchName : 'ville'
			});
		});
	}
};
*/


var initViewAdherent = function () {
	$$('.voir-adherent').each(
		function (el) {
			el.addEvent('click', function (event) {
				event.stop();
				var id_adherent = this.href.replace(/[^0-9]*/g, '');
				window.openWindow('infos-adherent-'+id_adherent+'.html', 'voir_adherent');
			});
		}
	);
};

var initViewDocument = function () {
	$$('a.voir-document').each(
		function (el) {
			el.addEvent('click', function (event) {
				event.stop();
				var id_document = this.href.replace(/[^0-9]*/g, '');
				window.openWindow('/view-document-' + id_document + '.html?id=' + id_document, 'voir_document');
			});
		}
	);
};

var initControlCotisation = function () {
	if ($$('a.confirmer-cotisation').length) {
		$$('a.confirmer-cotisation')[0].addEvent('click', function (event) {
			var date = new Date();
			if (window.confirm('Vous n’avez pas encore adhéré en '+date.getFullYear()+', voulez-vous adhérer ?')) {
				event.stop();
				window.location.href = '/generer_cotisation.html';
			}
		});
	}
};

var initFormList = function () {
	// confirmation pour suppression
	var form = $$('form.liste').getFirst();
	if (!form) {
		return;
	}
	
	form.addEvent('submit', function (event) {
		event = new Event(event);
		if (!checkFormList()) {
			event.stop();
		}
	});
	
	if ($('action') && $('action').get('tag') == 'select') {
		//$('action').getNext().dispose();
		$('action').addEvent('change', function (event) {
			if (checkFormList()) {
				this.getParent('form').submit();
			}
		});
	}
	
	if ($('checkall')) {
		$('checkall').addEvent('change', function (event) {
			var checkList = $$('input.toselect');
			if (!checkList) {
				return;
			}
			//if (this.checked) {
				checkList.set('checked', this.checked);
			//}
		});
	}
};


var initMessagerie = function () {
	if ($('messagerie')) {
		var control = new formMessagerie($('messagerie'));
	}
};


var initConfigDateGradeEchelon = function () {
	var table = $('date-grades-echelons'), corps, grades, echelons;
	if (table) {
		corps = table.getElements('select.select-corps');
		grades = table.getElements('select.select-grade');
		echelons = table.getElements('select.select-echelon');
		var l;
		for (var i = 0; i < corps.length; i++) {
			l = new relationCorps(corps[i], grades[i], echelons[i]);
		}
	}
}



var checkFormList = function () {
	var action = $('action');
	if (action.value == 'supprimer' && !window.confirm('Voulez-vous réellement supprimer ces éléments ?')) {
		action.value = "";
		return false;
	}
	
	return true;
};


var init = function () {
	//initVilles();
	initMessagerie();
	initUpdateStats();
	initViewAdherent();
	initViewDocument();
	initControlCotisation();
	initFormList();
	initConfigDateGradeEchelon();
	
	// grrr la W3C
	var a = $$('a.target-blanc');
	if (a.length) {
		a.setProperty('target', '_blanc');
	}
	
	
	// autocomplétion des villes

	if ($('id_departement') && $('ville') && $('code_postal')) {
		var adressPro = new autoCompleteAddress({
			elCity : $('ville'),
			elCode : $('code_postal'),
			elDepartement : $('id_departement'),
			url : '/actions/other/autocomplete-address.php'
		});
	}
	
	
	// relation affectation / entité
	if ($('id_affectation') && $('id_structure_affectation') && !$('form-inscription')) {
		var relationEntiteAffectation = [];
		var request = new Request.JSON({url: '/actions/profil/get-datas.php?i=relationsAffectation', onComplete: function (datas) {
			relationEntiteAffectation = datas;
			refreshRelationsAffectation();
		}});
		
		var refreshRelationsAffectation = function () {
			var sa = $('id_structure_affectation');
			var value = sa.get('value');
			
			if (sa) {
				sa.set('html', '<option value="0">Choisissez votre structure d\'affectation</option>');
				var values = relationEntiteAffectation['relations'][$('id_affectation').get('value')];
				if (values) {
					values.each(
						function (id) {
							var option = new Element('option', {value: id});
							option.set('text', relationEntiteAffectation['entites'][id]);
							sa.adopt(option);
						}.bind(this)
					);
					
					if (values.contains(value)) {
						$('id_structure_affectation').set('value', value);
					}
				}
			}
		};
		$('id_affectation').addEvent('change', refreshRelationsAffectation);
		request.send();
	}
	
	if ($('generer-cotisation')) {
		var rrr = new relationCorps($('id_corp'), $('id_grade'), $('echelon'));
	}
}
window.addEvent('domready', init);





var openWindow = function (adresse, nom) {
	var nouvelle_fenetre = window.open(adresse, nom, 'scrollbars=yes,menubar=no,top=0,left=0,toolbar=no,width=800,height=280,resizable=yes');
	nouvelle_fenetre.focus();
}


