
var Page = {};

/**
 * Création d'un objet pour le traitement des listes
 */
Page.List = Class.create();
Page.List.prototype = {

	/**
	 * constructeur de la classe
	 */
	initialize: function(options) {
		
		// Définition des parametres
		this.url			= 'ajax/list.php?t=1';
		this.action 		= 'action.php';
		this.id_container	= 'adm-list';
		this.id_form_search	= 'form_search';
		this.id_form_list	= 'form_list';
		this.img_loader		= '<img src="images/ajax-loader.gif" height="16" width="16" />';
		this.strGET			= '';
		this.strSearch		= '';
		this.strList		= '';
		this.page			= 0;
		this.sort			= 1;
		this.limit			= 10;
		this.order			= 'ASC';
		this.options		= {};
	
		Object.extend(this.options, options || {});
		
		// on affecte les propriétés des options
		for (var o1 in this) {
			for (var o2 in this.options) {
				if (o1==o2) {
					this[o1] = this.options[o2];
				}
			}
		}
		
		
		if($(this.id_container)){
			this.container = $(this.id_container);
		}else{
			alert("Attention, le conteneur n'est pas valide.");
		}
	}, // fin du constructeur

	/**
	 * affiche le tableau de liste
	 */
	display: function (options)
	{
		this.options		= {};
	
		Object.extend(this.options, options || {});

		if(this.options.onFinish){
			onfinish = this.options.onFinish;
		}

		
		
		if ($(this.id_form_search)) { this.strSearch = "&" + $(this.id_form_search).serialize(); }
		if ($(this.id_form_list)) {	this.strList = "&" + $(this.id_form_list).serialize(); }
		
		this.strGET = this.strSearch + this.strList;
	
		var container = this.container;
	
		container.update(this.img_loader);
		
		new Ajax.Request(this.url + this.strGET, {
			method: 'get',
			onSuccess: function(transport) {
				
				container.update(transport.responseText);
				
				if(onfinish)
				onfinish();
				
			}
		});
	},
	
	/**
	 * Déplacement des lignes de la liste
	 */
	drag: function(options){
		
		this.currentDrag = { id:0,rang:0,old_rang:0}; // objet d'enregistrement de l'element déplacé
		this.sort_id   = "drag-list"; // id du conteneur de la liste
		this.handle_id = "handle"; // class handle pour les deplacements
		this.actionurl = 'action.php?act=sortDrag'; // URL de la page php pour les mise a jour
		this.tagType = 'div'; // type de tag utilisé
		
		Object.extend(this.options, options || {});
		
		// on affecte les propriétés des options
		for (var o1 in this) {
			for (var o2 in this.options) {
				if (o1==o2) {
					this[o1] = this.options[o2];
				}
			}
		}
		
		//******************************************************
		// on enregistre les attributs des elements de la liste
		//******************************************************
		
		// on parcour les elements qui ont un handler
		elem = $(this.sort_id).getElementsByClassName(this.handle_id);
		rang = 1;
		// pour chaque element on enregistre le rang onmouseover
		elem.each(function(el) {
			el.oldRang = rang;

			//on enregistre l'element courant sur le click
			Event.observe(el, 'mouseover', function() { 
				currentDrag.id = el.readAttribute('id');
			});  
			rang++;
		});
		
		sort_id = this.sort_id; //id du conteneur
		handle_id = this.handle_id; // id de l'handler
		actionurl = this.actionurl; // url action
		tagType = this.tagType;
		
		
		//******************************************************
		// on créé le tri
		//******************************************************
		Sortable.create(sort_id , {tag:tagType,constraint: false,handle:handle_id,
			onChange:function(){
				// si la liste de tri existe	
				if($(sort_id)){
			
					var rang = 1; // rang courant de l'item
					// on récupère tout les éléments drag n drop
					elem = $(sort_id).getElementsByClassName(handle_id);
					elem.each(function(el) {
					
						id = el.readAttribute('id');
						el.update(rang);
						
						if(currentDrag.id == id){  // si c'est l'element courant on enrgistre le nouveau rang
							currentDrag.rang = rang;
							currentDrag.old_rang = el.oldRang;
						}else{
							el.oldRang = rang;
						}
						
						rang++;
					});
					
					
				}else{
					alert("L'identifiant '"+sort_id+"' est inexistant!");
				}
				
			},
			onUpdate:function(){

				//on enregistre l'ancien rang
				$(currentDrag.id).oldRang = currentDrag.rang;
				
				//*************************************
				// enregistrement du déplacement
				//**************************************
				var post = $H({id: currentDrag.id,new_rang:currentDrag.rang,old_rang:currentDrag.old_rang}).toQueryString(); // parameteres post
				// requete sur le serveur
				
				new Ajax.Request(actionurl, {
					method: 'post',
					postBody:post,
					onSuccess: function(transport) {
						//
					}
				});
			}
		});
	},
	
	/**
	 * change la page courante de la liste
	 */
	changePage: function (page)
	{
		$(this.id_form_list).elements['p'].value = page;
		this.page = page;
		this.display();
	},

	/**
	 * Sort et Order de la liste
	 */
	sortList: function (s,o)
	{
		if($(this.id_form_list)){
			$(this.id_form_list).elements['sort'].value = s;
			$(this.id_form_list).elements['order'].value = o;
			this.sort = s;
			this.order = o;
			this.display();
		}else{
			alert("Le formulaire de la liste n'est pas valide pour le tri.")	
		}
	},
	
	/**
	 * change l'etat
	 * @param id : identifiant
	 * @param etat : etat à changer
	 */
	changeState: function (id, state)
	{
		var url = this.action + '?act=changeState&state=' + state + '&id=' + id;
		
		var container = this.container;
		container.update(this.img_loader);
		
		var obj = this;
		
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport) {
				obj.display();
			}
		});
	},
	
	/**
	 * change l'ordre d'un element
	 * @param id : identifiant
	 * @param order : nouvel ordre de l'element
	 */
	changeOrder: function (id, order)
	{
		var url = this.action + '?act=changeOrder&sort=' + order + '&id=' + id;
		
		var container = this.container;
		container.update(this.img_loader);
		
		var obj = this;
		
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport) {
				obj.display();
				new Display.Message("L'entrée a été déplacée !", {cssClass: "adm-info"});
			}
		});
	},
	
	/**
	 * Suppression des éléments cochés de la liste
	 */
	deleteList: function ()
	{
		if (confirm("Etes vous sur de vouloir supprimer votre sélection ?")) {
		
			$(this.id_form_list).elements["act"].value = "deleteMulti";

			var obj = this;
			
			$(this.id_form_list).request({
				onComplete: function(transport){
					obj.display();
					new Display.Message("Les entrées séléctionnées ont été supprimées !", {cssClass: "adm-info"});
				}
			});
		}
	},
	
	/**
	 * Cocher/Décocher toutes les coches de la liste
	 */
	checkAll: function (checked)
	{
		var tab = $(this.id_form_list).elements;
		for (i=0; i<tab.length; i++) {
			if (tab[i].name.substr(0,5) == "check" && tab[i].disabled == false) {
				if (checked) {
					tab[i].checked = true;
				} else {
					tab[i].checked = false;
				}
			}
		}
	}
}; // fin de List





/**
 * Création d'un formulaire
 */
Page.Form = Class.create();
Page.Form.prototype = {

	/**
	 * constructeur de la classe
	 */
	initialize: function(form, options) {
		
		// Définition des parametres
		this.form		= form;
		this.options	= {};
		
		Object.extend(this.options, options || {});
		
		// on affecte les propriétés des options
		for (var o1 in this) {
			for (var o2 in this.options) {
				if (o1==o2) {
					this[o1] = this.options[o2];
				}
			}
		}

		if(!$(this.form)){
			alert("Attention le nom du formulaire est vide ou inexistant");
		}	

	} // fin du constructeur
	,
	/**
	 * verification du formulaire
	 */
	verif: function(data, options){ // veririfcation du formulaire
		
		this.bgColorAlerte = "#DDDDDD";
		this.bgColorBase = "#ffffff";
		this.ftColorAlerte = "#000000";
		this.ftColorBase = "#000000";
		this.valid = true;
		this.message = "<strong>Attention erreur de saisie !</strong>";
		
		Object.extend(this.options, options || {});
		
		// on affecte les propriétés des options
		for (var o1 in this) {
			for (var o2 in this.options) {
				if (o1==o2) {
					this[o1] = this.options[o2];
				}
			}
		}
		
		cptDisplayError = 0;
		
		for (var element in data) {
		
			validLigne = true;
			
			var elt = $(this.form).elements[element]; 			
			elt = $(elt);
		
			if(elt){
				
				elt.setStyle({backgroundColor:this.bgColorBase,color:this.ftColorBase});
				
				switch(data[element].type){
			
					case "email":
						if( ((data[element].need)||(elt.getValue()!="")) && isNotEmailAdress(elt.getValue()) ){
							elt.setStyle({backgroundColor:this.bgColorAlerte,color:this.ftColorAlerte});
							this.valid = false;
							validLigne = false;
						}
					break;
					
					case "cp":
						if( ((data[element].need)||(elt.getValue()!="")) && isNotCodePostal(elt.getValue()) ){
							elt.setStyle({backgroundColor:this.bgColorAlerte,color:this.ftColorAlerte});
							this.valid = false;
							validLigne = false;
						}
					break;
					
					case "int":
						if( ((data[element].need)||(elt.getValue()!="")) && isNotInt(elt.getValue()) ){
							elt.setStyle({backgroundColor:this.bgColorAlerte,color:this.ftColorAlerte});
							this.valid = false;
							validLigne = false;
						}
					break;
					
					case "float":
						if( ((data[element].need)||(elt.getValue()!="")) && isNotFloat(elt.getValue()) ){
							elt.setStyle({backgroundColor:this.bgColorAlerte,color:this.ftColorAlerte});
							this.valid = false;
							validLigne = false;
						}
					break;
					
					case "tel":
						if( ((data[element].need)||(elt.getValue()!="")) && isNotTelephone($elt.getValue(),data[element].typetel) ){
							elt.setStyle({backgroundColor:this.bgColorAlerte,color:this.ftColorAlerte});
							this.valid = false;
							validLigne = false;
						}
					break;
					
					case "password":
						if($(data[element].pass2)){
							$(data[element].pass2).setStyle({backgroundColor:this.bgColorBase,color:this.ftColorBase});
							
							if(data[element].need){
								if( ( elt.getValue()=="" ) || (elt.getValue()!=$(data[element].pass2).getValue() ) ){
									elt.setStyle({backgroundColor:this.bgColorAlerte,color:this.ftColorAlerte});
									$(data[element].pass2).setStyle({backgroundColor:this.bgColorAlerte,color:this.ftColorAlerte});
									this.valid = false;
									validLigne = false;
								}
							}else{
								if( ( elt.getValue()=="" ) || (elt.getValue()!=$(data[element].pass2).getValue() ) ){
									elt.setStyle({backgroundColor:this.bgColorAlerte,color:this.ftColorAlerte});
									$(data[element].pass2).setStyle({backgroundColor:this.bgColorAlerte,color:this.ftColorAlerte});
									this.valid = false;
									validLigne = false;
								}
							}
						}else{
							alert("La confirmation du mot de passe est obligatoire");
						}
					break;
					
					default:
						if((elt.getValue()=="")&&(data[element].need)){
							elt.setStyle({backgroundColor:this.bgColorAlerte,color:this.ftColorAlerte});
							this.valid = false;
							validLigne = false;
						}
					break;
				}

				if( (data[element].mincar)&&(elt.getValue().length<data[element].mincar)) {
					elt.setStyle({backgroundColor:this.bgColorAlerte,color:this.ftColorAlerte});
					this.valid = false;
					validLigne = false;
				}
				
				if( (!validLigne) &&(data[element].message)){
					if(cptDisplayError==0){
						this.message += '<ul>';
					}
					this.message += "<li>"+data[element].message+"</li>";
					cptDisplayError ++;
				}
				
			}else{
				alert("Attention, le champs '"+element+"' n'existe pas !!")	
			}
		}
		
		if( (!this.valid)&&(this.message!="")){
			
			if(cptDisplayError>0){
			this.message += "</ul>";
			}
			
			new Display.Message(this.message, {cssClass: "form-alert",speed:0.3});
		}
		
		return this.valid;
	}


	
}; // fin de Form.Verif



