/**
 * @projectDescription	Classe permettant de gérer la création/suppression de champs dans un formulaire
 * 
 * @author				Luc ALBERT luc[at]nematis[dot]com
 * @version				1.2.2
 * @since				1.1
 * 
 * - Ajout de la gestion des champs type periode (2 champs "du" "au" contenant des dates)
 * - Gestion des champs dynamiquement (ajout à la volée [ex: données d'une bdd])
 * - Ajout du paramètre constructeur notAdd
 * 
 * [MODIF - 15/10/2007]
 * - Utilisation de maxChamp : 0 n'est plus illimité mais équivalent à notAdd=true! Pour illimité maxChamp=-1
 * 
 * [MODIF - 31/10/2007]
 * - Ajout des paramètres "txtAdd" et "txtRm" qui permettent de spécifier le texte afficher pour l'ajout et la suppression des champs
 * - Modification du code source généré afin de rendre le code accéssible aux css [voir la section hierarchie ci-dessous]
 * 
 * [MODIF - 24/12/2008]
 * - Ajout de la gestion des champs type nomPrenom (2 champs "texte")
 * 
 * [MODIF - 06/01/2009]
 * - Ajout de la gestion des champs type nomPrenomVille (3 champs "texte" :: nom, prenom, ville)
 * 
 * Exemple d'utilisation : 
 * 
 * -- Pour un champ texte
 * <script type="text/javascript">
 *	var Chp_benefices = new multiInput("Chp_benefices", "lib_benefices");
 *	{section name=benefice loop=$benefices}
 *		Chp_benefices.addChamp(["{$benefices[benefice]}"]);
 *	{/section}
 * </script>
 */
 
/**
 * Hierarchie CSS
 * 
 * Voici le code source généré avec l'appelle du javascript suivant : (on suppose que 2 champs on été ajoutés)
 * 
 * <script type="text/javascript">
 * 	var MyChamps = new multiInput("iChamps", "lib_chps", "text", '', '', "Ajouter", "Supprimer");
 * </script>
 * 
 * 
 * <div id="box_iChamps">
 * 		<span> id="Chp_iChamps_1">
 * 			<input type="text" name="lib_chps[]" />
 * 			<a ... class="rmChamp"><span>Supprimer</span></a>
 * 		</span>
 * 
 * 		<span> id="Chp_iChamps_2">
 * 			<input type="text" name="lib_chps[]" />
 * 			<a ... class="rmChamp"><span>Supprimer</span></a>
 * 		</span>
 * 
 * 
 * 		<span id="newchamp_iChamps">
 * 			<a ... ><span>Ajouter</span></a>
 * 		</span>
 * </div>
 * 
 */

 /* TODO : - Possibilité d'ajouter des attributs aux champs
  * 	   	 - Modifier les texte ajouter/supprimer champs (voir possibilité d'attribuer une image)
  * 	   	 - Pouvoir créer ses propres type de champs (genre "période!")
  */
 
 /**
 * Création d'une nouvelle instance de multiInput
 *
 * @classDescription				Class créant un nouvel objet multiInput
 * @param {string} nomInstance		Nom de l'instance de l'objet multiInput créé. Ce nom doit être absolument identique à l'instance (ex: ma_nouvelle_instance = new multiInput("ma_nouvelle_instance", ...)
 * @param {string, array} nomChamp	Nom des champs à gérer.
 * @param {string} [typeChamp]		Type de champ à gérer (text, file). Si ce paramètre est omis, c'est un champ de type text qui sera géré par défaut
 * @param {int} [maxChamp]			Nombre maximum de champ qui peuvent être créer. Si ce paramètre est omis, il sera mis à -1, c'est à dire que le nombre de champ pouvant être créé sera illimité.
 * @param {bool} [notAdd]			Booléen qui spécifie si l'on peut ou non ajouter des champs. Ceci est utilise quand on génère des champs à partir de données exsistantes (bdd). On ne peut alors laisser le choix que de supprimer des champs mais pas d'en rajouter. Si à TRUE, on ne tien plus compte de maxChamp
 * @return {multiInput}				Retourne un nouvel objet multiInput
 * @type {Object}
 * @constructor
 */
function multiInput(nomInstance, nomChamp, typeChamp, maxChamp, notAdd, txtAdd, txtRm){

	//Définition d'un tableau correspondant au type de champ que l'on est autorisé à créer
	var type		= new Array('text', 
								'file',
								'periode',
								'nomPrenom',
								'nomPrenomVille');
	
	//initialise les propriétés de l'instance
	
	this.nbrChamp	= 0;
	
	this.instance	= nomInstance;
	this.typeChamp	= typeChamp 	|| "text";
	this.nomChamp	= nomChamp;
	this.maxChamp	= maxChamp 		|| -1;
	this.notAdd		= notAdd		|| false;
	
	this.txtAdd		= txtAdd		||	"Ajouter un nouveau champ";
	this.txtRm		= txtRm			||	"Supprimer ce champ";
	
	this.erreur		= new Array(false);
	this.indiceCurrent		= 0;
	
	// maj notAdd
	if( this.maxChamp == 0 )this.notAdd = true;
/*
* Les variables utilisées
* 
*/
	//vérification des paramètres et gestion des erreurs
	if(this.instance == "" || this.instance == null || this.instance == 'undefined'){
			this.erreur[0]=true;
			this.erreur.push("Le paramètre \"nomInstance\" n'est pas renseigné.\n\nIl est obligatoire et doit corresponde au nom de l'instance créé : nominstance=new multiInput(\"nominstance\",...)");
	}
	
	if(!in_array(this.typeChamp, type)){
		this.erreur[0]=true;
		this.erreur.push("Le paramètre \"typeChamp\" n'est pas valable.\n\nSeuls les types "+type.join(" | ")+" sont autorisés.");
	}
	
	//création du 1er champ si pas d'erreur trouvé
	if(!this.erreur[0]){
		constructeur	 = '\n<div id="box_'+this.instance+'">\n';
		/* supprimé car cela ajoutait un champ par default
		if(this.typeChamp == "periode"){
			constructeur +='\t<span id="'+this.instance+'_0">du <input type="text" name="'+this.nomChamp[0]+'[]" /> au <input type="text" name="'+this.nomChamp[1]+'[]" /></span><br />\n';
		}else{
			constructeur += '\t<span id="'+this.instance+'_0"><input type="'+this.typeChamp+'" name="'+this.nomChamp+'[]" /></span><br />\n';
		}
		*/
		constructeur	+= '\t<span id="newchamp_'+this.instance+'"><a href="javascript:'+this.instance+'.addChamp([\'\',\'\',\'\'])"><span>'+this.txtAdd+'</span></a></span>\n'
		constructeur	+= '</div>'
	}else{
		constructeur	 = '<span style="font-weight:bold;color:red">Il y a des erreurs</span>';
		
		mess_err 	 = 'Il y a des erreurs :\n\n';
		for(i=1;i<this.erreur.length;i++){
			mess_err	+=  'Erreur '+i+' : '+this.erreur[i]+'\n';
			mess_err	+=	'---------------------------------------------------------------------------------';
		}
		alert(mess_err);
	}
	document.write(constructeur);
	
	affiche_add(this.instance, this.nbrChamp, this.maxChamp, this.notAdd);
}

 /**
 * Ajoute des champs
 * @memberOf				multiInput
 * @method
 * @return {void}			Ne retourne rien
 * @param {Array} values	Tableau des valeurs des champs (1er champ=values[0], 2ème champ=values[1],...)
 */
function addChamp(values){
	
	indiceCurrent=this.indiceCurrent;
	
	//incrémente le compteur de champ
	this.nbrChamp++;
	
	indiceNext=indiceCurrent+1;	//on génère l'indice du champ suivant
	
	newChamp=document.createElement("span");	//on crée un nouvel élement span
	newChamp.setAttribute("id",this.instance+"_"+indiceNext);	//on lui attribut un id
	if(this.typeChamp == "periode"){
		newInput ='\tdu <input type="text" name="'+this.nomChamp[0]+'[]" id="ID_'+this.instance+'_'+this.nomChamp[0]+'_'+indiceNext+'" value="'+values[0]+'" size="20" class="inputDate require type_date" /><img class="bt_calendrier" id="bt_ID_'+this.instance+'_'+this.nomChamp[0]+'_'+indiceNext+'" title="Calendrier" alt="Calendrier" src="/framework/images/bt_calendrier.png" />';
		newInput+=' au <input type="text" name="'+this.nomChamp[1]+'[]" id="ID_'+this.instance+'_'+this.nomChamp[1]+'_'+indiceNext+'" value="'+values[1]+'" size="20" class="inputDate require type_date DateFin_ID_'+this.instance+'_'+this.nomChamp[0]+'_'+indiceNext+'" /><img class="bt_calendrier" id="bt_ID_'+this.instance+'_'+this.nomChamp[1]+'_'+indiceNext+'" title="Calendrier" alt="Calendrier" src="/framework/images/bt_calendrier.png" />';
		newInput+=' <a href="javascript:'+this.instance+'.rmChamp('+indiceNext+')" class="rmChamp"><span>'+this.txtRm+'</span></a><br />\n';
	}
	else if( this.typeChamp == "nomPrenom" ){
		newInput ='\tNom : <input type="text" name="'+this.nomChamp[0]+'[]" id="ID_'+this.instance+'_'+this.nomChamp[0]+'_'+indiceNext+'" value="'+values[0]+'" size="20" class="require type_texte" />';
		newInput+=' Prénom : <input type="text" name="'+this.nomChamp[1]+'[]" id="ID_'+this.instance+'_'+this.nomChamp[1]+'_'+indiceNext+'" value="'+values[1]+'" size="20"  class="require type_texte" />';
		newInput+=' <a href="javascript:'+this.instance+'.rmChamp('+indiceNext+')" class="rmChamp"><span>'+this.txtRm+'</span></a><br />\n';
	}
	else if( this.typeChamp == "nomPrenomVille" ){
		newInput ='\tNom : <input type="text" name="'+this.nomChamp[0]+'[]" id="ID_'+this.instance+'_'+this.nomChamp[0]+'_'+indiceNext+'" value="'+values[0]+'" size="20" class="require type_texte" />';
		newInput+=' Prénom : <input type="text" name="'+this.nomChamp[1]+'[]" id="ID_'+this.instance+'_'+this.nomChamp[1]+'_'+indiceNext+'" value="'+values[1]+'" size="20"  class="require type_texte" />';
		newInput+=' Ville : <input type="text" name="'+this.nomChamp[2]+'[]" id="ID_'+this.instance+'_'+this.nomChamp[2]+'_'+indiceNext+'" value="'+values[2]+'" size="20"  class="require type_texte" />';
		newInput+=' <a href="javascript:'+this.instance+'.rmChamp('+indiceNext+')" class="rmChamp"><span>'+this.txtRm+'</span></a><br />\n';
	}
	else{
		newInput = '\t<input type="'+this.typeChamp+'" name="'+this.nomChamp+'[]" value="'+values[0]+'" /><a href="javascript:'+this.instance+'.rmChamp('+indiceNext+')" class="rmChamp"><span>'+this.txtRm+'</span></a><br />\n';
	}
	//newInput='<input type="'+this.typeChamp+'" name="'+this.nomChamp+'[]" /><a href="javascript:'+this.instance+'.rmChamp('+indiceNext+')"><span>'+ this.txtRm +'</span></a><br />\n';
	newChamp.innerHTML=newInput;
	
	inclusion = document.getElementById("newchamp_"+this.instance);
  	document.getElementById('box_'+this.instance).insertBefore(newChamp, inclusion);
	
	lien='<a href="javascript:'+this.instance+'.addChamp([\'\',\'\',\'\'])"><span>'+this.txtAdd+'</span></a>';
  	document.getElementById('newchamp_'+this.instance).innerHTML=lien;
	
	//Création de l'instance de calendar
	if(this.typeChamp=="periode"){
		Calendar.setup({"inputField":"ID_"+this.instance+"_"+this.nomChamp[0]+"_"+indiceNext,"button":"bt_ID_"+this.instance+"_"+this.nomChamp[0]+"_"+indiceNext,"singleClick":true,"ifFormat":"%d/%m/%Y"});
		Calendar.setup({"inputField":"ID_"+this.instance+"_"+this.nomChamp[1]+"_"+indiceNext,"button":"bt_ID_"+this.instance+"_"+this.nomChamp[1]+"_"+indiceNext,"singleClick":true,"ifFormat":"%d/%m/%Y"});
	}
	
	this.indiceCurrent++;
	affiche_add(this.instance, this.nbrChamp, this.maxChamp, this.notAdd);
}

/**
 * Supprime des champs
 * @memberOf multiInput
 * @method
 * @return {void}
 * @param {Integer} indiceCurrent		indice du champ à supprimer
 */
function rmChamp(indice){
	
	//décremente le compteur de champ
	this.nbrChamp--;
	document.getElementById(this.instance+"_"+indice).innerHTML="\n";
	
	affiche_add(this.instance, this.nbrChamp, this.maxChamp, this.notAdd);
}

//définitions des méthodes de la classe

multiInput.prototype.addChamp=addChamp;
multiInput.prototype.rmChamp=rmChamp;


function affiche_add(instance, nbrChamp, maxChamp, notAdd){
	
	if(maxChamp != -1 && !notAdd){
		if(nbrChamp >= maxChamp){
			document.getElementById('newchamp_'+instance).style.display="none";
		}else{
			document.getElementById('newchamp_'+instance).style.display="inline";
		}
	}else if(notAdd){
		document.getElementById('newchamp_'+instance).style.display="none";
	}else{
		document.getElementById('newchamp_'+instance).style.display="inline";
	}
}

/*fonctions supplémentaires*/
/**
 * 
 * @param {String} chaine		Chaîne de caractère à vérifier
 * @param {Array} tableau		Tableau des valeurs à vérifier
 * @return {Bool} retour		Retourne true si la valeur existe dans le tableau sinon retourne false
 */
function in_array(chaine, tableau){
	var retour=false;
	
	for(i=0;i<tableau.length;i++){
		if(tableau[i]==chaine){
			retour=true;
			break;
		}
	}
	
	return retour;
}
