// ajout d'un champ
function addField() {
	var champ = $F("add_field");
	
	/* zone de texte : titre et corps de la notice 	*/
	if (champ == 'titre') {
		addText('titre', "Mot(s) du titre ou de la légende");	//Champ commun
			n = n+1;

	}else if (champ == 'pleintexte') { //Champ commun
		addText('pleintexte', "Mot(s) du texte");
			n = n+1;

	}
	/* zone de texte avec autocomplétion :	*/
	/* person , cadre, communes, thésaurus sujet				*/
	else if (champ == 'fauteur') { //Champ commun
		box = document.getElementById('notice');
		if(box.checked){
			addAutocompletionNotices('fauteur', "Nom de personne (notices)");
			n = n+1;
		}
		box = document.getElementById('breve');
		if(box.checked){
			addAutocompletionBreves('fbrauteur', "Nom de personne (brèves)");
			n = n+1;
		}
		box = document.getElementById('illu');
		if(box.checked){
			addAutocompletionIllus('fiauteur', "Nom de personne (illustrations)");
			n = n+1;
		}
	} else if (champ == 'cadre') {
		addAutocompletionNotices(champ, "Cadre d'étude (notices)");
		n = n+1;
	} else if (champ == 'brcadre') {
		addAutocompletionBreves(champ, "Cadre d'étude (breves)");
		n = n+1;
	} else if (champ == 'fcommune') { //Champ commun
		box = document.getElementById('notice');
		if(box.checked){
			addAutocompletionNotices('fcommune', "Commune (notices)");
			n = n+1;
		}
		box = document.getElementById('breve');
		if(box.checked){
			addAutocompletionBreves('fbrcommune', "Commune (brèves)");
			n = n+1;
		}
		box = document.getElementById('illu');
		if(box.checked){
			addAutocompletionIllus('ficommune', "Commune (illustrations)");
			n = n+1;
		}
	} else if (champ == 'id') { //Champ commun
		box = document.getElementById('notice');
		if(box.checked){
			addAutocompletionNotices('noticeId', "Identifiant (notices)");
			n = n+1;
		}
		box = document.getElementById('breve');
		if(box.checked){
			addAutocompletionBreves('breveId', "Identifiant (brèves)");
			n = n+1;
		}
		box = document.getElementById('illu');
		if(box.checked){
			addAutocompletionIllus('figureId', "Identifiant (illustrations)");
			n = n+1;
		}
	/*} else if (champ == 'figureId') {
		addAutocompletionIllus(champ, "Identifiant de l'illustration (illustrations)");
		n = n+1;*/
	} else if (champ == 'fisujets') {
		addAutocompletionIllus(champ, "Sujets (illustrations)");
		n = n+1;
	} else if (champ == 'fthemes') {
		addAutocompletionNotices(champ, "Sujets (notices)");
		n = n+1;
	}	
	
	/* liste de choix :									*/
	/* opération, date, thésaurus(sauf sujet), région, département	*/
	else if (champ == 'operation') {
		addSelection(champ, "Type d'opération (notices)");
		n = n+1;
	} else if (champ == 'broperation') {
		addSelection(champ, "Type d'opération (brèves)");
		n = n+1;
	} else if (champ == 'dates_operations') {
		addSelection(champ, "Date de l'opération (notices)");
		n = n+1;
	} else if (champ == 'brdates_operations') {
		addSelection(champ, "Date de l'opération (brèves)");
		n = n+1;
	} else if (champ == 'fdepartement') { //Champ commun
		addSelectionDept('departement', "Département"); 
		n = n+1;
	} else if (champ == 'fregion') { //Champ commun
		addSelectionDept('region', "Région"); 
		n = n+1;
	} else if (champ == 'fchronologie') {
		addSelection(champ, "Chronologie (notices)");
		n = n+1;
	} else if (champ == 'fbrchronologie') {
		addSelection(champ, "Chronologie (brèves)");
		n = n+1;
	} else if (champ == 'fpeuples') {
		addSelection(champ, "Peuples (notices)");
		n = n+1;
	} else if (champ == 'fanthroponyme') {
		addSelection(champ, "Anthroponymes (notices)");
		n = n+1;
	} else if (champ == 'flieux') {
		addSelection(champ, "Lieux (notices)");
		n = n+1;
	} else if (champ == 'type') {
		addSelection(champ, "Type d'illustration (illustrations)");
		n = n+1;
	}
}

// ajout d'un champ texte
function addText(champ, intitule) {
	tbody = $('ajout');
	tr = Builder.node('tr', {id: n+'_tr'}, [
			addBoolean(champ),
			Builder.node('td',[intitule]),
			Builder.node('td', {colspan :2}, [
				Builder.node('input', {name: n+'_'+champ, type: 'text', value: '', size: '50', className: 'recherche_champ'})
			]),
			Builder.node('td', [
				Builder.node('input', {className: 'bouton', type: 'button', value: '-', onclick: 'removeElement('+n+')'})
			])
		]);
  	tbody.appendChild(tr);
}

// ajout d'un champ d'autocomplétion
function addAutocompletionNotices (champ, intitule) {
	tbody = $('ajout');
	tr = Builder.node('tr', {id: n+'_tr'}, [
			addBoolean(champ),
			Builder.node('td',[intitule]),
			Builder.node('td',[
				Builder.node('input', {id: n+'_'+champ+'-choice', name: n+'_'+champ+'-choice', type: 'text', value: '', size: '50'}),
				Builder.node('div', {id:n+'_'+'suggestion', className: 'autocompletion recherche_champ', style:'display:none'})
			]),
			Builder.node('td',[
				Builder.node('select', {
					className: 'choix',
					name: n + '_' + champ + '-chosen', 
					id:n + '_' + champ + '-chosen', 
					style: 'width: 100%; max-width: 100%;',
					size: 5,
					multiple: 'true',
					className: 'recherche_liste',
					onclick: 'delOption('+n+',\''+champ+'\',0)'
				})
			]),
			Builder.node('td', [
				Builder.node('input', {className: 'bouton', type: 'button', value: '-', onclick: 'removeElement('+n+')'})
			])
		]);
	tbody.appendChild(tr);
	var params = 'field='+champ+'&id='+n+'_'+champ+"-choice";
	autocompletion = new Ajax.Autocompleter(n+'_'+champ+'-choice',
						n+'_'+'suggestion',
						'autocompletionNotices',
						{updateElement: updateList,
						parameters: params});	
}

// ajout d'un champ d'autocomplétion
function addAutocompletionBreves (champ, intitule) {
	tbody = $('ajout');
	tr = Builder.node('tr', {id: n+'_tr'}, [
			addBoolean(champ),
			Builder.node('td',[intitule]),
			Builder.node('td',[
				Builder.node('input', {id: n+'_'+champ+'-choice', name: n+'_'+champ+'-choice', type: 'text', value: '', size: '50'}),
				Builder.node('div', {id:n+'_'+'suggestion', className: 'autocompletion recherche_champ', style:'display:none'})
			]),
			Builder.node('td',[
				Builder.node('select', {
					className: 'choix',
					name: n + '_' + champ + '-chosen', 
					id:n + '_' + champ + '-chosen', 
					style: 'width: 100%; max-width: 100%;',
					size: 5,
					multiple: 'true',
					className: 'recherche_liste',
					onclick: 'delOption('+n+',\''+champ+'\',0)'
				})
			]),
			Builder.node('td', [
				Builder.node('input', {className: 'bouton', type: 'button', value: '-', onclick: 'removeElement('+n+')'})
			])
		]);
	tbody.appendChild(tr);
	var params = 'field='+champ+'&id='+n+'_'+champ+"-choice";
	autocompletion = new Ajax.Autocompleter(n+'_'+champ+'-choice',
						n+'_'+'suggestion',
						'autocompletionBreves',
						{updateElement: updateList,
						parameters: params});	
}

// ajout d'un champ d'autocomplétion
function addAutocompletionIllus (champ, intitule) {
	tbody = $('ajout');
	tr = Builder.node('tr', {id: n+'_tr'}, [
			addBoolean(champ),
			Builder.node('td',[intitule]),
			Builder.node('td',[
				Builder.node('input', {id: n+'_'+champ+'-choice', name: n+'_'+champ+'-choice', type: 'text', value: '', size: '50'}),
				Builder.node('div', {id:n+'_'+'suggestion', className: 'autocompletion recherche_champ', style:'display:none'})
			]),
			Builder.node('td',[
				Builder.node('select', {
					className: 'choix',
					name: n + '_' + champ + '-chosen', 
					id:n + '_' + champ + '-chosen', 
					style: 'width: 100%; max-width: 100%;',
					size: 5,
					multiple: 'true',
					className: 'recherche_liste',
					onclick: 'delOption('+n+',\''+champ+'\',0)'
				})
			]),
			Builder.node('td', [
				Builder.node('input', {className: 'bouton', type: 'button', value: '-', onclick: 'removeElement('+n+')'})
			])
		]);
	tbody.appendChild(tr);
	var params = 'field='+champ+'&id='+n+'_'+champ+"-choice";
	autocompletion = new Ajax.Autocompleter(n+'_'+champ+'-choice',
						n+'_'+'suggestion',
						'autocompletionIllus',
						{updateElement: updateList,
						parameters: params});	
}

// mise à jour de la liste li
function updateList(li) {
	var id = li.up('div').previous().id;
	Field.clear(id);
	var select = $(id.replace("-choice", "-chosen"));
	var text = li.down("span.value").innerHTML;
	addOption(select,text);
}

// ajout une liste à sélection : 2e méthode
function addSelectionDept (champ, intitule) {
	tbody = $('ajout');
	tr = Builder.node('tr', {id: n+'_tr'}, [
			addBoolean(champ),
			Builder.node('td',[intitule]),
			Builder.node('td', [
				Builder.node('select', {
					name: n + '_' + champ + '-choice', 
					id:n + '_' + champ + '-choice', 
					style: 'width: 100%; max-width: 100%;',
					size: 5,
					multiple: 'true',
					onclick: 'swap('+n+',\''+champ+'\',0)'
				})
			]),
			Builder.node('td', [
				Builder.node('select', {
					name: n + '_' + champ + '-chosen', 
					id:n + '_' + champ + '-chosen', 
					style: 'width: 100%; max-width: 100%;',
					size: 5,
					multiple: 'true',
					className: 'recherche_liste',
					onclick: 'swap('+n+',\''+champ+'\',1)'
				})				
			]),
			Builder.node('td', [
				Builder.node('input', {className: 'bouton', type: 'button', value: '-', onclick: 'removeElement('+n+')'})
			])
		]);
  	tbody.appendChild(tr);
  	var num = n; /* afin d'éviter le décalage entre la variable global n et le temps de réponse d'ajax */

	
	if(document.getElementById('notice').checked){	
		champ2 = "f"+champ;
		ajax = new Ajax.Request('listTerms.ajax', 
		{
			method: 'post',
			parameters: $H({'field': champ2}).toQueryString(),
			onSuccess: function(request) {
				optionsb = request.responseText.substring(request.responseText.indexOf("<select>")+8,request.responseText.indexOf("</select>")-1);
				
				var temp = optionsb;
				var tab_optionsb = new Array();
				var j=0;
				
				for(var i=temp.length; i>=0; i--) {												
					tab_optionsb[j] = temp.substring(temp.indexOf("<option value=")+15,temp.indexOf(">")-1);
					temp = temp.substring(temp.indexOf("</option>")+9,temp.length);
					j=j+1;
					i=temp.length;
				}
				
				var liste = $(num + '_' + champ + '-choice');
				
				// on le rajoute dans l'ordre alphabétique dans l'autre select				
				for(var i=0; i < tab_optionsb.length; i++) {
					var idem =false;
					for(j=0 ; j < liste.options.length; j++) {						
						if(liste.options[j].value.toLowerCase()==(tab_optionsb[i].toLowerCase())){
							idem =true;
						}						
						if(liste.options[j].value.toLowerCase() > tab_optionsb[i].toLowerCase()) {
							suivant = liste.options[j];
							break;
						}
					}
					option = Builder.node('option', {value:tab_optionsb[i]}, [tab_optionsb[i]]);
					
					if(idem==false){
						if(liste.options.length > 0 && j!= liste.options.length) {
							liste.insertBefore(option,suivant);
						} else {
							liste.appendChild(option);
						}
					}
				}
				
				
			}
		}
	);	
	}
	
	if(document.getElementById('breve').checked){
	champ2 = "fbr"+champ;
	ajax = new Ajax.Request('listTerms.ajax', 
		{
			method: 'post',
			parameters: $H({'field': champ2}).toQueryString(),
			onSuccess: function(request) {
				optionsb = request.responseText.substring(request.responseText.indexOf("<select>")+8,request.responseText.indexOf("</select>")-1);
				
				var temp = optionsb;
				var tab_optionsb = new Array();
				var j=0;
				
				for(var i=temp.length; i>=0; i--) {												
					tab_optionsb[j] = temp.substring(temp.indexOf("<option value=")+15,temp.indexOf(">")-1);
					temp = temp.substring(temp.indexOf("</option>")+9,temp.length);
					j=j+1;
					i=temp.length;
				}
				
				var liste = $(num + '_' + champ + '-choice');
				
				// on le rajoute dans l'ordre alphabétique dans l'autre select				
				for(var i=0; i < tab_optionsb.length; i++) {
					var idem =false;
					for(j=0 ; j < liste.options.length; j++) {						
						if(liste.options[j].value.toLowerCase()==(tab_optionsb[i].toLowerCase())){
							idem =true;
						}						
						if(liste.options[j].value.toLowerCase() > tab_optionsb[i].toLowerCase()) {
							suivant = liste.options[j];
							break;
						}
					}
					option = Builder.node('option', {value:tab_optionsb[i]}, [tab_optionsb[i]]);
					
					if(idem==false){
						if(liste.options.length > 0 && j!= liste.options.length) {
							liste.insertBefore(option,suivant);
						} else {
							liste.appendChild(option);
						}
					}
				}
				
				
			}//,
		}
	);	
	}

	
	if(document.getElementById('illu').checked){
	champ2 = "fi"+champ;
	ajax = new Ajax.Request('listTerms.ajax', 
		{
			method: 'post',
			parameters: $H({'field': champ2}).toQueryString(),
			onSuccess: function(request) {
				optionsb = request.responseText.substring(request.responseText.indexOf("<select>")+8,request.responseText.indexOf("</select>")-1);
				
				var temp = optionsb;
				var tab_optionsb = new Array();
				var j=0;
				
				for(var i=temp.length; i>=0; i--) {												
					tab_optionsb[j] = temp.substring(temp.indexOf("<option value=")+15,temp.indexOf(">")-1);
					temp = temp.substring(temp.indexOf("</option>")+9,temp.length);
					j=j+1;
					i=temp.length;
				}
				
				var liste = $(num + '_' + champ + '-choice');
				
				// on le rajoute dans l'ordre alphabétique dans l'autre select				
				for(var i=0; i < tab_optionsb.length; i++) {
					var idem =false;
					for(j=0 ; j < liste.options.length; j++) {						
						if(liste.options[j].value.toLowerCase()==(tab_optionsb[i].toLowerCase())){
							idem =true;
						}						
						if(liste.options[j].value.toLowerCase() > tab_optionsb[i].toLowerCase()) {
							suivant = liste.options[j];
							break;
						}
					}
					option = Builder.node('option', {value:tab_optionsb[i]}, [tab_optionsb[i]]);
					
					if(idem==false){
						if(liste.options.length > 0 && j!= liste.options.length) {
							liste.insertBefore(option,suivant);
						} else {
							liste.appendChild(option);
						}
					}
				}
				
				
			}//,
		}
	);	
	}	
		
	}



// ajout une liste à sélection
function addSelection (champ, intitule) {
	tbody = $('ajout');
	tr = Builder.node('tr', {id: n+'_tr'}, [
			addBoolean(champ),
			Builder.node('td',[intitule]),
			Builder.node('td', [
				Builder.node('select', {
					name: n + '_' + champ + '-choice', 
					id:n + '_' + champ + '-choice', 
					style: 'width: 100%; max-width: 100%;',
					size: 5,
					multiple: 'true',
					onclick: 'swap('+n+',\''+champ+'\',0)'
				})
			]),
			Builder.node('td', [
				Builder.node('select', {
					name: n + '_' + champ + '-chosen', 
					id:n + '_' + champ + '-chosen', 
					style: 'width: 100%; max-width: 100%;',
					size: 5,
					multiple: 'true',
					className: 'recherche_liste',
					onclick: 'swap('+n+',\''+champ+'\',1)'
				})				
			]),
			Builder.node('td', [
				Builder.node('input', {className: 'bouton', type: 'button', value: '-', onclick: 'removeElement('+n+')'})
			])
		]);
  	tbody.appendChild(tr);
  	var num = n; /* afin d'éviter le décalage entre la variable global n et le temps de réponse d'ajax */
	
	ajax = new Ajax.Request('listTerms.ajax?'+new Date(), 
		{
			method: 'post',
			parameters: $H({'field': champ}).toQueryString(),
			onSuccess: function(request) {
				//alert("deb succes");
				optionsb = request.responseText.substring(request.responseText.indexOf("<select>")+8,request.responseText.indexOf("</select>")-1);
	
				var temp = optionsb;
				var tab_optionsb = new Array();
				var j=0;
				
				for(var i=temp.length; i>=0; i--) {												
					tab_optionsb[j] = temp.substring(temp.indexOf("<option value=")+15,temp.indexOf(">")-1);
					temp = temp.substring(temp.indexOf("</option>")+9,temp.length);
					j=j+1;
					i=temp.length;
				}
				
				var liste = $(num + '_' + champ + '-choice');
				
				// on le rajoute dans l'ordre alphabétique dans l'autre select				
				for(var i=0; i < tab_optionsb.length; i++) {
					var idem =false;
					for(j=0 ; j < liste.options.length; j++) {						
						if(liste.options[j].value.toLowerCase()==(tab_optionsb[i].toLowerCase())){
							idem =true;
						}						
						if(liste.options[j].value.toLowerCase() > tab_optionsb[i].toLowerCase()) {
							suivant = liste.options[j];
							break;
						}
					}
					option = Builder.node('option', {value:tab_optionsb[i]}, [tab_optionsb[i]]);
					
					if(idem==false){
						if(liste.options.length > 0 && j!= liste.options.length) {
							liste.insertBefore(option,suivant);
						} else {
							liste.appendChild(option);
						}
					}
				}
	}});
	
}

// Ajout des opérateurs booléens
function addBoolean(champ) {
	
	var td = Builder.node('td',[
				Builder.node('select', {
					name: n + '_' + champ + '-bool', 
					id:n + '_' + champ + '-bool'
				}, [
					Builder.node('option', {value: 'SAUF'},['SAUF']),
					Builder.node('option', {value: 'ET'},['ET']),
					Builder.node('option', {value: 'OU', selected: 'selected'},['OU'])
				])
			]);
	return td;
}

// fonction qui permet d'ajouter et enlever un élément d'une liste à une autre
function swap(num, champ, op) {
	var selectChoice = $(num + '_' + champ + '-choice');
	var selectChosen = $(num + '_' + champ + '-chosen');
	if(op === 0) {
		selectPlus = selectChosen;
		selectMoins = selectChoice;
	} else {
		selectPlus = selectChoice;
		selectMoins = selectChosen;
	}
	// pour chaque item selectionné
	for(var i=selectMoins.options.length-1; i>=0; i--) {
		if (selectMoins.options[i].selected) {		
		// on le rajoute dans l'ordre alphabétique dans l'autre select
			for(j=0 ; j < selectPlus.options.length; j++) {
				if(selectPlus.options[j].value.toLowerCase() > selectMoins.options[i].value.toLowerCase()) {
					suivant = selectPlus.options[j];
					break;
				}
			}
			option = Builder.node('option', {value:selectMoins.options[i].value}, [selectMoins.options[i].value]);
			if(selectPlus.options.length > 0 && j!= selectPlus.options.length) {
				selectPlus.insertBefore(option,suivant);
			} else {
				selectPlus.appendChild(option);
			}
			// on l'enleve dans le premier select
			selectMoins.removeChild(selectMoins.options[i]);
		}
	}
}

// Supprime une option
function delOption(num, champ) {
	var select = $(num + '_' + champ + '-chosen');
	for(var i=select.options.length-1; i>=0; i--) {
		if (select.options[i].selected) {	
			select.removeChild(select.options[i]);
			break;
		}
	}
}

// Ajout d'une option
function addOption(select, text) {
	var suivant = null;
	var optionExist = false;
	for(var i=0; i<select.options.length; i++) {
		if(select.options[i].value == text) {
			optionExist = true;
			break;
		} else if(select.options[i].value.toLowerCase() > text.toLowerCase()) {
			suivant = select.options[i];
			break;
		}
	}
	if(!optionExist) {
		option = Builder.node('option', {value: text, selected: 'selected'},[text]);
		if(suivant !== null) {
			select.insertBefore(option,suivant);
		} else {
			select.appendChild(option);
		}
	}
}

// Supprime un element
function removeElement(n) {
	var tobdy = $('ajout');
	var tr = $(n+ '_tr');
	tbody.removeChild(tr); 
	if($('ajout').childNodes.length < 2) {
		$('valid').hide();
	}
}

// Validation sommaire
function validForm(event) {
	// vérification qu'il existe au moins un champ input rempli ou un chosen avec un élément
	var ok = false;
	var inputs = $$('.recherche_champ');
	var selects = $$('.recherche_liste');
	if($("pleintexte").value !== '') {ok = true;}
	if(!ok) {
		for(k=0; k<inputs.length; k++) {
			if(inputs[k].value !== '') {
				ok = true;
				break;
			}
		}
	}
	if(!ok) {
		for(k=0; k<selects.length; k++) {
			if(selects[k].options.length > 0) {
				ok = true;
				break;
			}
		}
	}
	
	if(ok) {
		// sélectionne tous les éléments des ***-chosen
		for(k=0; k<selects.length; k++) {
			for(l=0; l< selects[k].options.length; l++){
				selects[k].options[l].selected=true;
			}
		}
	} else {
		$('flash').update("Vous devez remplir au moins un champ !").show();
		Event.stop(event);
	}
	
}

function setParams(){

	var cache = document.getElementById('typeTemp');
	var requet = document.getElementById('pleintexte');
	
	if(document.getElementById('notice').checked){
		cache.value += "notices ";
	}
	if(document.getElementById('illu').checked){
		cache.value += "illus ";
	}
	if(document.getElementById('breve').checked){
		cache.value += "breves ";
	}
	
	if(document.getElementById('OR').checked){
		bool = "OR";
	}else{
		bool = "AND";
	}
	
	reg1 = new RegExp(/^[0-9]*_.*/);
	reg2 = new RegExp(/.*-bool$/);
	reg3 = new RegExp(/.*-chosen$/);
	reg4 = new RegExp(/.*-choice$/);
	var chaineParam = "";
	
	for(i=0;i<document.zone_champ.length;i++){
		name = document.zone_champ.elements[i].name;
		if(reg1.test(name) && reg3.test(name)){ //Ne laisse passer que le "chosen"
		
			for(j=0;j<document.zone_champ.elements[i].length;j++){
				chaineParam += "&"+name+"2="+document.zone_champ.elements[i].options[j].value;
			}
		}
		
		if(reg1.test(name) && reg2.test(name)){ //Ne laisse passer que le "bool"
			for(j=0;j<document.zone_champ.elements[i].length;j++){
				if(document.zone_champ.elements[i].options[j].selected){
					chaineParam += "&"+name+"2="+document.zone_champ.elements[i].options[j].value;
				}
			}
			
		}
		
		if(reg1.test(name) && reg4.test(name)){ //Ne laisse passer que le "choice"
			chaineParam += "&"+name+"2="+document.zone_champ.elements[i].value;
		}
	}

	formulaire = document.getElementById('zone_champ'); 
	formulaire.action = 'resultat?pleintexte='+requet.value+'&type='+cache.value+'&booleen='+bool+chaineParam;
	return true ;
}

// initialisation
function initEventListener() {
	Event.observe('add_button', 'click', addField);
	Event.observe('valid', 'click', validForm);
}

var n=0;
Event.observe(window,'load', initEventListener);