

var Aujourdhui=new Date();

// *********************************************
// function Mois(date,t)
// Donne le mois en toutes lettres 
//   date   : une date quelconque
//   t      = "c" pour format court
//   t      toute autre valeur format long
// *********************************************
function Mois(date,t)
{
tMois = ["janvier" , "février" , "mars" , "avril" , "mai" , "juin" , "juillet" , "aout" , "septembre" , "octobre" , "novembre" , "décembre"];
tMoisCourt = ["jan" , "fév" , "mars" , "avr" , "mai" , "juin" , "jui" , "aout" , "sept" , "oct" , "nov" , "déc"];
   if ( t == "c" )
       w = tMoisCourt[ date.getMonth() ]
   else   
      w = tMois[ date.getMonth() ]
return w;
}

// *********************************************
// function jour(date,t)
// Donne le jour en toutes lettres 
//      date    : une date quelconque
//       t       = "c" pour un format court (3 lettres)
//       t      toute autre valeur, format long
// *********************************************
function jour(date,t)
{
   tJour= ["dimanche" , "lundi" , "mardi" , "mercredi" , "jeudi" , "vendredi" , "samedi"];
   if ( t == "c" )
      { w = tJour[ date.getDay() ].substr( 0 , 3) }
   else
      { w = tJour[ date.getDay() ] }
return w;
}

// *********************************************
// function DateCourte(date,separ)
// Donne une date du style jj/mm/aaaa
//      date    : une date quelconque
//      separ   : le séparateur (par exemple /)
// *********************************************

function DateCourte(date,separ)
{
   w = right("0" + date.getDate() , 2 );
   w = w + separ;
   w = w + right( "0" + ( date.getMonth() + 1 ) , 2 );
   w = w + separ;
   w = w + date.getFullYear();
return w;
}

// *********************************************
// function DateLongue(date)
// Donne une date au format long
//      date    : une date quelconque
// *********************************************
function DateLongue(date)
{
   w = jour( date ) + " ";
   w= w + date.getDate() + " ";
   w= w + Mois( date ) + " ";
   w= w + date.getFullYear();
return w;
}

// *********************************************
// function datedecal(date,n,t)
// Donne une date décalée par raport à une autre
//      date    : la date de référence
//      n       : le nombre d'unités dont on décale
//      t       = "j" pour changer les jours
//      t       = "m" pour changer les mois
//      t       = "a" pour changer les années
//      t       toute autre valeur ne fait rien
// *********************************************

function datedecal(date,n,t)
{
   j = date.getDate();
   m = date.getMonth();
   a = date.getFullYear();
   switch (t)
   {   case "j"    : j = j + n;
               break;
      case "m"   : m = m + n;
               break;
      case "a"   : a = a + n;
               break;
   }
   w = new Date( a , m , j );
return w;
}

// *********************************************
// function DernierJourMois(date)
// Donne une date correspondant au dernier jour du mois
//      date    : une date quelconque
// *********************************************
function DernierJourMois(date)
{
   j = date.getDate();
   m = date.getMonth();
   a = date.getFullYear();
   w = new Date( a , m + 1 , 0 )
return w;
}

// *********************************************
// function right(literal,longueur)
// Renvoie  les premiers caractères d'une chaîne
//      literal    : la chaîne de caractères
//      longueur   : le nombre de caractères
// *********************************************

function right(literal,longueur)
{
   l = literal.length
   w = literal.substr( l - longueur);
return w;
}


// *********************************************
// function estUnNombre(s)
// Renvoie vrai (true) si le paramètre est un nombre
//	s : la valeur à tester
// *********************************************

function estUnNombre(s) { return ( !isNaN( s ) )}


// *********************************************
// function estPositif(s)
// Renvoie vrai (true) si le paramètre est positif
// s : le nombre à tester (doit être un nombre)
// *********************************************

function estPositif(s) {return ( parseInt( s ) >= 0)}


// *********************************************
// function estEntier(s)
// Renvoie vrai (true) si le paramètre est entier
// s : le nombre à tester (doit être un nombre)
// *********************************************
function estEntier(s) {return (parseInt(s) == s)}


// *********************************************
// function Entier(s)
// Teste avec alarm paramètre est entier
// s : le nombre à tester (doit être un nombre)
// *********************************************
function Entier( item ) {
	item.value = trim(item.value) 
	var valeurchamp =  item.value  
	if ( valeurchamp == '' ) 
		return;
	if 	( !estEntier( valeurchamp ) ){ 	
		alert( "Entrez un nombre entier " );
		item.select();
	}
}

// *********************************************
// function Entier(s)
// Teste avec alarm paramètre est entier
// s : le nombre à tester (doit être un nombre)
// *********************************************
function Nombre ( item ) {
	item.value = trim(item.value) 
	var valeurchamp =  item.value  
	if ( valeurchamp == '' ) 
		return;

	valeurchamp = valeurchamp.replace ( ',' , '.')
	item.value = valeurchamp
	if 	( !estUnNombre( valeurchamp ) ){ 	
		alert( "Entrez un nombre +-nombre.dec" );
		item.select();
	}
}


// *********************************************
// function estEntierPositif(s)
// Utilise les fonctions précédentes pour tester
// si un paramètre est un nombre, entier et positif
// Renvoie vrai (true) si c'est le cas
//	s : la valeur à tester
// *********************************************

function estEntierPositif(s) {return (estUnNombre(s) & estEntier(s) & estPositif(s))}



// *********************************************
// function testBornes(item, min, max)
// teste si le champ contient un nombre, entier positif
// compris entre deux bornes
// item : le champ à tester
// min : la valeur minimale
// max : la valeur maximale
// *********************************************

function testBornes(item, min, max) 

{

	var valeurchamp = item.value 

	// Pour l'heure la valeur à retourner est faux (false)
	var returnVal = false	

	// Teste si le champ contient autre chose qu'un entier positif

	if 	( !estEntierPositif( valeurchamp ) )
		{ 	alert( "Entrez un nombre entier positif" );
			item.select();
		}
	// Si non (le contenu est entier positif)
	// teste si le contenu du champ est plus petit que le minimum

	else if (parseInt( valeurchamp ) < min)
		{	alert( "Le nombre " + item.name + " doit être plus grand que ou égal à " + min);
			item.value = min; // facultatif
			item.select();
		}

		// Si non (le contenu n'est pas plus petit que le minimum)
		// test si le contenu du champ est plus grand que le maximum

		else if ( parseInt( valeurchamp ) > max)
			{ 	alert("Le nombre " + item.name + " doit être inférieur ou égal à " + max);
				item.value = max; // facultatif
				item.select();	
			}

			// Si non (	le contenu n'est pas plus petit que le minimum et
			// 			n'est pas plus grand que le maximum)
			// alors le contenu est valable : la valeur à retourner est passée à vrai (true)
			else
			{                     
				returnVal = true;
			}
	return returnVal;
}


function trim(string) 
{ 
	return string.replace(/(^\s*)|(\s*$)/g,''); 
} 



// ************************************************************
// Contrôle si le champ date a été rempli et s'il est valide
// Un champ date valide doit être de la forme [J]J/M[M]/AA[AA] 
// (Les parties entre [] sont facultatives, "-" ou "." peuvent êtres utilisés à la place des "/",
// Soit "1/07/2003", "01/7/2003", "01/07/03", "01-07-2003" ou "01.07.2003" sont valides)
// Et doit correspondre à une date valide ("29/02/2003" sera refusé)
// ************************************************************

function ControleDate(champ) {
 if (champ.value == "" || champ.value == "0") {
    	champ.value="0";
	champ.select();
	}
 else {
   var pivot = 20;
   var resultat = true;
   re = /^(\d\d?)(\/|-|\.)(\d\d?)(\/|-|\.)(\d\d)(\d\d)?$/;
   var tab = champ.value.match(re);
   if (!tab) resultat = false;
   else {
     if ((tab.length == 6) || (!tab[6])) 
       tab[5] = ((tab[5] < pivot) ? 2000 : 1900) + parseInt(tab[5]);
     else tab[5] = parseInt(tab[5].concat(tab[6]));
     var unedate = new Date(tab[5], parseInt(tab[3])-1, tab[1]);
     resultat = ((unedate.getFullYear() == tab[5]) && (unedate.getMonth() == tab[3]-1) && (unedate.getDate() == tab[1]));
   }
  
    if (resultat) return "";
   else {
   	alert(  "Date invalide jj/mm/aa " + champ.name);
   	// champ.select();
  }  
 }
}



// Le focus sur le premier text
// <BODY OnLoad="PlaceFocus()">
function PlaceFocus() {
	if (document.forms.length > 0) {
	var field = document.forms[0];
	for (i = 0; i < field.length; i++) {
			if ((field.elements[i].type == "text") || 
			(field.elements[i].type == "textarea") || 
			(field.elements[i].type.toString().charAt(0) == "s")) {
			document.forms[0].elements[i].focus();
			break;
         }
      }
   }
}

// Le focus sur le premier text du formulaire x

function PlaceFocusI( x) {
	if (document.forms.length > 0) {
	var field = document.forms[x];
	for (i = 0; i < field.length; i++) {
			if ((field.elements[i].type == "text") || 
			(field.elements[i].type == "textarea") || 
			(field.elements[i].type.toString().charAt(0) == "s")) {
			document.forms[x].elements[i].focus();
			break;
         }
      }
   }
}
// Gestion DE ORDER BY
 function tri ( nb ) {
 	 document.forms[0].TRI.value=nb;
 	 document.forms[0].submit();
 }
 
 
//  Recherche simple OU Recherche avancé
 function funcf1 () {
 // alert ( document.getElementById('D2').style.display )
 	 if ( document.forms[0].AVC.value == '' ) {
 		document.forms[0].AVC.value='1';
 		document.getElementById('D2').style.display='block';
 		document.getElementById('D20').innerHTML = 'Recherche simple';
 	} else {
 		document.forms[0].AVC.value='';
 		document.getElementById('D2').style.display='none';
 		document.getElementById('D20').innerHTML = 'Recherche avancée';
 	}
 	// alert ( document.forms[0].AVC.value )
}


// P1= Cle   P2=Onglet 		ex:  '103136','CLIENT'
 function funcf2 (p1 , p2) {
 var chooser = null;
 	if ( p1 == '' ) return;
 	
  	document.forms[0].VONGLET.value='1'
  	document.forms[0].KEY.value = p2
  	if ( document.forms[0].PG.value !=  '' ) {
  		// alert ( document.location=document.forms[0].PG.value + '  ?KEY=  ' + p1  + ' ' + p2 );
  		if ( document.forms[0].PG.value.indexOf('?') <0 )
  			document.location=document.forms[0].PG.value + '?KEY=' + p1
  		else
  			document.location=document.forms[0].PG.value + '&KEY=' + p1
  		document.forms[0].VONGLET.value='2'
  		return;
	}
	
	if ( document.forms[0].PHPONGLET.value == '' && document.forms[0].PG.value == '' ) {
	    chooser = window.open("autre_options.php?KEY=" + p1 + '&ONGLET='+ p2, 
			"chooser", 
			"scrollbars=yes,location=no,menubar=no,status=no,toolbar=no,resize=no,width=300,height=600");
	    chooser.focus();
	}
	else 
	document.forms[0].submit();
}	

/**
 * Sets/unsets the pointer and marker in browse mode
 *
 * @param   object   the table row
 * @param   string   the action calling this script (over, out or click)
 * @param   string   the default background color
 * @param   string   the color to use for mouseover
 * @param   string   the color to use for marking a row
 *
 * @return  boolean  whether pointer is set or not
 */
function setPointer(theRow, theAction, theCouleur)
{
    var theCells = null;
    var theDefaultColor= '#FFFFFF'
    var thePointerColor= '#E1E2FF'
    var theMarkColor= '#FFCC99';
    var nom_navigateur = navigator.appName;

    if ( nom_navigateur != 'Microsoft Internet Explorer' ) {
    	theCells = theRow.getElementsByTagName('td');
    	var rowCellsCnt = theCells.length;
           for (c = 0; c < rowCellsCnt; c++) {
           	if ( theAction == 'out' )
                    theCells[c].setAttribute('bgcolor', 'white', 0);
           	if ( theAction == 'click' )
                    theCells[c].setAttribute('bgcolor', '#FFCC99', 0);
           	if ( theAction == 'over' )
                    theCells[c].setAttribute('bgcolor', '#E1E2FF', 0);                    
            }  
    	return;
    }
    // 1. Pointer and mark feature are disabled or the browser can't get the
    //    row -> exits
    if ((thePointerColor == '' && theMarkColor == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }

    // 2. Gets the current row and exits if the browser can't get it
    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }

    // 3. Gets the current color...
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentColor = null;
    var newColor     = null;
    // 3.1 ... with DOM compatible browsers except Opera that does not return
    //         valid values with "getAttribute"
    if (typeof(window.opera) == 'undefined'
        && typeof(theCells[0].getAttribute) != 'undefined') {
        currentColor = theCells[0].getAttribute('bgcolor');
        domDetect    = true;
    }
    // 3.2 ... with other browsers
    else {
        currentColor = theCells[0].style.backgroundColor;
        domDetect    = false;
    } // end 3

    // 4. Defines the new color
    // 4.1 Current color is the default one
    if (currentColor == ''
        || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
        if (theAction == 'over' && thePointerColor != '') {
            newColor = thePointerColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor = theMarkColor;
        }
    }
    // 4.1.2 Current color is the pointer one
    else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()) {
        if (theAction == 'out') {
            newColor = theDefaultColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor = theMarkColor;
        }
    }
    // 4.1.3 Current color is the marker one
    else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
        if (theAction == 'click') {
            newColor = (thePointerColor != '')
                     ? thePointerColor
                     : theDefaultColor;
        }
    } // end 4

    // 5. Sets the new color...
    if (newColor) {
        var c = null;
        // 5.1 ... with DOM compatible browsers except Opera
        if (domDetect) {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].setAttribute('bgcolor', newColor, 0);
            } // end for
        }
        // 5.2 ... with other browsers
        else {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].style.backgroundColor = newColor;
            }
        }
    } // end 5

    return true;
} // end of the 'setPointer()' function


function creerCalendrier() {
	// Constructeur du calendrier
	this.date=new Date();
	this.mois=Array("Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre");
	this.champ=null;
	this.timer=null;
	this.init=initCalendrier;
	this.formatDate=formatDateCalendrier;
	this.getDate=getDateCalendrier;
	this.printSaisie=printSaisieCalendrier;
	this.affiche=afficheCalendrier;
	this.cache=cacheCalendrier;
	this.getContenu=getContenuCalendrier;
	this.selectDate=selectDateCalendrier;
	this.initTimer=initTimerCalendrier;
	this.stopTimer=stopTimerCalendrier;
}

function initCalendrier() {
	// Fonction d'initialisation pour la création du calque divCalendrier
	document.write("<div id=\"divCalendrier\" style=\"display:none\" onmouseover=\"calendrier.stopTimer();\" onmouseout=\"calendrier.initTimer()\"></div>");
}

function formatDateCalendrier(dt) {
	// Retourne une date en format texte
	var Y=dt.getFullYear();
	var D=dt.getDate();
	if (D<10) {D="0"+D;}
	var M=dt.getMonth()+1;
	if (M<10) {M="0"+M;}
	return D+"/"+M+"/"+Y;
}

function getDateCalendrier(txtDt) {
	// Retourne un objet Date à partir d une chaîne
	var dt=new Date();
	var regControleDate=new RegExp("^[0-9]{2}(/){1}[0-9]{2}(/){1}[0-9]{4}$","g");
	if (txtDt.match(regControleDate)) {
		dt.setDate(txtDt.substring(0,2));
		dt.setMonth(txtDt.substring(3,5)-1);
		dt.setFullYear(txtDt.substring(6,10));
	}
	return dt;
}

function printSaisieCalendrier(nom) {
	// Ecrit dans le document un champ de saisie de type date avec calendrier
	document.write("<input type=\"text\" name=\""+nom+"\" class=\"inputCalendrier\" onfocus=\"calendrier.affiche(this)\">");
}

function afficheCalendrier(champ) {
	// Affiche à l écran le calendrier
	if (document.getElementById) {
		this.stopTimer();
		this.date=this.getDate(champ.value);
		this.champ=champ;
		var div=document.getElementById("divCalendrier");
		// alert( champ.offsetLeft+"px" );
		div.style.top=(champ.offsetTop+champ.offsetHeight+100)+"px";
		div.style.left=(champ.offsetLeft+360)+"px";
		this.getContenu();
		div.style.display="block";
		this.initTimer();
	}
}

function getContenuCalendrier() {
	// Crée le contenu du calendrier pour la date passée en paramètre

	// Création de l entête du calendrier
	var mois=this.mois[this.date.getMonth()];
	var annee=this.date.getFullYear();
	var txtContenu="<table cellspacing=\"1\"><tr><td class=\"titre\"><a href=\"#\" onclick=\"calendrier.date.setMonth("+(this.date.getMonth()-1)+");calendrier.getContenu();\">&lt;&lt;</a></td><td colspan=\"5\" class=\"titre\">"+mois+" "+annee+"</td><td class=\"titre\"><a href=\"#\" onclick=\"calendrier.date.setMonth("+(this.date.getMonth()+1)+");calendrier.getContenu();\">&gt;&gt;</a></td></tr>";
	txtContenu+="<tr><td class=\"jour\">L</td><td class=\"jour\">M</td><td class=\"jour\">M</td><td class=\"jour\">J</td><td class=\"jour\">V</td><td class=\"jour\">S</td><td class=\"jour\">D</td></tr>";
	txtContenu+="<tr>";

	// Recherche du premier jour du mois pour déterminer à quelle date commence l affichage
	var dtAujourdhui=new Date();
	var dtJour1=new Date();
	dtJour1.setDate(1);
	dtJour1.setMonth(this.date.getMonth());
	dtJour1.setFullYear(this.date.getFullYear());
	var nbJourDecalage=dtJour1.getDay();
	if (nbJourDecalage==0) { // Dimanche
		nbJourDecalage=7;
	}

	// Boucle sur les cases du calendrier
	var nbCase=0;
	var dtBoucle=dtJour1;
	dtBoucle.setDate(1-nbJourDecalage);
	for (var i=0; i<42 ; i++) {
		dtBoucle.setDate(dtBoucle.getDate()+1);
		var txtDt=this.formatDate(dtBoucle);
		var classe="moisActif";
		if (dtBoucle.getMonth()!=this.date.getMonth()) {
			classe="moisInactif";
		}
		if (txtDt==this.champ.value) {
			classe="jourSelection";
		}
		if ((this.champ.value=="")&&(txtDt==this.formatDate(dtAujourdhui))) {
			classe="jourSelection";
		}
		txtContenu+="<td class=\""+classe+"\"><a href=\"javascript:calendrier.selectDate('"+txtDt+"')\" title=\""+txtDt+"\">"+dtBoucle.getDate()+"</a></td>";
		nbCase++;
		if (nbCase==7) {
			txtContenu+="</tr>";
			if (i<41) {
				txtContenu+="<tr>";
			}
			nbCase=0;
		}
	}
	txtContenu+="</table>";
	if (document.getElementById) {
		document.getElementById("divCalendrier").innerHTML=txtContenu;
	}
}

function selectDateCalendrier(txtDate) {
	// Gère le clic sur une date dans le calendrier
	this.champ.value=txtDate;
	this.cache();
}

function initTimerCalendrier() {
	// Déclenche la minuterie qui gère l effacement du calendrier
	if (this.timer==null) {
		this.timer=setTimeout("cacheCalendrier()", 2000);
	}
}

function stopTimerCalendrier() {
	// Arrête la minuterie quand la souris est sur le calendrier
	if (this.timer!=null) {
		clearTimeout(this.timer);
		this.timer=null;
	}
}

function cacheCalendrier() {
	// Cache le calque contenant le calendrier
	if (document.getElementById) {
		var div=document.getElementById("divCalendrier");
		div.style.display="none";
	}
	calendrier.stopTimer();
}

var calendrier=new creerCalendrier();



function getNewXMLHTTP( ) {

   try {
	  return new XMLHttpRequest();
    } catch(e) {
	  try {
	    var aObj = new ActiveXObject("Msxml2.XMLHTTP");
	  } catch (e) {
	    try {
		  var aObj = new ActiveXObject("Microsoft.XMLHTTP");
	    } catch(e) {
		  return false;
	    }
      }
    }
      return aObj;
 }




function fsurvol_lance ( page , param  )  {
 
    if ( ! document.getElementById('SUR02').checked ) return;

	var xhr = getNewXMLHTTP();

	var url = page + '?PARAM=' + param
	 
	xhr.onreadystatechange = function() { fsurvol_ajax(xhr); };
	xhr.open("GET", url, true);
        xhr.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
	xhr.send(null);
}



function fsurvol_ajax(xhr)
{
    if (xhr.readyState == 4)
		if ( xhr.responseText != '' ) {
			document.getElementById('SUR03').innerHTML = xhr.responseText ;
			$("#SUR03").fadeIn(2000);
		}	

}


var timer2
var cle1
var cle2
var page_ajax


function fsurvol ( page , param  )  {
	page_ajax = page
	cle2 = param
}

function timer_on_off () {
	if ( document.getElementById('SUR02').checked )
		timer2 = setInterval("Timer1()", 2000);
	else
		clearInterval( timer2 )
}

function survol_timer_go () {
	 
	clearInterval( timer2 )	;
	timer2 = setInterval("Timer1()", 2000);	 
	document.getElementById('SUR02').checked = true
		
}


function Timer1 () {
	if ( cle2 != cle1  ) {
		cle1 = cle2
		fsurvol_lance ( page_ajax, cle2 );
	}
}





var zarti1 = '';
var timer3;
var cpt2a=0;

function arti_keypress ( moi ) {
	 zarti1 = '';
	 zarti2 = '';
	 cpt2a = 0;
	 document.getElementById('searchsuggestions').style.display='none';
}



function Timer2A () {
	var zarti =  document.getElementById('RECHERCHE').value;
	if ( zarti1 != zarti   ) {
		zarti1 = zarti
		if ( trim(zarti).length > 2 && document.getElementById('searchsuggestions').value != ''  ) {
			document.getElementById('searchsuggestions').style.display='block';
			cpt2a=0;
			sugg_lance ();
		}
	} else
	  if ( (cpt2a++) > 4 )
	  	document.getElementById('searchsuggestions').style.display='none';


}



function sugg_lance ()  {
	
	
	var xhr = getNewXMLHTTP();
	var url = '/sugg_mot_ajax.php?RECHERCHE=' + document.getElementById('RECHERCHE').value
	document.getElementById('searchsuggestions').innerHTML = ''
	xhr.onreadystatechange = function() { sugg_lance_ajax (xhr); };
	xhr.open("GET", url, true);
	xhr.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
	xhr.send(null);
}



function sugg_lance_ajax(xhr)	{
    if (xhr.readyState == 4)
		if ( xhr.responseText != '' ) 
			document.getElementById('searchsuggestions').innerHTML = xhr.responseText ;	
}

function f_a (moi) {

	 cpt2a = 0;
	 var i = 0
	 var tmp = ''

	 mato = document.getElementById('RECHERCHE').value.split(' ')
	 for ( var i=0; i< mato.length-1; i++ )
	 		tmp = tmp + ' ' + mato[i]

	 tmp = trim(tmp) + ' ' + moi+ ' '
	 document.getElementById('searchsuggestions').style.display='none'
	 document.getElementById('RECHERCHE').value = tmp
	 zarti1 = tmp;
	 zarti2 = tmp;
	 document.getElementById('RECHERCHE').focus();

}


