var Formulaire = Class.create({
	initialize: function(nom){
		this.liste = new Array();
		this.form = $(nom);
		this.ajax = new Object();
		this.tab  = -1;
		this.traduction = {estNonNul    : 'ne doit pas être vide.',
						   confirmation : 'doit être égal à la confirmation.',
						   estUnEmail   : 'n\'est pas une adresse email valide.',
						   estUneDate   : 'n\'est pas une date valide.',
						   estUnNumTel  : 'n\'est pas un numéro de téléphone valide.',
						   estUnNombre  : 'n\'est pas un nombre',
						   estNonMinuit : 'n\'est pas une heure valide'};
		$$$F = this;
	},
	
	add: function(el){
		$$$F.liste.push(el);
	},
	
	removeFormItem: function(id){
		var retour = new Array();
		for(var i=0;i<$$$F.liste.length;i++){
			if($$$F.liste[i].id != id){
				retour.push($$$F.liste[i]);
			}
		}
		$$$F.liste = retour;
	},
	
	navigateTo: function(index){
		if(index != $$$F.tab){
			$('onglet_' + index).setStyle({display: 'block'});
			$('tab_' + index).className = 'on';
			if($$$F.tab >= 0){
				$('onglet_' + $$$F.tab).setStyle({display: 'none'});
				$('tab_' + $$$F.tab).className = 'off';
			}
			$$$F.tab = index;
		}
	},
	
	toggle: function(element,etat){
		if(etat){
			$(element).className = 'visible';
		} else {
			$(element).className = 'cache';
			$(element).value     = '';
		}
	},
	
	toggleLigne: function(arr,etat){
		for(var i=0;i<arr.length;i++){
			var element = ($(arr[i] + '_0') == undefined) ? $(arr[i]) : $(arr[i] + '_0');
			
			if(etat){
				element.parentNode.parentNode.className = 'visible';
			} else {
				element.parentNode.parentNode.className = 'cache';
				if($(arr[i] + '_0') == undefined) $(arr[i]).value     = '';
			}
		}
	},
	
	toggleLink: function(id){
		
		if(id=="f_pub_link_type0"){
			$('f_pub_link_libre').className = 'visible textLong';
			if($('f_pub_link_evenement') != undefined){
				$('f_pub_link_evenement').className = 'cache';
				$('f_pub_link_evenement').selectedIndex = 0;
			} else {
				$('f_pub_link_page').className = 'cache';
				$('f_pub_link_page').selectedIndex = 0;
			}
			
		} else {
			$('f_pub_link_libre').className = 'cache textLong';
			if($('f_pub_link_evenement') != undefined){
				$('f_pub_link_evenement').className = 'visible';
			} else {
				$('f_pub_link_page').className = 'visible';
			}
			$('f_pub_link_libre').value = '';
		}
	},
	
	
	checkToRadio: function(el,arr){
		for(var i=0;i<arr.length;i++){
			
			$(arr[i] + '_0').checked = false;
		}
	},
	
	insertFusion: function(){
		if ($('champ_fusion').value != ''){
			tinyMCE.activeEditor.execCommand('mceInsertContent', false, '[' + $('champ_fusion').value + '] ');
		}
	},
	
	wash: function(el){
		var retour = $(el).value;
		retour = retour.gsub(/[&"',;: ]/,'_');
		retour = retour.gsub(/[àâ]/,'a');
		retour = retour.gsub(/[ç]/,'c');
		retour = retour.gsub(/[éèê]/,'e');
		retour = retour.gsub(/[î]/,'i');
		retour = retour.gsub(/[ô]/,'o');
		retour = retour.gsub(/[ùû]/,'u');
		return(retour.toLowerCase());
	},
	
	validateAll: function(){
		var listeValidator;
		for(var i=0; i<$$$F.liste.length; i++){
			
			if($$$F.validate(i) === false) return false;
		}
		return true;
	},
	
	validate: function(ec){
		var retour;
		var validators = $$$F.liste[ec].validators != '' ? $$$F.liste[ec].validators.split(',') : [];
		for(var i=0; i<validators.length; i++){
			retour = eval('$$$F.' + validators[i] + '($$$F.liste[' + ec + ']);');
			if(retour === false) {
				$$$F.warning(ec,validators[i]);
				return false;
			}
		}
		return(true);
	},
	
	supEvenement: function(id){
		if(id == '') return false;
		if(parseInt(id,10) != id) return false;
		if(confirm("Etes-vous sûr de vouloir supprimer cet évènement ?")){
			att = new Attente();
			att.show();
			var url = 'module/Formulaire/supEvenement.php';
			var pars = 'id=' + id;
			$$$F.ajax = new Ajax.Request(url,{
									method: 'post',
									parameters: pars,
									onComplete: function(r){
										var rep = r.responseText;
										if(rep.substring(0,1) != '@'){
											alert(rep);
										}
										window.location.reload();
									}
			});
		}
	},
	
	supCourse: function(id){
		if(id == '') return false;
		if(parseInt(id,10) != id) return false;
		if(confirm("Etes-vous sûr de vouloir supprimer cette course ?")){
			att = new Attente();
			att.show();
			var url = 'module/Formulaire/supCourse.php';
			var pars = 'id=' + id;
			$$$F.ajax = new Ajax.Request(url,{
									method: 'post',
									parameters: pars,
									onComplete: function(r){
										var rep = r.responseText;
										if(rep.substring(0,1) != '@'){
											alert(rep);
										}
										window.location.reload();
									}
			});
		}
	},
	
	supNews: function(id){
		if(id == '') return false;
		if(parseInt(id,10) != id) return false;
		if(confirm("Etes-vous sûr de vouloir supprimer cette news ?")){
			att = new Attente();
			att.show();
			var url = 'module/Formulaire/supNews.php';
			var pars = 'id=' + id;
			$$$F.ajax = new Ajax.Request(url,{
									method: 'post',
									parameters: pars,
									onComplete: function(r){
										var rep = r.responseText;
										if(rep.substring(0,1) != '@'){
											alert(rep);
										}
										window.location.reload();
									}
			});
		}
	},
	
	supprimeMessage: function(id){
		if(id == '') return false;
		if(parseInt(id,10) != id) return false;
		if(confirm("Etes-vous sûr de vouloir supprimer ce message ?")){
			att = new Attente();
			att.show();
			var url = 'module/Formulaire/supprimeMessage.php';
			var pars = 'id=' + id;
			$$$F.ajax = new Ajax.Request(url,{
									method: 'post',
									parameters: pars,
									onComplete: function(r){
										var rep = r.responseText;
										if(rep.substring(0,1) != '@'){
											alert(rep);
										}
										window.location.reload();
									}
			});
		}
	},
	
	presave:function(){
		this.initWarning();
		if($$$F.validateAll()){
			var pars = "";
			var arr = new Array();
			for(var i=0; i<$$$F.liste.length;i++){
				arr[i] = $$$F.liste[i].id + '=' + $$$F.valueOf($$$F.liste[i].id,$$$F.liste[i].type);
			}
			pars = arr.join('&');
			_PUM_.open({"type":"Mailing","width":"700px","height":"700px","param":pars});
			
		}
	},
	
	save: function(){
		this.initWarning();
		if($$$F.validateAll()){
			att = new Attente();
			att.show();
			var pars = "";
			var arr = new Array();
			for(var i=0; i<$$$F.liste.length;i++){
				arr[i] = $$$F.liste[i].id + '=' + $$$F.valueOf($$$F.liste[i].id,$$$F.liste[i].type);
			}
			pars = arr.join('&');
			var url = 'module/Formulaire/save' + $$$F.liste[0].data + '.php';
			
			//if($$$F.liste[0].data == 'Inscription' || $$$F.liste[0].data == 'Epreuve'){
			if($('P_container') != undefined) $('P_container').setStyle({visibility: 'hidden'});
			//}
			
			$$$F.ajax = new Ajax.Request(url,{
				method: 'post',
				parameters: pars,
				onComplete: function(r){
								var rep = r.responseText;
								if(rep.substr(0,1) == '#'){
									alert(rep.substr(1));
									if($('P_container') != undefined) $('P_container').setStyle({visibility: 'visible'});
									att.hide();
								} else {
									switch($$$F.liste[0].data){
									case 'Course':
										window.location = 'index.php?load=liste_course_admin';
										break;
									case 'Discussion':
										window.location = 'index.php?load=forum_message&key=' + rep.substr(1);
										break;
									case 'Epreuve':
										window.location.reload();
										break;
									case 'News':
										window.location = 'index.php?load=liste_news';
										break;
									case 'Inscription':
										alert(rep.substr(1));
										window.location.reload();
										break;
									case 'Message':
										window.location.reload();
										break;	
									case 'Mailing':
										if(rep != '') alert(rep);
										window.location.reload();
										break;	
									case 'Messagerie':
										window.location.reload();
										break;
									case 'Publicite':
										window.location.reload();
										break;
									case 'PubliciteAdmin':
										window.location = 'index.php?load=publicite_admin';
										break;
									case 'Page':
										window.location.reload();
										break;
									case 'Association':
										window.location = 'index.php?load=structure';
										break;
									case 'Societe':
										window.location = 'index.php?load=structure';
										break;
									case 'Recherche':
										window.location = 'index.php?load=liste_evenement';
										break;
									case 'Profil':
										window.location = 'index.php?load=accueil';
										break;
									case 'Parametrage':
										window.location.reload();
										break;
									case 'Utilisateur':
										alert(rep.substr(1));
										window.location = 'index.php';
										break;
									case 'Contact':
										alert("Votre message a été envoyé avec succès.")
										window.location.reload();
										break;
									case 'Bug':
										window.location = 'index.php?load=liste_bug_report';
										break;
									}
									
								}
							}
			});
		}
	},
	
	showPub: function(file,pubType){
		$('f_img_id_img_screen').setStyle({width  : importateur.dimension[pubType][0]+'px',
										   height : importateur.dimension[pubType][1]+'px'});
		$('f_img_id_img_screen').src = 'module/Importateur/uploaded/' + file;
	},
	
	creerCourse: function(){
		var nom = $F('nomCourse');
		if(nom == null) return false;
		if(nom != ''){
			var url = 'module/Formulaire/creerCourse.php';
			var pars = 'nom=' + nom;
			$$$F.ajax = new Ajax.Request(url,{
				method: 'post',
				parameters: pars,
				onComplete: function(r){
								var rep = r.responseText;
								if(rep.substr(0,1) == '@'){
									window.location="index.php?load=course_admin&key=" + rep.substr(1);
								} else {
									alert(rep.substr(1));
								}
				}
			});
		} else {
			alert('Veuillez saisir un nom pour cet évènement');
		}
	},
	
	changeNumTel: function(element){
		$(element).value = $(element).value.replace(/[^0-9 .-]/, '');

	},
	
	changeDateFin: function(){
		if($('f_pub_date_debut') != undefined){
			var beginDate = $('f_pub_date_debut').value;
			var newDay    = String(parseInt(beginDate.substr(0,2),10) + (7 * parseInt($F('f_pub_nb_semaine'),10)));
			var newDate    = new Date(beginDate.substr(6,4),String(parseInt(beginDate.substr(3,2),10) -1),newDay);
			var day        = (newDate.getDate() < 10) ? '0' + String(newDate.getDate()) : String(newDate.getDate());
			var month      = (newDate.getMonth() + 1 < 10) ? '0' + String(newDate.getMonth() + 1) : String(newDate.getMonth() + 1);
			
			var endDate    = day + '/' + month + '/' + String(newDate.getFullYear());
			if($('end_date') == undefined){
				var contenu = ' jusqu\'au <span id="end_date"></span>';
				$('f_pub_date_debut').insert({after: contenu});
			}
			if(beginDate != ''){
				$('end_date').innerHTML = endDate;
			} else {
				$('end_date').innerHTML = '';
			}
		}
	},
	
	autoComplete: function(data){
		if(data!=''){
			var action = true;
			var tmp_data = data.split('$');
			var couple;
			for(var i=0; i<tmp_data.length; i++){
				couple = tmp_data[i].split('#');
				if(couple[2] != 'regle'){
					if($(couple[0]) != undefined || ($(couple[0]) == undefined && couple[2] == 'radio')){
						this.put(couple[0], couple[2], couple[1]);
					}
				} else {
					if(couple[0] == 'f_indicateur'){
						if(couple[1] == '1'){
							action = true;
						} else {
							action = false;
						}
					}
				}
			}
			
			if(action){
				// Si visiteur on masque les champs de création de compte
				for(var j=0; j<$$$F.liste.length; j++){
					
					if($$$F.liste[j].id == 'f_uti_password'){
						$$$F.liste[j].validators = 'estNonNul';
					}
				}
				if($('f_uti_email') != undefined) $('f_uti_email').parentNode.parentNode.setStyle({display:'none'});
				if($('f_uti_password_confirmation') != undefined) $('f_uti_password_confirmation').parentNode.parentNode.setStyle({display:'none'});
				if($('f_uti_ville') != undefined) $('f_uti_ville').parentNode.parentNode.setStyle({display:'none'});
			}
		}
	},
	
	supprimePubAdmin: function(id){
		if(confirm('Etes-vous certain de vouloir supprimer cette publicité ?')){
			var url = 'module/Formulaire/supprimePubAdmin.php';
			var pars = 'id=' + id;
			$$$F.ajax = new Ajax.Request(url,{
				method: 'post',
				parameters: pars,
				onComplete: function(r){
								var rep = r.responseText;
								if(rep.substr(0,1) == '@'){
									window.location='index.php?load=publicite_admin';
								} else {
									alert(rep.substr(1));
								}
				}
			});
		}
	},
	
	supprimePub: function(id){
		if(confirm('Etes-vous certain de vouloir supprimer cette publicité ?')){
			var url = 'module/Formulaire/supprimePub.php';
			var pars = 'id=' + id;
			$$$F.ajax = new Ajax.Request(url,{
				method: 'post',
				parameters: pars,
				onComplete: function(r){
								var rep = r.responseText;
								if(rep.substr(0,1) == '@'){
									window.location='index.php?load=publicite';
								} else {
									alert(rep.substr(1));
								}
				}
			});
		}
	},
	
	searchByCode: function(){
		att = new Attente();
		att.show();
		$('P_container').setStyle({visibility : 'hidden'});
		var url = 'module/Formulaire/searchByCode.php';
		
		var pars = 'code=' + $('f_uti_code_coureur').value + '&epr_id=' + $F('f_epr_id');
		$$$F.ajax = new Ajax.Request(url,{
			method: 'post',
			parameters: pars,
			onComplete: function(r){
							var data = r.responseText;
							if(data!=''){
								$('P_container').setStyle({visibility : 'visible'});
								var tmp_data = data.split('$');
								var couple;
								for(var i=0; i<tmp_data.length; i++){
									couple = tmp_data[i].split('#');
									//alert(couple[0] + ', ' + couple[2] + ', ' + couple[1]);
									$$$F.put(couple[0], couple[2], couple[1]);
								}
							}
							
			}
		});
	},
	
	estNonNul: function(item){
		var retour = $$$F.valueOf(item.id,item.type);
		
		if(retour.constructor.toString().indexOf("Array") == -1){
			return (retour != "");
		} else {
			return(retour.length != 0);
		}
	},
	
	estUnEmail: function(item){
		var retour = $$$F.valueOf(item.id,item.type);
		if(retour == '') return true;
		var reg = /^[a-z0-9._-]+@[a-z0-9.-]{2,}[.][a-z]{2,4}$/;
		return (reg.exec(retour)!=null);
	},
	
	estUnNumTel: function(item){
		var retour = $$$F.valueOf(item.id,item.type);
		if(retour == '') return true;
		retour = retour.replace(/[^0-9]/g, '');
		if(retour.length == 10){
			$(item.id).value = retour.substr(0,2) + ' ' + retour.substr(2,2) + ' ' +
			retour.substr(4,2) + ' ' + retour.substr(6,2) + ' ' + retour.substr(8,2);
			return true
		}
		return false;
	},
	
	estUneDate: function(item){
		var retour = $$$F.valueOf(item.id,item.type);
		if(retour == '') return true;
		var reg = /^[0-9]{2}\/[0-9]{2}\/[1-2][0-9]{3}$/;
		if(!(reg.exec(retour)!=null)) return false;
		/*var arDate = retour.split('/');
		var iDay = parseInt(arDate[0]);
		var iMonth = parseInt(arDate[1]);
		var iYear = parseInt(arDate[2]);
		if(iDay == 0) return false;
		if(iDay > 31) return false;
		if(iMonth == 0) return false;
		if(iMonth > 12) return false;*/
		return true;
	},
	
	estUnNombre: function(item){
		var retour = $$$F.valueOf(item.id,item.type);
		if(retour == '') return true;
		return(retour == parseInt(retour));
	},
	
	estNonMinuit: function(item){
		var retour = $$$F.valueOf(item.id,item.type);
		return(retour != '00:00:00');
	},
	
	confirmation: function(item){
		var el1 = $$$F.valueOf(item.id,item.type);
		var el2 = $$$F.valueOf(item.id+'_confirmation',item.type);
		return(el1 == el2);
	},
	
	valueOf: function(id,type){
		var tmp;
		switch(type){
			case 'text':
				return $$$F.encode($F(id));
				break;
			case 'textarea':
				return $$$F.encode($F(id));
				break;
			case 'hidden':
				return $F(id);
				break;	
			case 'select':
				return $F(id);
				break;
			case 'checkbox':
				tmp = $$('input').select(function(e){return(e.id.substr(0,e.id.lastIndexOf('_')) == id && e.checked == 1);});
				if(tmp.length > 0){
					return tmp.map(function(input){return(input.value);});
				} else {
					return '';
				}
				break;
			case 'radio':
				tmp = $$('input[type=radio]').detect(function(e){return(e.checked == 1 && e.name==id);});
				if(tmp != undefined){
					return tmp.value;
				} else {
					return '';
				}
				break;
			case 'editeur':
				return ed.encode(id);
				break;
		}
	},
	
	put: function(id,type,value){
		var i;
		var tmp;
		var indice;
		switch(type){
			case 'text':
				$(id).value = value;
				break;
			case 'textarea':
				//value = value.gsub(/</,'&lt;');
				//value = value.gsub(/>/,'&gt;');
				$(id).innerHTML = value;
				break;
			case 'hidden':
				$(id).value = value;
				break;	
			case 'select':
				indice = 0;
				for(i=0;i<$(id).length;i++){		
					if($(id)[i].value == value) indice = i;;
				}
				$(id).selectedIndex=indice;
				break;
			case 'checkbox':
				tmp = value.split(',');
				var cb; 
				for(i=0;i<tmp.length;i++){
					cb = $$('input[type=checkbox]').detect(function(e){return(e.id.substr(0,e.id.length - 1) == id && e.value==tmp[i]);});
					cb.checked = 1;
				}
				break;
			case 'radio':
				tmp = $$('input[type=radio]').detect(function(e){return(e.name == id && e.value==value);});
				if(tmp != undefined){
					tmp.checked = 1;
				} else {
					$$('input[type=radio]').map(function(e){if(e.name == id) e.checked = 0;})
				}
				break;
		}
	},
	
	update: function(data){
		for(var i=0; i<$$$F.liste.length;i++){
			if(data[$$$F.liste[i].id.substr(2)] != undefined) {
				$$$F.put($$$F.liste[i].id, $$$F.liste[i].type, data[$$$F.liste[i].id.substr(2)]);
				//if($$$F.liste[0].data == "Publicite" && $$$F.liste[i].id == 'f_img_id') selecteur.displayImage(data['img_nom']);
			}
		}
	},
	
	updateHM: function(element){
		var heure = $(element+'_heure').value;
		var minute = $(element+'_minute').value;
		$(element).value = heure+':'+minute;
	},
	
	refresh: function(image){
		var src = $(image).src;
		var currentDate = new Date();
		if(src.indexOf('?') != -1){
			src = src.substr(0,src.indexOf('?'));
		}
		$(image).src = src + '?t=' + currentDate.getTime();
	},
	
	encode: function(element){
	     var retour = element; 
	     retour = retour.gsub("#","[diez]");
	     retour = retour.gsub("%","[pourcent]");
	     retour = retour.gsub("&","[esperluette]");
	     retour = retour.gsub("'","[apos]");
	     retour = retour.gsub(/\?/,"[point_int]");
	     return(retour);
	},
	
	warning: function(ec,validator){
		if($($$$F.liste[ec].id+'_w') != undefined){
			$($$$F.liste[ec].id+'_w').setStyle({visibility: 'visible'});
			if(validator == 'confirmation'){
				$($$$F.liste[ec].id +"_confirmation").setStyle({border : 'solid 1px red'});
			}
			var trad = eval('$$$F.traduction.' + validator);
			alert('Le champ marqué d\'un icône "Attention" ' + trad);
		}
	},
	
	initWarning: function(){
		$$('img.warning').map(function(a){a.setStyle({visibility: 'hidden'})});
	},
	
	showBlock: function(el){
		$(el).setStyle({display: 'block'});
	},
	
	hideBlock: function(el){
		$(el).setStyle({display: 'none'});
	}
});

var FormItem = Class.create({
	initialize: function(arr){
		this.id = arr[0];
		this.type = arr[1];
		this.dataProvider = arr[2];
		this.data = arr[3];
		this.validators = arr[4];
	}
});