function initProgress() {  
	if ($('progressMsg'))
		Effect.Appear('progressMsg');
}

function resetProgress() {
	if ($('progressMsg'))
		Effect.Fade('progressMsg'); 
}     


function turnAutocompleteOff()
{
	try {
		var inputs = document.getElementsByTagName('INPUT');
		for (var i = 0; i < inputs.length; i++) {
			inputs[i].setAttribute('autocomplete', 'off');
		}
	} catch (e) {}
}

var i=0;



function invoke(form, event, container) {
	initProgress();  	
	event.disabled=true;        
	var params = Form.serialize(form);
	if (event != null) params = event.name + '=&' + params;
	new Ajax.Updater(container, form.action, 
		{method:'post', 
		evalScripts:true,
		postBody:params, 
		onComplete:function(){resetProgress();event.disabled=false;},
		on404:function(){alert('erreur 404');}
		});
}

function chargeMenu( url, idMenuSource, idMenuDest, defaultOptions, forceSelection) {	
	chargeMenuAvecParam( url, idMenuSource, idMenuSource, idMenuDest, defaultOptions, forceSelection);
}

function isArray(obj) {
	   if (obj.constructor.toString().indexOf("Array") == -1)
	      return false;
	   else
	      return true;
}

function chargeMenuAvecParam( url, paramName, idMenuSource, idMenuDest, defaultOptions, forceSelection) {
	var dest = document.getElementById(idMenuDest);
	dest.options.length = 0;
	
	var inputSource = document.getElementById(idMenuSource);
	var value;
	
	if (inputSource.type == "checkbox") {
		value = inputSource.checked;
	} else {
		value = inputSource.value;
	}
	
	$.post(contextPath + url + "&" + paramName+'='+value,
		function(data){
			var options = eval(data);
			if(defaultOptions && !isArray(defaultOptions)) {
				defaultOptions =  defaultOptions.replace('[', '').replace(']', '').split(",");
			}
			if(!isArray(options)){ options = []; }
			if(!forceSelection) {
				dest.options[0]=new Option('-', '');
			}
			
			var newOption = null;
			for(var i = 0; i < options.length; i++) {
				newOption = new Option(options[i].label, options[i].value);
				newOption.selected = (options[i].selected || (jQuery.inArray(options[i].value, defaultOptions) != -1));
				dest.options[dest.options.length] = newOption;
			}
			
		    if (newOption === null) {
		    	dest.options[dest.options.length] = new Option('-', '');
		        //dest.disabled = true;
		    }		  
		    
		   //recopy valeur pour select en readOnly 
		   if(document.getElementById('readonly_select_'+document.getElementById(idMenuDest).name) && dest.selectedIndex>-1){			 
			   document.getElementById('readonly_select_'+document.getElementById(idMenuDest).name).innerHTML = dest.options[dest.selectedIndex].text;
		   }							
		}
	);
}


/** autocomplete un champ texte a partir d'un menu deroulant si 
une seule correspondance est trouvee */
function autoComplete (field, select,nomChampId) {
	/* Init champ id si lib est vide */
	var champId = document.getElementById(nomChampId);
	if(field.value==''){
		champId.value='';
	}
	
	var found = 0;
	var foundIndex = 0;
	for (var i = 0; i < select.options.length; i++) {
		if (select.options[i].text.toUpperCase().indexOf(field.value.toUpperCase()) == 0) {
			found++;
			foundIndex=i;
		}
	}
	/*  Valeur trouvee -> recopie */
	if (found==1) { 
		field.value=select.options[foundIndex].text; 
		champId.value=select.options[foundIndex].value;
	}
	/*  Valeur non trouvee -> annule caractere tappe */
	else if (found==0) {
		field.value=field.value.substring(0,field.value.length-1); 
	}	
}


function addNewLigne(idTable,nomList,pk,tableDescription,nbLignes) {
	
	//Incrément index max du tableau
	nbLignes = nbLignes + 1;

	//Table
	var table = $(idTable);
	if(table==null){
		alert('Ajout impossible');
		return;	
	}
	
	// Create a new line.
	var newRow = table.insertRow(table.rows.length);	
	newRow.className='odd';
	var index  = nbLignes-1;
	var newCell;	

	for (var i = tableDescription.length-1; i > -1 ; i--) { 										
	    newCell = newRow.insertCell('');								   
	    if(	tableDescription[i][0]!='empty'){	    	
	    	input = creerChamp(tableDescription[i][3],nomList,tableDescription[i][1],index,tableDescription[i][2],tableDescription[i][0],tableDescription[i][4],tableDescription[i][5]);  
	   		newCell.appendChild(input);
	    }
	}		
	
	//Champ cache id					
	var hidden = creerChampCache(nomList,pk,index);
	table.parentNode.appendChild(hidden);			
	
	return nbLignes;
}

function creerChamp(type,nomList,maxLength, index, size, nomChamp,rows,cols){		
	var input;
	if(type=='TEXT'){
		input = document.createElement('INPUT');
		input.setAttribute('type', "text");		
		input.setAttribute('value', "");
		input.setAttribute('size', size);		
		if(maxLength!=''){
			input.setAttribute('maxLength', maxLength);
		}			
				
	}else if(type=='SELECT'){
		input = document.createElement('SELECT');			
		if(size!=''){						
			input.setAttribute('size', size);
		}		
		
		var modele='';
		for (var i=0;i<listes.length;i++){  
			if(listes[i][1]==nomChamp){					
				modele=listes[i][2];
				break;
			} 
        }        
		
		if(modele!=''){
			for (var i=0;i<modele.length;i++){               
	            input.options[i+1] = new Option(modele[i][1],modele[i][0]);   
	        }
        }
	}else if(type=='CHECKBOX'){
		input = document.createElement('INPUT');
		input.setAttribute('type', "checkbox");			
	}
	else if(type=='TEXTAREA'){
		input = document.createElement('TEXTAREA');
		input.setAttribute('rows',rows);
		input.setAttribute('cols',cols);		
	}
	input.setAttribute('name', nomList+'['+index+'].'+nomChamp);
	return input;
}			

function creerChampCache(nomList,property, index) {
	var hidden = document.createElement("INPUT");
	hidden.setAttribute('type', 'hidden');		
	hidden.setAttribute('name', nomList+'['+index+'].'+property);							
	return hidden;
}

function initSelectAjax(element){	
	if(document.getElementById(element)) {
		document.getElementById(element).style.display='none';
		document.getElementById(element+'Titre').style.display='none';	
		document.getElementById(element).selectedIndex=-1;	
	}
}


function getKeyCode(e) {
	var code;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;	
	return code;
}

function bloqueToucheEntree(e){
	return (getKeyCode(e)!=13) ? true : false;	
}

//ouverture d'un popup
function popup(url, width, height){
	left = (screen.availWidth-width)/2;
	topp = (screen.availHeight-height)/2;
	windowprops = "location=no,scrollbars=yes,menubars=no,toolbars=no,resizable=yes,status=yes" +
		",left=" + left + ",top=" + topp + ",width=" + width + ",height=" + height;

	opened = window.open(url,"popup",windowprops);
	opened.focus();		
	return false;
}

//ouverture d'un popup documents
function popupDocuments(url, width, height){
	left = (screen.availWidth-width)/2;
	topp = (screen.availHeight-height)/2;
	windowprops = "location=no,scrollbars=yes,menubars=no,toolbars=no,resizable=yes,status=yes" +
		",left=" + left + ",top=" + topp + ",width=" + width + ",height=" + height;

	opened = window.open(url,"popupdocuments",windowprops);
	opened.focus();		
	return false; 
}

//Gestion du menu
function afficherRubrique(id) {	
	$('#menuHorizontal dd').css("display", 'none');	
	if(id){		
		$("#"+id).css("display", 'block');		
	}
}


function virgule(champ, e) {
	if(getKeyCode(e)==110 || getKeyCode(e)==190) {
		champ.value = champ.value+",";
		return false;
	}
	return true;
}

/** coche toutes les cases de l'element donné */
function selectAll(htmlId) {
	$$('#'+htmlId+' input').each(function(elem) {elem.checked=true});
	return false;
}

/** verifie qu'au moins une ligne est selectionnée
 * efafce toutes les lignes cochées de l'écran
 */
function checkSelection(htmlId, submitId) {
	auMoinsUnCheck = false;
	$$('#'+htmlId+' input[type="checkbox"]').each(function(elem) {
		if(elem.checked){
			auMoinsUnCheck = true;
		}
	});
	return auMoinsUnCheck;

}

/** verifie qu'au moins une ligne en radio est selectionnée
 */
function checkRadioSelection(htmlId) {
	auMoinsUnCheck = false;
	$$('#'+htmlId+' input[type="radio"]').each(function(elem) {
		if(elem.checked){
			auMoinsUnCheck = true;
		}
	});
	return auMoinsUnCheck;

}

 function checkSelectionAuMoinsUn(htmlId, maClass) {
		var auMoinsUnCheck = false;
		$$('#'+htmlId+' input.'+maClass).each(function(elem) {
			if(elem.checked){
				auMoinsUnCheck = true;
				return;
			}
		});
		return auMoinsUnCheck;
	}

 
//Même traitement que checkSelection en comptant en plus le nb de cases cochées
//retourn le nombre de ligne sélectionnées
function checkSelectionCpt(htmlId) {
	//auMoinsUnCheck = false;
	var nb=0;
	$$('#'+htmlId+' input[type="checkbox"]').each(function(elem) {
		if(elem.checked){
			nb++;
		}
	});
	return nb;
}

//Même traitement que checkSelection en comptant en plus le nb de cases cochées mais ne prenant que les élément ayant un .class donné
//retourn le nombre de ligne sélectionnées
function checkSelectionCptAvecClass(htmlId,maClass) {
	var nb=0;
	$$('#'+htmlId+' input[type="checkbox"].'+maClass).each(function(elem) {
		if(elem.checked){
			nb++;
		}
	});
	return nb;
}

function hierarchyBeanReset(){
	if($('hierarchyLib').value==''){
		$('hierarchy').value='';
	}
}

function confirmDelete(){
	return confirm(confirmDeleteMessage);
}

function confirmAction(){
	return confirm(confirmActionMessage);
}

function reloadDiv(divId,url){
	var o_options = new Object();
	o_options = {method: 'get', evalScripts: true};	
	var requete = new Ajax.Updater(divId,url,o_options);
}

//Affiche aprés la sélection d'une action les champs complémentaires nécessaire à l'application
//de l'action
function displayComplementaryFields(action){

	if(action=='addRetest'){
		if ($('intervRetestDateDebutPrevField')){
			$('intervRetestDateDebutPrevField').style.display= 'inline';
		}
	}else{
		if ($('intervRetestDateDebutPrevField')){
			$('intervRetestDateDebutPrevField').style.display= 'none';
		}
	}
	
	if(action=='postponeActivationDate'){
		$('activationDateField').show();
		$('newCriticiteField').hide();
	} else if(action=='updateCriticite') {
		$('newCriticiteField').show();
		$('activationDateField').hide();
	} else{
		if ($('activationDateField')){
			$('activationDateField').hide();
		}
		if ($('newCriticiteField')){
			$('newCriticiteField').hide();
		}
	}
}

//Active ou désactive applyAction selon le type d'action et le nb de ligne cochées
function enableApplyAction(action){
	if(action=='applyProtocole'){
		var nbLignes = checkSelectionCptAvecClass('applyActionForm', 'selectable');
		checkApplyProtocole('searchProductResult',nbLignes); //ne pas changer cet appel sauf éventuellement passser le nbLignes
	}else{
		var auMoinsUn = checkSelectionAuMoinsUn('applyActionForm', 'selectable');
		if(action!=''&& auMoinsUn){
			if(action!='linkToPioche' ||  checkSelectionCptAvecClass('applyActionForm', 'selectable')==1)
			$('applyAction').disabled=false;
		}
		else{
			$('applyAction').disabled=true;
		}
		displayComplementaryFields(action);
	}
}

//Double submit bloqué   
function doubleSubmit() {	
	if(deja==true){
		alert(doubleSubmitLibelle);
		return true;
	}
	deja=true;
	return false;		
}

function initAjaxMessages(){
	document.getElementById('messageDeleteAjax').style.display='none';
	document.getElementById('messageSuccesAjax').style.display='none';
	document.getElementById('messageErreurAjax').style.display='none';
}