/* $VERSION: input.js 3.1.032.1.2011.02.09.09.11	 */
/*
* Gestion des inputs, label, select, textarea
*/
var __message = "";
var currentFieldset;
var traiteattente = function (){};

function fieldset_save() {
	this.elements = new Array();
	var test = new Array();
	for (var tagName in Form.Element.Serializers) {
      var tagElements = this.getElementsByTagName(tagName);
      for (var j = 0; j < tagElements.length; j++){
		tagElements[j].save();
      	tagElements[j].fieldset = this;
      	if (tagElements[j].type 
      		&& (tagElements[j].type == 'button' || tagElements[j].type == 'reset' || tagElements[j].type == 'submit'))
      		continue;
      	if (test[tagElements[j].name]) continue;
      	test[tagElements[j].name] = 1;
        this.elements.push(tagElements[j]);
      }
    }
}

function fieldset_reset() {
	for (var i = 0; i < this.elements.length; i++) {
		this.elements[i].reset();
	}
}

function fieldset_serialise() {
	var values = {};
	var elements = '';
	for (var i = 0; i < this.elements.length; i++) {
		values[this.elements[i].name] = this.elements[i].getValue();
		elements += (this.elements[i].name + ' ');
	}
	values['SENDDATA'] = elements;
	
	return $H(values).toQueryString();
}

function fieldset_isOK() 
{
	for (var i = 0; i < this.elements.length; i++) 
	{
		if (this.elements[i].isOK() == false)
			return false;
	}
	
	return true;
}

function input_init(input) {
	if (input.type != 'reset' && input.type != 'submit' && input.type != 'button') return;
	input.confirm = true;
	input.obligatoire = false;
	if (Element.hasClassName(input, 'bouton'))
	{
		switch (input.value.toLowerCase().slice()){
			case "enregistrer" :{
				input.confirm = true;
				input.obligatoire = true;
				break;
			}
			case "valider" :{
				input.confirm = true;
				input.obligatoire = true;
				break;
			}
			case "ajouter" :{
				input.confirm = false;
				input.obligatoire = false;
				break;
			}
			case "rechercher" :{
				input.confirm = false;
				input.obligatoire = false;
				break;
			}
			case "annuler" :{
				input.confirm = false;
				input.obligatoire = false;
				break;
			}
			case "supprimer" :{
				input.confirm = true;
				input.obligatoire = false;
				break;
			}
			case "actualiser" :{
				input.confirm = false;
				input.obligatoire = false;
				break;
			}
		}
	}
	if (Element.hasClassName(input, 'enregistrer')) {
		input.confirm = true;
		input.obligatoire = true;
	}
	if (Element.hasClassName(input, 'valider')) {
		input.confirm = true;
		input.obligatoire = true;
	}
	if (Element.hasClassName(input, 'ajouter')) {
		input.confirm = false;
		input.obligatoire = false;
	}
	if (Element.hasClassName(input, 'rechercher')) {
		input.confirm = false;
		input.obligatoire = false;
	}
	if (Element.hasClassName(input, 'annuler')) {
		input.confirm = false;
		input.obligatoire = false;
	}
	if (Element.hasClassName(input, 'supprimer')) {
		input.confirm = true;
		input.obligatoire = false;
	}
	if (Element.hasClassName(input, 'actualiser')) {
		input.confirm = false;
		input.obligatoire = false;
	}
	
	if (input.getAttribute("askConfirm") == "YES")
		input.confirm = true;

	if (input.getAttribute("askConfirm") == "NO")
		input.confirm = false;

	if (input.getAttribute("testObligatoire") == "YES")
		input.obligatoire = true;	

	if (input.getAttribute("testObligatoire") == "NO")
		input.obligatoire = false;	
}

function input_save() {
	if (this.type == 'checkbox' || this.type == 'radio')
		this.resetValue = this.checked;	
	else
		this.resetValue = this.value;
}

function input_getForm() {
	return this.fieldset;	
}

function input_getValue()
{
	if (this.hasSqlValue)
		return this.sqlValue;	
	else
		switch (this.type)
		{
			case "radio":
				radios = document.getElementsByName(this.name);
				for (i = 0; i < radios.length; i++)
				{
					if (radios[i].checked)
						return (radios[i].value);
				}
				break;
			case "checkbox":
					return (this.checked) ?  this.value : this.uncheckedValue;				
				break;
			default:
				return this.value;
		}
}

function input_reset()
{
	if (this.type == 'checkbox' || this.type == 'radio')
		this.checked = this.resetValue;	
	else	
		this.value = this.resetValue;
}

function labelonclick(lbl)
{
	var input_name = lbl.getAttribute('htmlfor')|| lbl.getAttribute('for');
	if (input_name){
		if (input = document.getElementsByName(input_name)[0])
		{
			try
			{
				input.focus();
				if (input.type == 'checkbox')
				{
					input.checked = !input.checked;
				}
			} catch (e){};
		}
	}
}

function inputonfocus(zone){
	try	{zone.localvalue = zone.value;} catch(e){};
	window.zonefocus = zone;
	if (zone.tagName.toUpperCase() != 'SELECT')
		Element.addClassName(zone, 'focus'); 
	if (label = zone.label)	{
	    if (!Element.hasClassName(label, 'erreur'))
			Element.addClassName(label, 'focus'); 
	}    
}

function inputonchange(zone)
{
	Element.removeClassName(zone, 'erreur')
	if (zone.label)
		Element.removeClassName(zone.label, 'erreur')
	if (zone.valueAssistant == zone.value) return;
	if (zone.methode == '') return;
	
	if (zone.value == '') 
	{
		zone.sqlValue = ''
		
		return;
	}
	zone.valOk = false;
	
	if (!zone.win)
	{
		zone.win = new winassistant(zone);
	}
	else
	{
		if(zone.win.multi == 1 && zone.win.input.value.indexOf(',',0) != -1)
		{
			zone.win.input.forceaffiche = true;
		}
		else
		{
			zone.sqlValue = '';
		}
	}

	zone.win.populate();
	
	if(zone.win.multi == 1 && zone.win.input.value.indexOf(',',0) != -1)
	{
		zone.win.dosearch();
	}
}

function inputonblur(zone) {	
	Element.removeClassName(zone, 'focus'); 
        
	try{zone.format();} catch(e){};
	if (label = zone.label)
		Element.removeClassName(label, 'focus');
	try	{
		if (zone.localvalue != zone.value)
		{
			change = new Function(zone.name + '_onchange()');
			try {change();} catch(e){};
		}
		zone.localvalue = zone.value;
	} catch(e){};
}

function inputonkeypress(e, zone)
{
	if (!zone.expregpress) return;
	
    var keycode = (e.which || e.keyCode);
    if ((e.charCode == 0) || (keycode == 0) || (keycode == 8) || (keycode == 9) || (keycode == 13))
    	return true;
    	
	var expreg= new RegExp(zone.expregpress);
    if (expreg.test(String.fromCharCode(keycode)))
    	return true;
  		
	Event.stop(e);
    return false;
}

function inputonclick(input)
{
	traiteattente = function (){};
	Dialog.setMessage("Voulez vous " + input.value.toLowerCase() + "?");
	try {
		beforeonclick = new Function('return '+ input.name + '_beforeonclick();');
		if (!beforeonclick())
		{
			Dialog.alert(Dialog.message, {windowParameters: {width:300}, okLabel: "OK"});
			return;
		}
	}
	catch(e){};
	
	if (input.type != 'reset' && input.type != 'submit' && input.type != 'button') return;
	
	if (input.type == 'reset')	{
		input.fieldset.reset();
		return;
	}
	try
	{
		inputonblur(window.zonefocus);
	}
	catch(e){};
	
	if (!input.fieldset.isOK())
	{
		traitenattente = function (){inputonclick(input)}; 
		return;
	}
	if (input.obligatoire) {
		var parent = input.getForm();
		for (var i = 0; zone = parent.elements[i]; i++) {
			if (zone.isObligatoire && zone.getValue() == '') {
				try{zone.focus();} catch(e) {};
				try{
					if (zone && !Element.visible(zone)) continue;
					if (zone.parentNode && !Element.visible(zone.parentNode)) continue;
				} catch (e){};
				try
				{
					Element.addClassName(zone, 'erreur'); 
					Element.addClassName(zone.label, 'erreur'); 
				} catch(e){};
				if (zone.MessageObligatoire)
					alerte(zone.MessageObligatoire);
				else if (zone.label)
				{
					label = zone.label.innerHTML.replace(/ : /, '');
					alerte(label+ ' est vide');
				}
				else
					alerte(zone.name);
				return;						
			}
		}
	}
	currentFieldset = input.fieldset;
	currentInput = input;
	if (input.getAttribute("methode")){	
		input = currentInput;
		if (input.confirm)
		{
			Dialog.confirm(Dialog.message, 
              	{windowParameters: {width:300}, okLabel: input.value||'OK', cancelLabel: "Annuler",
               	buttonClass: "myButtonClass",
               id: "myDialogId",
               ok:function(win) {return input_validate();}
              });
		}
		else
			return input_validate();
	}
	else{
		try {
			variable =  input.name + '_afteronclick();';
			afteronclick = new Function(variable);
			if (!afteronclick())
				return;
		}catch(e){};

	}
}

function input_validate()
{
	input = currentInput;
	param = currentFieldset.serialise();
	Dialog.setMessage('');
	if (input.getAttribute("ajax") == 'O') {
		Dialog.info("Traitement en cours", 
             {windowParameters: {width:300}, okLabel: "close", showProgress: true });
			var pars = 'ACTION='+input.getAttribute("methode")+'&PAGE_AJAX=Y&PHPSESSID=' + getValue("PHPSESSID") + '&'+ param;
	
	    var url = document.location.href;
   		var pos = url.indexOf('?', 0);
    	if (pos > 0)
    	{
    		url = url.substring( 0, pos)
		}
		var myAjax = new Ajax.Request(
			url, 
			{method: 'post', parameters: pars, onComplete: reportOk, onFailure: reportError});
	}
	else {
		checkModified = false;
		Dialog.info("Traitement en cours", 
             {windowParameters: {width:300}, okLabel: "close", showProgress: true });		
			$("ACTION").value = input.getAttribute("methode");
			$("ENVOI_PARAMETRE").value =param;
			$("ENVOI_PARAMETRE").form.submit();
	}
}



function reportError(request) {
	Dialog.alert("Problème lors du traitement", 
             {windowParameters: {width:300}, okLabel: "OK"});
	try {
		variable =  input.name + '_erroronclick();';
		beforeonclick = new Function(variable);
		if (!beforeonclick())
			return;
	}catch(e){};
}

function alerte(message)
{
	/* gestion du focus */
	Dialog.alert(message, 
             {windowParameters: {width:300}, okLabel: "OK"});
}


function reportOk(request) {
	var response = request.responseText;
	try{response.evalScripts();} catch(e){};
	if (Dialog.type == 1)
		currentFieldset.save();
	try {
		variable =  input.name + '_afteronclick();';
		beforeonclick = new Function(variable);
		if (!beforeonclick())
			return;
	}catch(e){};

}

function setObligatoire(objet, message) {
	if (!(objet = getObj(objet))) return;
	objet.isObligatoire = true;
	if (message)
  		objet.MessageObligatoire = message;
}

function setDate(objet) {
	if (!(objet = getObj(objet))) return;
	objet.expregpress = "[ 0123456789/.-]";
	objet.format = function(){formatdate(objet)};
}

function setEmail(objet) {
	if ((!(objet = getObj(objet)))) return;
	objet.format = function(){formatemail(objet)};
}

function setNumerique(objet, longueur, message) {
	if (!(objet = getObj(objet))) return;
	objet.expregpress = "[-0123456789.,]";
	if (longueur)
	{
  		objet.format = function(){formatnumerique(objet, longueur)};
	}
}

function setTelephone(objet) {
	if (!(objet = getObj(objet))) return;
	objet.expregpress = "[ 0123456789.:]";
	objet.format = function(){formattelephone(objet)};
}

function setDecimal(objet) {
	if (!(objet = getObj(objet))) return;
	objet.expregpress = "[-0123456789.,]";
	objet.nbDecimal = -1;
	objet.format = function(){formatdecimal(objet)};
}
function setNbDecimal(objet,nb) {
	if (!(objet = getObj(objet))) return;
	objet.nbDecimal = nb;
	objet.expregpress = "[-0123456789.,]";
	objet.format = function(){formatdecimal(objet)};
}
function setUncheckedValue(objet, str) {
	if (!(objet = getObj(objet))) return;
	if (objet.type.toLowerCase() == "checkbox")
		objet.uncheckedValue = str;
}


// Nb de jours dans un mois si annee non bissextille
var nbJMois = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
//Nb de jours dans un mois si annee bissextille
var nbJMoisBis = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// nombre de jours dans le mois
function nbJourMois(mois, annee){
  if ((annee % 4) == 0) {
    if ((annee % 100) == 0 && (annee % 400) != 0)
      return nbJMois[mois];
    return nbJMoisBis[mois];
  }
  else
    return nbJMois[mois];
}

function formatdate(iText){
  var aujourdhui = new Date();
  var jAujourdhui = aujourdhui.getDate();
  var mAujourdhui = aujourdhui.getMonth()+1;
  var aAujourdhui = aujourdhui.getFullYear();
  
  
  iVal = iText.value;
  if (iVal == '.')
	  iVal = jAujourdhui+'/'+mAujourdhui+'/'+aAujourdhui;
  regT = new Array(
        /^([1-9]|0[1-9]|[1-3]0|[1-3]1|1[0-9]|2[0-9])$/,
        /^([1-3][0-1])\D?([1-9]|0[1-9]|1[0-2])$/,
        /^([1-9]|0[1-9]|[1-3]0|[1-3]1|[1-2][0-9])\D?([1-9]|0[1-9]|1[0-2])$/,
        /^(0[1-9]|[1-3]0|[1-3]1|[1-2][0-9])\D?(0[1-9]|1[0-2])\D?(0|[1-9]|\d{2}|\d{3}|\d{4})$/,
        /^(0[1-9]|[1-3]0|[1-3]1|[1-2][0-9])\D?([1-9]|0[1-9]|1[0-2])\D?(0|[1-9]|\d{2}|\d{3}|\d{4})$/,
        /^([1-9]|0[1-9]|[1-3]0|[1-3]1|[1-2][0-9])\D?([1-9]|0[1-9]|1[0-2])\D?(0|[1-9]|\d{2}|\d{3}|\d{4})$/
        );

  nbJour = nbJourMois(mAujourdhui-1, aAujourdhui);
  
  if(iVal)  {
	numExp = 0;
	while (numExp < regT.length) {
		isReg=false;
		for(i=numExp; i<regT.length; i++)
		   if(isReg = regT[i].test(iVal) )		   {
		     regT[i].exec(iVal);
		     break;
		   }   
		if(isReg) {
		  var d = RegExp.$1;
		  var m = RegExp.$2;
		  var y = RegExp.$3;
		  if(d.length==1) d = '0'+d;
		  if(m.length==0) m = ''+mAujourdhui;
		  if(m.length==1) m = '0'+m;
		  if(y.length==0) y = ''+aAujourdhui;
		  if(y.length==1) y = '200'+y;
		  if(y.length==2) y = ( y < 50 ) ? '20'+y : '19'+y;
		  if(y.length==3) y = ( y < 500) ? '2'+y : '1'+y;
		  iText.value = d+'/'+m+'/'+y;
		  reg = /^(0?[1-9]|[1-3][0-9])\D?(0?[1-9]|1[0-2])\D?(\d{4})$/;
		  reg.exec(iText.value);
		  if( parseInt(RegExp.$1) > nbJourMois((RegExp.$2)-1,RegExp.$3) )
			isReg = false;
		  else
			break;
		}
		numExp = i+1;	 
	}
	if (!isReg) iText.value="";
  }
}

/*---------------------------------------------*/
/*  renvoie la valeur decimal de la zone     */
/*---------------------------------------------*/

function formatdecimal(zone)
{
	if (!zone || !zone.value) return;
	var format_nb_decimal = 2;
	var format_sep_dec = ",";
	var format_sep_millier = " ";

	var sortie= "";
	iVal = zone.value;
	var taille=iVal.length;
	for (var i = 0 ; i < taille ; i++)
	{
		var car = iVal.substr(i, 1);
		if (car != ' ')
		if (car != ',')
		sortie += car;
	else
		sortie += '.';
	}
	sortie = ""+parseFloat(sortie);
	if (isNaN(sortie))
	{
		zone.value ='';
		return;
	}
	if ((format_sep_dec!=".")&&((pos=sortie.indexOf(".", 0)) >0))
	{
		if (zone.nbDecimal > 0)
		{
			sortie = sortie + '0000000000000000';
			partieDecimal = sortie.substr(pos+1,zone.nbDecimal);
		}
		else
			partieDecimal = sortie.substr(pos+1);
		zone.value = sortie.substr(0,pos) + format_sep_dec + partieDecimal;
	}
	else 
	{
		if ((sortie.indexOf(".", 0)<0) && (zone.nbDecimal > 0))
		{
			partieDecimal = "000000000000000000000000";
			partieDecimal =partieDecimal.substr( 1 ,zone.nbDecimal); 
		 	zone.value = sortie + format_sep_dec + partieDecimal;
		}
		else
			zone.value = sortie;
	}
}

function formatemail(zone) {
	var expreg = new RegExp("[a-zA-Z0-9_\\.\\-]{3,}@[a-zA-Z0-9_\\-]{2,}\\.[a-z]{2,4}");
	if (!expreg.test(zone.value))
		zone.value = "";
}

function formatnumerique(input, longueur,message){
	if (input && input.value && input.value.length != longueur)	
		alert(message ? message : "Veuillez saisir un nombre d'une longeur de " + longueur + " chiffres");
}

function formattelephone(iText){
	if (iText.value.length == 10)
		iText.value = iText.value.substr(0,2) + ' ' +iText.value.substr(2, 2) + ' ' + iText.value.substr(4, 2) + ' ' + iText.value.substr(6, 2) + ' ' + iText.value.substr(8, 2);
}


function showassistant(e)
{
	var target = (document.all)? e.srcElement: e.target;
	input = target.input;
	input.forceaffiche = (target.tagName != 'INPUT');
	if(target.tagName == 'INPUT' && target.value.indexOf(',',0) != -1)
	{
		input.forceaffiche = true;
	}
	
	if (!input.win)
		input.win = new winassistant(input);
	input.win.populate();
}

function show_Calendrier()
{
  p_item = arguments[0];
  p_item = p_item.substr(p_item.indexOf('.') + 1)

	win = new wincalendrier( getObj(p_item));
	 
	win.show();
	return; 
}

/*
	Gestion du calendier
*/
function showcalendrier(e)
{
	var target = (document.all)? e.srcElement: e.target;
	
	if (!target.input.win)
	target.input.win = new wincalendrier(target.input);
	target.input.win.show();
}

/* 
*	Parcours les inputs javascripts de la page
*/

function initialise_input()
{
	var acdb = [];
	
	var inputs = document.getElementsByTagName('input');
	for (var i = 0; input = inputs[i]; i++)
	{
		if (!input.methode)
		{
			input.methode = '';
			if (input.getAttribute('methode'))
				input.methode = input.getAttribute('methode');
		}
		// on recherche l'element suivant, pour lui associé une action
		suivant = input;
		while (	suivant = suivant.nextSibling)
		{
			if (suivant.tagName)
			{
				break;
			}
		}

		// recherche des calendriers		
		if ((suivant) && (suivant.tagName == "IMG"))
		{
			if (suivant.src)
			{
				image = '';
				images = suivant.src.split(/\/|\\/);
				if (images.length)
					image = images[images.length -1];
				if (image == "calendrier.gif")
				{
					// on a trouvé un input qui doit être une zone date
					// modifie
					setDate(input.name);
					suivant.input = input;
					input.size=10;
					if (suivant.attachEvent)
						suivant.attachEvent('onclick', showcalendrier);
					if (suivant.addEventListener)
						suivant.addEventListener('click', showcalendrier, true);
					if (suivant.style.cursor)  				
						suivant.style.cursor = 'pointer';
					Element.addClassName(suivant, 'bouton');
					
				}
			}
		}
		if (input.methode == 'assistant')
		{
			input.ischanged = false;
			if ((suivant) && (suivant.tagName == "IMG"))
			{
				if (suivant.src)
				{
					image = '';
					images = suivant.src.split(/\/|\\/);
					if (images.length)
						image = images[images.length -1]; 	
					if (image == "assistant.gif")
					{
						// on a trouvé un input qui doit être une zone assistant
						// modifie
						suivant.input = input;
						if (suivant.attachEvent)
							suivant.attachEvent('onclick', showassistant);
						if (suivant.addEventListener)
							suivant.addEventListener('click', showassistant, true);
						suivant.title = "Choisir";
						Element.addClassName(suivant, 'bouton');					
						suivant.onmouseover = function(){if(this.style) this.style.cursor = 'pointer';};
						suivant.onmouseout = function() {if(this.style) this.style.cursor = '';};
					}
				}
			}
		}
		
		if (input.methode == 'autocomplete')
		{
			var uri = window.location.href;
			if (!acdb[input.action]) 
			{
				acdb[input.action] = new ACDB_Remote(uri);
				acdb[input.action].action = input.action ;
			}	
			input.setAttribute('autocomplete', 'OFF');
			NewAutoComplete(input, acdb[input.action]);			
		}
				
	}
}


function HTTPGet(uri, callback_function, callback_parameter) 
{
	
	var url = document.location.href;
   	var pos = url.indexOf('?', 0);
    if (pos > 0)
    {
    	url = url.substring( 0, pos)
	}
	pars = uri.substring(1);
	
	function reportAssOkPage(request) {
		callback_function(request.responseText, request, callback_parameter)
	}

	var myAjax = new Ajax.Request(
				url, 
				{method: 'post', parameters: pars, onComplete: reportAssOkPage, onFailure: reportErrorPage});
				
}


function reportAssErrorPage(request) {
	alert('Erreur de traitement Interne');
}

function HTTPinto(html, http, node) 
{
	node.innerHTML = html;
}

/*

autocomplete (JavaScript AutoComplete) v1.0

*/

function AbsolutePosition(el) 
{
	var SL = 0, ST = 0;
	var is_div = /^div$/i.test(el.tagName);
	if (is_div && el.scrollLeft)
		SL = el.scrollLeft;
	if (is_div && el.scrollTop)
		ST = el.scrollTop;
	var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
	if (el.offsetParent) 
	{
		var tmp = AbsolutePosition(el.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	
	return r;
}


function NewAutoComplete(input, db) 
{
	if (!input.parentNode)
		input = document.getElementById(input);
	
	var ac = new autocomplete(input, db);
}

/* === autocomplete Class === */
function autocomplete(input, db) 
{
	this.input = input;
	this.input.libelles = this.input.libelles.length > 0 ? this.input.libelles.split(',') : [];
	input.autocomplete = this;
	this.init();
	this.db = db;
}

autocomplete.prototype.toString = function () 
{
	return '[AutoComplete Object]';
}

autocomplete.prototype.init = function() 
{
	var ac = this;
	
	this.focusClassName = 'focus';
	
	this.input.onfocus = function () { ac.onfocus(this) }
	this.input.onkeydown = function (event) { return ac.onkeydown(this, event) }
	this.input.onkeyup = function (event) { ac.onkeyup(this, event) }
	this.input.onblur = function () { ac.onblur(this) }
	this.popup = document.createElement('div');
	this.popup.id = 'autocomplete';
}

autocomplete.prototype.hidePopup = function () 
{
	if (this.selected)
		this.input.value = this.selected.innerHTML;
	if (this.popup.parentNode && this.popup.parentNode.tagName)
		this.popup.parentNode.removeChild(this.popup);
}

autocomplete.prototype.onkeydown = function (input, e) 
{
	if (!e) e = window.event;
	switch (e.keyCode) 
	{
		case 40:
			this.selectDown();
			return false;
		case 38:
			this.selectUp();
			return false;
		default:
			return true;
	}
}

autocomplete.prototype.onmouseover = function(input)
{
	if (this.input.tooltip)
	{
		while (this.popup.hasChildNodes())
			this.popup.removeChild(this.popup.childNodes[0]);
		if (!this.popup.parentNode || !this.popup.parentNode.tagName)
			document.getElementsByTagName('body')[0].appendChild(this.popup);

		var pos = AbsolutePosition(this.input);
		this.popup.style.top = (pos.y + this.input.offsetHeight) + 'px';
		this.popup.style.left = pos.x + 'px';
		this.popup.style.width = (this.input.offsetWidth - 4) + 'px';
		
		var div = document.createElement('div');
		div.appendChild(document.createTextNode(this.input.tooltip));
		this.popup.appendChild(div);
	}
}

autocomplete.prototype.onmouseout = function(input)
{
	this.hidePopup();
}

autocomplete.prototype.onfocus = function(input)
{
    this.oldFocusClassName = this.input.className;
    this.input.className = this.focusClassName;
    this.selected = false;
}


autocomplete.prototype.onkeyup = function (input, e) 
{
		if (!e) e = window.event;
		switch (e.keyCode) 
		{
			case 38: // up arrow
			case 40: // down arrow
			case 37: // left arrow
			case 39: // right arrow
			case 33: // page up
			case 34: // page down
			case 36: // home
			case 35: // end
			case 27: // esc
			case 16: // shift
			case 17: // ctrl
			case 18: // alt
			case 46: // effacer tout		
			case 20: // caps lock
				return true;
				
			case 9:  // tab
				this.hidePopup();
				return false;
			case 13: // enter
				this.hidePopup();
				return true;
			default: // all other keys
				if (this.input.methode == 'autocomplete')
				{
					if (input.value.length > 0)
						this.populatePopup();
					else
						this.hidePopup();
				}
				return true;
		}
}

autocomplete.prototype.onblur = function (input) 
{
	// on recupere l'ancien style
	this.input.className = this.oldFocusClassName;

	// on cache le popup
	if ((input.value.length > 0) && (this.input.methode == 'assistant'))
	{
		this.populatePopup();
		var ps = this.popup.getElementsByTagName('p');
		if (ps.length > 1)
		{
			-- modifie
			//this.input.focus();
			return false;
		}
		return true;
	}
	
	this.hidePopup();
}

autocomplete.prototype.select = function (node) 
{
	setValue(this.input.name, node.innerHTML);
	setSqlValue(this.input.name, node.innerHTML);
	
	this.hidePopup();
}

autocomplete.prototype.selectDown = function () 
{
	if (this.selected) 
	{
		if (this.selected.nextSibling && this.selected.nextSibling.tagName)
		this.highlight(this.selected.nextSibling);
	} 
	else 
	{
		var ps = this.popup.getElementsByTagName('p');
		if (ps.length > 0)
			this.highlight(ps[0]);
	}
}

autocomplete.prototype.selectUp = function () 
{
	if (this.selected && this.selected.previousSibling 
		&& this.selected.previousSibling.tagName) 
	{
		this.highlight(this.selected.previousSibling);
	}
}

autocomplete.prototype.template = function () { }

autocomplete.prototype.highlight = function (node) 
{
	if (this.selected)
		this.selected.className = '';
	node.className = 'selected';
	this.selected = node;
}

autocomplete.prototype.unhighlight = function (node) 
{
	node.className = '';
	this.selected = false;
}

autocomplete.prototype.populatePopup = function () 
{
	var ac = this;
	var pos = AbsolutePosition(this.input);
	this.selected = false;
	this.popup.style.top = (pos.y + this.input.offsetHeight) + 'px';
	this.popup.style.left = pos.x + 'px';
	this.popup.style.width = (this.input.offsetWidth - 4) + 'px';
	this.db.onmatch = function(matches) { ac.found	(matches); }
	
//	this.db.search(string)
	var test = new Array();
	this.inputs = this.input.inputs.length > 0 ? this.input.inputs.split('_$_') : [];
	for (var i = 0 ; i < this.inputs.length; i++)
	{
		test[i] = getValue(this.inputs[i]);
	}	
	string = jsarray2php(test);
	this.db.search(string);	
}

autocomplete.prototype.found = function (matches) 
{
	while (this.popup.hasChildNodes())
		this.popup.removeChild(this.popup.childNodes[0]);
	if (!this.popup.parentNode || !this.popup.parentNode.tagName)
		document.getElementsByTagName('body')[0].appendChild(this.popup);

	var div = document.createElement('div');
	var ac = this;
	if (matches.length > 0) 
	{
		for (var i = 0; i < matches.length; i++) 
		{
			var p = document.createElement('p');
			p.appendChild(document.createTextNode(matches[i][1]));
			p.codesql = matches[i][0];
			p.onmousedown = function() { ac.select(this,matches[i]); }
			p.onmouseover = function() { ac.highlight(this); }
			p.onmouseout = function() { ac.unhighlight(this); }
			div.appendChild(p);
		}
		this.popup.appendChild(div);
	} 
	else 
	{
		this.hidePopup();
	}
}



/* === ACDB Base class */

function ACDB() 
{
	this.max = 15; // max returned results
	this.delay = 1000; // milliseconds
	this.docache = false; // client side cache
	this.cache = {};
	this.len = 0;
}

ACDB.prototype.toString = function () 
{
	return '[AutoComplete Database]';
}

ACDB.prototype.search = function(search_string) 
{
	if (!this.dosearch)
		return false;
	if (this.docache) 
	{
		this.search_string = search_string;
		if (this.cache[search_string])
			return this.match(this.cache[search_string]);
	}
	var db = this;
	if (this.timer) clearTimeout(this.timer);
	this.timer = setTimeout(function() { db.dosearch(search_string) }, this.delay);
}


ACDB.prototype.match = function (matches) 
{
	if (this.docache)
		this.cache[this.search_string] = matches;
	if (this.onmatch)
		this.onmatch(matches);
}


/* === class ACDB_JS extends ACDB === */

function ACDB_JS(array_of_strings) 
{
	this.strings = array_of_strings;
	this.delay = 1000;
}

ACDB_JS.prototype = new ACDB;

ACDB_JS.prototype.dosearch = function(search_string) 
{
	var search_length = search_string.length;
	var matches = [];
	var test_string = '';

	for (var i = 0; test_string = this.strings[i]; i++) 
	{
		if (test_string.substr(0,search_length).toLowerCase() == search_string.toLowerCase())
			matches[matches.length] = test_string;
		if (matches.length >= this.max)
			break;
	}
	this.match(matches);
}


/* === class ACDB_Remote extends ACDB === */

function ACDB_Remote(uri) 
{
	this.uri = uri;
	this.delay = 300;
	this.docache = false;
	this.action = '';
}

ACDB_Remote.prototype = new ACDB;

ACDB_Remote.prototype.dosearch = function(search_string) 
{
	Dialog.info("Recherche en cours!", 
             {windowParameters: {width:300}, okLabel: "Fermer", showProgress: true });	
	HTTPGet('?PAGE_AJAX=Y&ACTION='+this.action+'&ENVOI_PARAMETRE='+search_string , this.receive, this);
}

ACDB_Remote.prototype.receive = function(string, xmlhttp, acdb) 
{
	Dialog.closeInfo();
	if (xmlhttp.status != 200)	{
		return alert('An HTTP error ' + xmlhttp.status + ' occured.\n' + acdb.uri);
	}
	if (string.substr(0,7) == 'MESSAGE')
	{
		string.evalScripts();
	}
	else
	{
		try
		{
			var tableau = [];
			var reg = string.match(/retour&&&__(.*)__&&&/);	
			if ((reg != null) && (reg != -1)) 
			{
/*				var tableau = new phparray2js(reg[1]);	
				tableau = tableau.retour()
			
				this.len = tableau.length;
				var reg = string.match(/size&&&__(.*)__&&&retour/);	
				if ((reg != null) && (reg != -1)) 
				{
					acdb.len = Number(reg[1]);	
				}
				*/
				eval(reg[1]);
				acdb.match(tableau);
			}
		}
		catch(e){
			alert('erreur de traitement');
		};
	}
}


Event.onDOMReady(function(){InitInputs();})

function InitInputs()
{
	var ccclase = '';
	if (navigator.appVersion.match(/\bMSIE\b/)){
		ccclase = 'radioie';
	}
	else{
		ccclase = 'radioother';
	}
	var $$texte = $('texte');
	function $$$(tagname)
	{
		return $A(document.getElementsByTagName(tagname));
	}
	
	$$$('input').each(function(element) {
		element.valOk = true;
		element.fieldset = $$texte;
		element.save  = input_save;
		element.reset  = input_reset;
		element.getValue  = input_getValue;
		element.getForm  = input_getForm;
		element.methode = element.methode||'';
		
		if ( element.type == 'text')
		{	
			element.isOK = function (){return element.valOk};
//			element.isOK = function (){return true};

			if (Element.hasClassName(element,'date')){
			 	element.expregpress = "[ 0123456789/.-]";
				element.format = function(){formatdate(element)};
			}
			else if (Element.hasClassName(element,'numerique')){
			 	element.expregpress = "[ 0123456789,.-]";
			 	element.nbDecimal = -1;
			}
			else if (Element.hasClassName(element,'decimal')){
			 	element.expregpress = "[ 0123456789,.-]";
			 	element.nbDecimal = -1;
			}
			else if (Element.hasClassName(element,'monetaire')){
			 	element.expregpress = "[ 0123456789,.-]";
			 	element.nbDecimal = -1;
			}
			Event.observe(element, 'focus', function(){inputonfocus(element) }, false);
			Event.observe(element, 'blur', 	function(){inputonblur(element) }, false);
			Event.observe(element, 'change', function(){inputonchange(element) }, false);
			Event.observe(element, 'keypress', function(e){inputonkeypress(e,element) }, false);
			Event.observe(element, 'click', function(){inputonclick(element) }, false);
		}
		else if ( element.type == 'button' || element.type == 'reset' || element.type == 'submit' )
		{
			element.isOK = function (){return true};
			input_init(element);
			Event.observe(element, 'click', function(){inputonclick(element) }, false);
		}
		else
		{
			element.isOK = function (){return true};
			if (element.type == 'radio' || element.type == 'checkbox')
			{
				Element.addClassName(element, 'radio');
				Element.addClassName(element, ccclase);
				if (element.type == 'checkbox')
				{
					if (!element.uncheckedValue)
						element.uncheckedValue = "";
				}
			}

			Event.observe(element, 'focus', function(){inputonfocus(element) }, false);
			Event.observe(element, 'blur', 	function(){inputonblur(element) }, false);
		}
	});

	$$$('select').each(function(element) {
		element.fieldset = $$texte;
		element.save  = input_save;
		element.reset  = input_reset;
		element.getValue  = input_getValue;
		element.isOK = function (){return true};
		element.getForm  = input_getForm;
		element.methode = element.methode||'';
		Event.observe(element, 'click', function(){inputonclick(element) }, false);
		Event.observe(element, 'focus', function(){inputonfocus(element) }, false);
		Event.observe(element, 'change', 	function(){inputonblur(element) }, false);
	});

	$$$('textarea').each(function(element) {
		element.fieldset = $$texte;
		element.save  = input_save;
		element.reset  = input_reset;
		element.getValue  = input_getValue;
		element.getForm  = input_getForm;
		element.methode = element.methode||'';
		element.isOK = function (){return true};
		Event.observe(element, 'click', function(){inputonclick(element) }, false);
		Event.observe(element, 'focus', function(){inputonfocus(element) }, false);
		Event.observe(element, 'blur', 	function(){inputonblur(element) }, false);
		Event.observe(element, 'change', function(){inputonchange(element) }, false);
	});

	$$$('label').each(function(element) {
		Event.observe(element, 'click', function(){labelonclick(element) }, false);
		if (input = (element.getAttribute('htmlfor') || element.getAttribute('for')))
		{
			if (Element.hasClassName(element, 'obligatoire'))
				setObligatoire(input);
			if (!(input = getObj(input))) return;
			input.label = element;
		}
		labels = element.parentNode.getElementsByTagName('label');
		if (element == labels[0])
			element.className += ' labelfirst';
	});
	
	$$texte.save  = fieldset_save;
	$$texte.reset  = fieldset_reset;
	$$texte.serialise  = fieldset_serialise;
	$$texte.isOK  = fieldset_isOK;
	$$texte.save();

	$$$('fieldset').each(function(element) {
		element.save  = fieldset_save;
		element.reset  = fieldset_reset;
		element.serialise  = fieldset_serialise;
		element.isOK  = fieldset_isOK;
		element.save();
	});

}

