// diverses fonctions javascripts
// version: 01/09/03
// fonctions de Dreamweaver
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}



function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}


function MM_changeProp(objName,x,theProp,theValue) { //v6.0
  var obj = MM_findObj(objName);
  if (obj && (theProp.indexOf("style.")==-1 || obj.style)){
    if (theValue == true || theValue == false)
      eval("obj."+theProp+"="+theValue);
    else eval("obj."+theProp+"='"+theValue+"'");
  }
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function MM_setTextOfLayer(objName,x,newText) { //v4.01
if ((obj=MM_findObj(objName))!=null) with (obj)
	if (document.layers) {document.write(unescape(newText)); document.close();}
    else innerHTML = unescape(newText);
}

function toggleDisplay(id){
			if(this.document.getElementById( id).style.display=='none'){
				this.document.getElementById( id).style.display='inline'						
			}else{
				this.document.getElementById(  id).style.display='none'
			}
		}

// Fonctions outestoi
function ValidatePassword(pwd1,pwd2)
{	//**TODO** A faire test de longueur
	alert("et ho !"+pwd1);
}

function isDate(d) {
  // Cette fonction permet de vérifier la validité d'une date au format jj/mm/aa ou jj/mm/aaaa
  // Par Romuald http://www.javascriptfr.com/article.aspx?Val=50
  if (d == "") // si la variable est vide on retourne faux
    return false;
  
  e = new RegExp("^[0-9]{1,2}\/[0-9]{1,2}\/([0-9]{2}|[0-9]{4})$");
  
  if (!e.test(d)) // On teste l'expression régulière pour valider la forme de la date
    return false; // Si pas bon, retourne faux

  // On sépare la date en 3 variables pour vérification, parseInt() converti du texte en entier
	var j = (d.split("/")[0]); // jour
	var m = (d.split("/")[1]); // mois
	var a = (d.split("/")[2]); // année

//  j = parseInt(d.split("/")[0], 10); // jour
//  m = parseInt(d.split("/")[1], 10); // mois
//  a = parseInt(d.split("/")[2], 10); // année

  // Si l'année n'est composée que de 2 chiffres on complète automatiquement
  if (a < 1000) {
    if (a < 89)  a+=2000; // Si a < 89 alors on ajoute 2000 sinon on ajoute 1900
    else a+=1900;
  }

  // Définition du dernier jour de février
  // Année bissextile si annnée divisible par 4 et que ce n'est pas un siècle, ou bien si divisible par 400
  if (a%4 == 0 && a%100 !=0 || a%400 == 0) fev = 29;
  else fev = 28;

  // Nombre de jours pour chaque mois
  nbJours = new Array(31,fev,31,30,31,30,31,31,30,31,30,31);

  // Enfin, retourne vrai si le jour est bien entre 1 et le bon nombre de jours, idem pour les mois, sinon retourn faux
  return ( m >= 1 && m <=12 && j >= 1 && j <= nbJours[m-1] );
}
// verifie la date à partir d'un champ formulaire
// si elle est au format jj/mm --> convertie en jj/mm/aa dans le champ d'origine
// retourne false si la date reste invalide
function validatefrmDate(champdate)
{
	var myObj = MM_findObj(champdate);
    while(!isDate(myObj.value))
		{
		// forme jj/mm --> jj/mm/aa
		if(String(myObj.value).length==5) 
			{
			var today=new Date();
			y=today.getYear();
			if (String(y).length == 4)	y=String(y).substring(2,4) ;
			myObj.value+="/"+y;
			}
		else return false;
		}
	return true;
}

/**
 * Checks/unchecks all checkbox from a form
 * onclick='setCheckboxes(document.MassUpdate, "mass[]", this.checked)'
 * @param   string   the form name
 * @param	string   the checkbox names (in form 'tbl_chk[]')
 * @param   boolean  whether to check or to uncheck the element
 *
 * @return  boolean  always false
 */
function setCheckboxes(the_form, the_table, do_check)
{
	alert("go"+the_form);
    var elts      = document.forms[the_form].elements[the_table];
    var elts_cnt  = (typeof(elts.length) != 'undefined')
                  ? elts.length
                  : 0;

    if (elts_cnt) {
        for (var i = 0; i < elts_cnt; i++) {
            elts[i].checked = do_check;
        } // end for
    } else {
        elts.checked        = do_check;
    } // end if... else

    return false;	// pour empecher le lien
} // end of the 'setCheckboxes()' function

/**
 * Retourne VRAI si dans la liste de checkbox il y a au moins une selection
 * Affiche un message et retourne FAUX sinon
 * Retourne VRAI si la liste n'existe pas, ou si il s'agit d'une liste avec un seul item.
 *
 * @param   string   the form name
 * @param	string   the checkbox names (in form 'tbl_chk[]')
 *
 * @return  boolean  true if one checkbox is checked
 */
function isCheckboxeSelected(the_form, the_table)
{
var n,elts,elts_cnt,msg,i;
    elts      = document.forms[the_form].elements[the_table];
    elts_cnt  = (typeof(elts.length) != 'undefined')? elts.length : 0;
    if (elts_cnt) {
		n=0;
		for (i = 0; i < elts_cnt; i++) {
				if(elts[i].checked) return true;
			}
		alert("Cochez au moins une case dans la liste avant d'appuyer sur ce bouton.");
		return false;
		}
	else {
		var elt=document.forms[the_form].elements[the_table];
		if(!elt.checked) alert("Cochez la case dans la liste avant d'appuyer sur ce bouton.");
		return elt.checked;
	}
} // end of the 'isSelected()' function

// Demande la confirmation de la suppression des enregistrements sélectionnés
// retourne TRUE si l'utilisateur a confirmé la supression
// 12/04/03 AF - FP
function confirmKill(the_form, the_table)
{
var nb,elts,elts_cnt,msg;
		nb=0; //nb= nombres de cases cochees
		elts = document.forms[the_form].elements[the_table];
		elts_cnt  = (typeof(elts.length) != 'undefined') ? elts.length : 0;
		for (var i = 0; i < elts_cnt; i++)
		{
			if(elts[i].checked)	nb=nb+1;
		}

		if (elts_cnt==0)
		{
			if (elts.checked==true)	nb=1;
		}

		if (nb==1)
		{
			msg="cet enregistrement";
		}else{
			msg="ces "+nb+" enregistrements";
		}
		return confirm("Etes vous sûr de vouloir supprimer "+msg+" ?");
}
// Ouverture d'une fenetre popup bloquée
// 12/04/03 GT
function ouvreFenetre(page, largeur, hauteur) {
   window.open(page, "", "scrollbars=no,menubar=no,toolbar=no,resizable=no,top=50,left=50,width="+largeur+",height="+hauteur);
}

/* Variables et Fonctions pour la récupération des variables de l'URL */
var url_variables=new Array()

function url_clear(text)
{
	while (text.search(/%20/) != -1)
		text = text.replace(/%20/," ");
	return text;
}

function url_cut()
{
	var str1 = document.location.search;
	var str2 = str1;
	var pos1 = 1;
	var pos2 = pos1;
	var pos3 = pos1;
	var count = 0;

	while ( (pos2 = str1.indexOf("&", pos1)) != -1 )
	{
		str2 = str1.substring(pos1,pos2);
		pos3 = str2.indexOf("=");
		url_variables[count] = new Array();
		url_variables[count]["name"] = str2.substring(0,pos3);
		url_variables[count]["value"] = url_clear(str2.substring(pos3+1,str2.length));
		pos1 = pos2+1;
		count++;
	}

	pos2 = str1.length;
	str2 = str1.substring(pos1,pos2);
	pos3 = str2.indexOf("=");
	url_variables[count] = new Array();
	url_variables[count]["name"] = str2.substring(0,pos3);
	url_variables[count]["value"] = url_clear(str2.substring(pos3+1,str2.length));
}

function str_replace(text, src, rep){
		offset = text.toLowerCase().indexOf(src.toLowerCase());
		while ( offset != -1 ) {                         
		text = text.substring(0, offset) + rep + text.substring(offset + src.length ,text.length);
		offset = text.indexOf( src, offset + rep.length + 1);
		}
		return text;
		}


