// fonctions de contrôle syntaxique :

// function debug(_obj)
// function redirectRech( _action){
// function checkString(str,char_list)
// function verifyPath(thevalue)
// function parseFileName(localfile)
// function submit()
// function displayMessage()

// function checkSector( field, fieldName )
// function checkField( field )
// function checkCheckBox( field )
// function checkString( field, fieldName )
// function checkStringWithSize( field, fieldName, sizeMax, mandatory )  : contrôle que la taille du champ ne dépasse pas sizeMax (+ obligatoire)
// function checkStringWithSizeMin( field, fieldName, sizeMin )          : contrôle que le champ contienne au moins sizeMin caractères
// function checkWithFormat( field, fieldName, re, formatErrorMessage, mandatory )
// function isSameAndNotNull(s1, s2)

// function isDateValid(madate, fieldName )
// function checkValidDate( field, fieldName, mandatory )
// function checkDate( field, fieldName )
// function checkOptionalDate( field, fieldName )
// function checkDiffDate()
// function checkBODiffDate()
// function isDate (s)
// function checkDateBeforeToday( field, fieldName, mandatory )  : contrôle syntaxe date + date <= aujourd'hui (+ obligatoire)
// function checkAnneeBeforeThisYear( field, fieldName )         : contrôle entier < année(aujourd'hui) et >= année(aujourd'hui)-20 ans
// function checkValidDateRange( field, fieldName, mandatory, min, max) : contrôle syntaxe date + min <= date <= max (+ obligatoire)
// function checkValidDateInterv( field, fieldName, mandatory, min, max) :  min <= date <= max (+ obligatoire)

// function checkValidInteger( field, fieldName, mandatory )
// function checkInteger( field, fieldName )
// function checkOptionalInteger( field, fieldName )
// function checkSignedInteger( field, fieldName )
// function checkOptionalSignedInteger( field, fieldName )
// function checkValidSignedInteger( field, fieldName, mandatory )
// function checkValidSignedIntegerRange( field, fieldName, mandatory, min, max )

// function checkFloat( field, fieldName )
// function checkOptionalFloat( field, fieldName )
// function checkPositivFloat( field, fieldName )
// function checkOptionalPositivFloat( field, fieldName )
// function checkSignedFloat( field, fieldName )
// function checkOptionalSignedFloat( field, fieldName )
// function checkValidSignedFloat( field, fieldName, mandatory)
// function checkValidSignedFloatRange( field, fieldName, mandatory, min, max)

// function checkMandatoryField(titre,file)
// function checkCriterii(_form,profondeur)
// function checkAllCriterii(_form,profondeur)

// function isTelephone (s)
// function isTelephoneValid(telephone, fieldName )
// function checkValidTelephone( field, fieldName, mandatory )
// function checkTelephone( field, fieldName )
// function checkOptionalTelephone( field, fieldName )

// function isEmail (s)
// function isEmailValid(email, fieldName )
// function checkValidEmail( field, fieldName, mandatory )
// function checkEmail( field, fieldName )
// function checkOptionalEmail( field, fieldName )

// function isURL (s)
// function isURLValid(url, fieldName )
// function checkValidURL( field, fieldName, mandatory )
// function checkURL( field, fieldName )
// function checkOptionalURL( field, fieldName )

// function desactivateSectors()
// function openSmallWindow(url)
// function openContactWindow(url)

// function checkDateApport(field, fieldName, _msg)          : spécifique Suivi Cultural - Apports
// function checkSelect(field, fieldName)                    : Contrôle le choix dans une liste déroulante différent de '1 - NON RENSEIGNE'

//function checkValidSignedFloatSum( sum, fieldName, max)    : Contrôle sur la somme doit être supérieure à un maximum
//function initField( field, valInit)			     : Initialisation des champs à une valeur


//function checkSpecialCharacter( field, fieldName ) Contrôle interdisant les caractères spéciaux ; / ? : @ & = + $ , - _ . ! ~ * ' ( )
//function formatBDtoRegExp(formatBD)                        : Traduit un format issu de la BD (ex: 999.99) en expression régulière



//function checkPercentCharacter( field, fieldName )Contrôle interdisant le caractère %
var mandatoryMessage = "";

var FIELD_ERROR = "Le champ \'";
var DATE_ERROR = "La date \'";
var EMAIL_ERROR = "L\' adresse email \'";
var URL_ERROR = "L\' url \'";
var TEL_ERROR = "Le numéro de téléphone \'";
var MANDATORY_ERROR = "\' doit être renseigné.\n";
var INTEGER_FORMAT_ERROR = "\' doit être un entier positif.\n";
var SIGNED_INTEGER_FORMAT_ERROR = "\' doit être un entier signé.\nExemple : -1 ou 10\n";
var FLOAT_FORMAT_ERROR = "\'  doit être un réel positif.\nExemple : +1.1 ou 10.5\n\n";
var SIGNED_FLOAT_FORMAT_ERROR = "\'  doit être un réel signé.\nExemple : -1.1 ou 10.5\n";
var DATE_FORMAT_ERROR = "\' doit être une date au format \'JJ/MM/AAAA\'.\n";
var DATE_UNEXIST_ERROR = "\' n'est pas valide.\n";
var DATE_BEFORE_TODAY_ERROR = "\' doit être antérieure à aujourd'hui.\n";
var YEAR_BEFORE_TODAY_ERROR = "\' doit être < à l'année en cours et doit être >= à l'année en cours -20 ans.\n";
var EMAIL_UNEXIST_ERROR = "\' n'est pas valide.\nElle doit être au format suivant x@y.z où xyz sont des mots d\'au moins un caractère.\nExemple : dupont@fournisseur.fr\n";
var URL_FORMAT_ERROR = "\' n'est pas valide.\nElle doit être au format suivant x://y.z où xyz sont des mots d\'au moins un caractère\n";
var TEL_FORMAT_ERROR = "\' n'est pas valide.\nIl doit être au format suivant 0Z AB PQ MC DU où \nZ est un chiffre entre 1 et 8 et ABPQMCDU sont des chiffres de 0 à 9.\nExemple : 01 01 01 01 01\n";
var RANGE_FORMAT_ERROR_1 = "\' doit être compris entre les valeurs ";
var RANGE_FORMAT_ERROR_2 = " et ";
var RANGE_FORMAT_ERROR_3 = " (valeurs incluses).\n";
var SIZE_FORMAT_ERROR_1 = "\' doit contenir au maximum ";
var SIZE_FORMAT_ERROR_2 = "\' doit contenir au moins ";
var SIZE_FORMAT_ERROR_3 = " caractères.\n";
var SIZE_FORMAT_ERROR_3b = " caractère.\n";
var SIZE_FORMAT_ERROR_4a = "\' doit contenir exactement ";
var SIZE_FORMAT_ERROR_4b = " caractères.\n";

var ALPHA_STRING_FORMAT_ERROR = "\' doit être alphanumérique sans caractères spéciaux.\n";
var SECTION_URL_FORMAT_ERROR = "\' doit être alphanumérique sans caractères spéciaux (sauf - et _).\n";
var DATE_RANGE_FORMAT_ERROR_1 = "\' doit être comprise entre le ";
var DATE_RANGE_FORMAT_ERROR_2 = " et le ";
var DATE_RANGE_FORMAT_ERROR_3 = " (bornes comprises).\n";
var WRONG_CHARACTER_ERROR_2 = "\' n'est pas valide.\nIl ne doit pas contenir de caractères spéciaux:\n  ; \/ ? : @ & = + $ , - _ . ! ~ * \' ( )\n";
var WRONG_PERCENT_CHARACTER_ERROR = "\' ne doit pas contenir de caractères \%.\n";

function debug(_obj)
{
 var str ="";
  for (i in _obj)
  {
   str += "["+i+"]="+_obj[i]+"\n";
   if (str.length > 600 )
   {
     alert(str);
     str="";
   }
  }
   alert(str);

}

function redirectRech( _action){

    this.document.rechercheForm.action = _action;
    //debug(this.document.rechercheForm);
    this.document.rechercheForm.submit();

}


function checkString(str,char_list)
{
 if (str==null)
  return false;

 if (str.length==0)
  return false;

 for (var i=0;i<str.length;i++)
 {
  var c = str.charAt(i);
  if ((c>='a')&&(c<='z'))
   continue;
  if ((c>='A')&&(c<='Z'))
   continue;
  if ((c>='0')&&(c<='9'))
   continue;
  if (char_list.indexOf(c)==-1)
  return false;
 }
 return true;
}


function verifyPath(thevalue)
{
// alert ("verifyPath :" + thevalue);
 if ( checkString(thevalue,"-_.")==false )
  {
   alert( "Seuls les chiffres, lettres et caractères '-' et '_' sont authorisés/"
          + "\nLes espaces sont interdits.");
   return false;
  }
 return true;
}

function parseFileName(localfile)
{
//alert("parseFileName("+localfile+")" );
 if (localfile==""||localfile==null||localfile.length==0)
 {
  alert ("Le nom du fichier est incorrect.");
  return false;
  }

 var idx1 = localfile.lastIndexOf("\\");
 var idx2 = localfile.lastIndexOf("/");
 var idx = Math.max(idx1,idx2);

 return verifyPath(localfile.substring(idx+1, localfile.length));

}

function submit() {
    if( ! displayMessage() ){
        document.formulaire.submit();
    }
}

function displayMessage() {
	if ( mandatoryMessage != "") {
            alert( mandatoryMessage );
            mandatoryMessage = "";
            return true;
	}else{
            return false;
        }
}

function checkSector( field, fieldName )
{
    var good = false;
    if( field.tagName ){
        // Ce n est pas un tableau
        if( field.value != '' ){
            good = true;
        }
    }else{
        //C est un tableau
        for( i = 0; i < field.length; ++i ){
            if( field[i].value != '' ){
                good = true;
            }
        }
    }
    if( good == false ){
        mandatoryMessage += FIELD_ERROR + fieldName + MANDATORY_ERROR;
    }
    return good;
}

function checkField( field )
{
	//alert(field);
    if((!field) || (field.value == null) || ( field.value.length == 0 ) ){
        return false;
    }else{
        return true;
    }
}

function checkCheckBox( field )
{
    return field.checked;

}

function checkString( field, fieldName )
{
    if( (field.value == null) || ( field.value.length == 0 ) ){
        mandatoryMessage += FIELD_ERROR + fieldName + MANDATORY_ERROR;
        return false;
    }else{
        return true;
    }
}

// contrôle que la taille du champ est égale à size
function checkStringWithFixedSize( field, fieldName, size, mandatory )
{
    if( checkField(field) ){
    	if( field.value.length != size ) {
           mandatoryMessage += FIELD_ERROR + fieldName + SIZE_FORMAT_ERROR_4a + size + SIZE_FORMAT_ERROR_4b;
           return false;
        }
    }else{
        if(mandatory == true) {
           mandatoryMessage += FIELD_ERROR + fieldName + MANDATORY_ERROR;
           return false;
        }
    }
    return true;
}

// contrôle que la taille du champ ne dépasse pas sizeMax (+ obligatoire)
function checkStringWithSize( field, fieldName, sizeMax, mandatory )
{
    if( field.value.length > sizeMax ) {
        mandatoryMessage += FIELD_ERROR + fieldName + SIZE_FORMAT_ERROR_1 + sizeMax + SIZE_FORMAT_ERROR_3;
        return false;
    }else{
        if( (mandatory == true) && ( (field.value == null) || ( field.value.length == 0 ) ) ) {
            mandatoryMessage += FIELD_ERROR + fieldName + MANDATORY_ERROR;
            return false;
        }
    }
    return true;
}

// contrôle que le champ contienne au moins sizeMin caractères
function checkStringWithSizeMin( field, fieldName, sizeMin ) {
    if( (field.value == null) || ( field.value.length < sizeMin) ){
        mandatoryMessage += FIELD_ERROR + fieldName + SIZE_FORMAT_ERROR_2 + sizeMin;
        if(sizeMin==1) mandatoryMessage += SIZE_FORMAT_ERROR_3b;
        else mandatoryMessage += SIZE_FORMAT_ERROR_3;
        return false;
    }
    return true;
}

function checkWithFormat( field, fieldName, re, formatErrorMessage, mandatory )
{
    if( checkField( field ) ){
        if( !re.test( field.value ) ){
            mandatoryMessage +=  FIELD_ERROR + fieldName + formatErrorMessage;
            return false;
        }
   }else{
        if( mandatory == true ){
            mandatoryMessage += FIELD_ERROR + fieldName + MANDATORY_ERROR;
            return false;
        }
    }
    return true;
}

var reDate = /^\d\d\/\d\d\/\d\d\d\d$/;

function isDateValid(madate, fieldName ) {
      var separateur="/"; // separateur entre jour/mois/annee
      var jour=parseInt(madate.substring(0,2),10);
      var mois=parseInt(madate.substring(3,5),10);
      var annee=parseInt(madate.substring(6),10);

      if ( !reDate.test(madate) ){
        mandatoryMessage += DATE_ERROR + fieldName + DATE_FORMAT_ERROR;
        return false;
      }
      if ((jour<1)||(jour>31)||(mois<1)||(mois>12)) {
        mandatoryMessage += DATE_ERROR + fieldName + DATE_UNEXIST_ERROR;
        return false;
      }
      if ( (madate.substring(2,3)!=separateur)||((madate.substring(5,6)!=separateur)&&madate.length>5) ) {
        mandatoryMessage += DATE_ERROR + fieldName + DATE_FORMAT_ERROR;
        return false;
      }

      var date2=new Date(annee,mois-1,jour);
      jour2=date2.getDate();
      mois2=date2.getMonth()+1;
      annee2=date2.getFullYear();
      if ( (jour!=jour2)||(mois!=mois2)||(annee!=annee2) ) {
        //alert("La date "+madate+" n'existe pas !");
        mandatoryMessage += DATE_ERROR + fieldName + DATE_UNEXIST_ERROR;
        return false;
      }
      return true;
}

function checkValidDate( field, fieldName, mandatory )
{
    if( checkField( field ) ){
        return isDateValid( field.value, fieldName );
   }else{
        if( mandatory == true ){
            mandatoryMessage += FIELD_ERROR + fieldName + MANDATORY_ERROR;
            return false;
        }
    }
    return true;
}

function checkDate( field, fieldName )
{
    return checkValidDate( field, fieldName, true );
}

function checkOptionalDate( field, fieldName )
{
    return checkValidDate( field, fieldName, false );
}

function checkDateBeforeToday( field, fieldName, mandatory )
{
    if( checkValidDate( field, fieldName, mandatory ) ) {
        maDateString = field.value;
        jour = parseInt(maDateString.substring(0,2),10);
        mois = parseInt(maDateString.substring(3,5),10);
        annee = parseInt(maDateString.substring(6),10);
        maDate = new Date(annee,mois-1,jour);
        dateJour = new Date();
        if ( maDate > dateJour ) {
            mandatoryMessage += DATE_ERROR + fieldName + DATE_BEFORE_TODAY_ERROR;
            return false;
        }
    }
    return true;
}

function checkAnneeBeforeThisYear(field, fieldName)
{
    if( checkInteger(field, fieldName) ) {
        dateJour = new Date();
        dateSaisie = parseInt(field.value);
        //alert ( "dateSaisie:"+ dateSaisie +"/dateJour:"+dateJour);
        if (  (dateSaisie < dateJour.getFullYear())
           && (dateSaisie >= (dateJour.getFullYear())-20)
           )
        {
            return true;
        }
        else {
            mandatoryMessage += FIELD_ERROR + fieldName + YEAR_BEFORE_TODAY_ERROR ;
            return false;
        }
    }
}

function checkValidDateInterv( field, fieldName, mandatory, min, max)
{
	maDateString = field.value;
	jour = parseInt(maDateString.substring(0,2),10);
	mois = parseInt(maDateString.substring(3,5),10);
	annee = parseInt(maDateString.substring(6),10);
	maDate = new Date(annee,mois-1,jour);

	jour = parseInt(min.substring(0,2),10);
	mois = parseInt(min.substring(3,5),10);
	annee = parseInt(min.substring(6),10);
	dateMin = new Date(annee,mois-1,jour);

	jour = parseInt(max.substring(0,2),10);
	mois = parseInt(max.substring(3,5),10);
	annee = parseInt(max.substring(6),10);
	dateMax = new Date(annee,mois-1,jour);

	if ( maDate < dateMin || maDate > dateMax ) {
	    mandatoryMessage += DATE_ERROR + fieldName + DATE_RANGE_FORMAT_ERROR_1 + min + DATE_RANGE_FORMAT_ERROR_2 + max + DATE_RANGE_FORMAT_ERROR_3;
	    return false;
	}
    	return true;
}

function checkValidDateRange( field, fieldName, mandatory, min, max)
{
    if( checkValidDate( field, fieldName, mandatory ) ) {
        maDateString = field.value;
        jour = parseInt(maDateString.substring(0,2),10);
        mois = parseInt(maDateString.substring(3,5),10);
        annee = parseInt(maDateString.substring(6),10);
        maDate = new Date(annee,mois-1,jour);

        jour = parseInt(min.substring(0,2),10);
        mois = parseInt(min.substring(3,5),10);
        annee = parseInt(min.substring(6),10);
        dateMin = new Date(annee,mois-1,jour);

        jour = parseInt(max.substring(0,2),10);
        mois = parseInt(max.substring(3,5),10);
        annee = parseInt(max.substring(6),10);
        dateMax = new Date(annee,mois-1,jour);

        if ( maDate < dateMin || maDate > dateMax ) {
            mandatoryMessage += DATE_ERROR + fieldName + DATE_RANGE_FORMAT_ERROR_1 + min + DATE_RANGE_FORMAT_ERROR_2 + max + DATE_RANGE_FORMAT_ERROR_3;
            return false;
        }
    }
    return true;
}

/////////////////////////////////////
// INTEGER
/////////////////////////////////////

var reInteger = /^\s*\d+\s*$/;

function checkValidInteger( field, fieldName, mandatory )
{
    return checkWithFormat( field, fieldName, reInteger, INTEGER_FORMAT_ERROR, mandatory );
}
function checkInteger( field, fieldName )
{
    return checkWithFormat( field, fieldName, reInteger, INTEGER_FORMAT_ERROR, true );
}

function checkOptionalInteger( field, fieldName )
{
    return checkWithFormat( field, fieldName, reInteger, INTEGER_FORMAT_ERROR, false );
}
/////////////////////////////////////
// SIGNED INTEGER
/////////////////////////////////////

//var reSignedInteger = /^.+$/;
var reSignedInteger = /^\s*-?\s*\d+\s*$/;

function checkSignedInteger( field, fieldName )
{
    return checkWithFormat( field, fieldName, reSignedInteger, SIGNED_INTEGER_FORMAT_ERROR, true );
}

function checkOptionalSignedInteger( field, fieldName )
{
    return checkWithFormat( field, fieldName, reSignedInteger, SIGNED_INTEGER_FORMAT_ERROR, false );
}

function checkValidSignedInteger( field, fieldName, mandatory )
{
    return checkWithFormat( field, fieldName, reSignedInteger, SIGNED_INTEGER_FORMAT_ERROR, mandatory );
}


function checkValidSignedIntegerRange( field, fieldName, mandatory, min, max )
{
    result = checkValidSignedInteger( field, fieldName, mandatory );
    if (result) {
     if ( ((parseInt(field.value) >= min ) && (parseInt(field.value) <= max) ) || (field.value.length == 0) ) {
        return true;
      } else {
         mandatoryMessage +=  FIELD_ERROR + fieldName + RANGE_FORMAT_ERROR_1 + min + RANGE_FORMAT_ERROR_2 + max + RANGE_FORMAT_ERROR_3;
        return false;
      }
    } else {
      return result;
    }
}
/////////////////////////////////////
// FLOAT
/////////////////////////////////////

var reFloat = /^.+$/;
function checkFloat( field, fieldName )
{
    return checkWithFormat( field, fieldName, reFloat, FLOAT_FORMAT_ERROR, true );
}

function checkOptionalFloat( field, fieldName )
{
    return checkWithFormat( field, fieldName, reFloat, FLOAT_FORMAT_ERROR, false );
}


/////////////////////////////////////
// POSITIV FLOAT
/////////////////////////////////////
var rePositivFloat = /^\s*[+]?\s*\d+\.?\d*\s*$/;

function checkPositivFloat( field, fieldName )
{
    return checkWithFormat( field, fieldName, rePositivFloat, FLOAT_FORMAT_ERROR, true );
}

function checkOptionalPositivFloat( field, fieldName )
{
    return checkWithFormat( field, fieldName, rePositivFloat, FLOAT_FORMAT_ERROR, false );
}
/////////////////////////////////////
// SIGNED FLOAT
/////////////////////////////////////

//var reSignedFloat = /^.+$/;
var reSignedFloat = /^\s*-?\s*\d+\.?\d*\s*$/;

function checkSignedFloat( field, fieldName )
{
    return checkWithFormat( field, fieldName, reSignedFloat, SIGNED_FLOAT_FORMAT_ERROR, true );
}

function checkOptionalSignedFloat( field, fieldName )
{
    return checkWithFormat( field, fieldName, reSignedFloat, SIGNED_FLOAT_FORMAT_ERROR, false );
}

function checkValidSignedFloat( field, fieldName, mandatory)
{
    return checkWithFormat( field, fieldName, reSignedFloat, SIGNED_FLOAT_FORMAT_ERROR, mandatory );

}

function checkValidSignedFloatRange( field, fieldName, mandatory, min, max)
{
    // test du format et du caractère obligatoire
    result = checkValidSignedFloat( field, fieldName, mandatory );

    // test des bornes min et max
    if (result) {
     if ( ((parseFloat(field.value) >= min ) && (parseFloat(field.value) <= max)) || (field.value.length == 0) ) {
        return true;
      } else {
        mandatoryMessage +=  FIELD_ERROR + fieldName + RANGE_FORMAT_ERROR_1 + min + RANGE_FORMAT_ERROR_2 + max + RANGE_FORMAT_ERROR_3;
        return false;
      }
    } else {
      return result;
    }

}

/////////////////////////////////////
// DATE
/////////////////////////////////////

function checkDiffDate()
{
    var Form = this.document.formulaire;
    var ok = true;
    ok = checkDate( Form.DiffusionDebut, 'Date de debut de diffusion') && ok;
    ok = checkDate( Form.DiffusionFin, 'Date de fin de diffusion' ) && ok;
    ok = checkDate( Form.ArchivageFin, 'Date de fin d\'archivage' ) && ok;
    return ok;
}

function checkBODiffDate()
{
    var Form = document.formulaire;
    var ok = true;
    ok = checkDate( Form.DiffusionDebut, 'Date de debut de diffusion') && ok;
    ok = checkDate( Form.DiffusionFin, 'Date de fin de diffusion' ) && ok;
    ok = checkDate( Form.ArchivageFin, 'Date de fin d\'archivage' ) && ok;
    return ok;
}

function checkMandatoryField(titre,file)
{
   if (  (titre.value.length == 0) && (file.value.length > 0)  )
   {
     alert("Remplissez le champ obligatoire : Titre");
     return false;
   }
   else if (  (titre.value.length > 0) && (file.value.length == 0)  )
   {
     alert("Remplissez le champ obligatoire : Fichier");
     return false;
   }
   else if (  (titre.value.length == 0) && (file.value.length == 0)  )
   {
     alert("Remplissez les champs obligatoires : Titre & Document");
     return false;
   }
   return parseFileName(file.value);
}

function checkCriterii(_form,profondeur)
{
  var taille = eval(profondeur);
  var tabCriteria = new Array(taille);
  var result = 1;
  for (i = 1; i<=taille; i++)
  {
    if (eval("_form.Critere"+i)) {
      tabCriteria[i] = eval("_form.Critere"+i).selectedIndex;
    }else{
      tabCriteria[i] = 0; // il est non renseigné
    }
  }
  for (i=taille; i>0; i--)
  {
    if (tabCriteria[i] >0)
    {
      for (j=i;j>0;j--)
      {
        result *= tabCriteria[j];

      }
      if (result == 0)
      {
         mandatoryMessage += 'La complétude des critères choisis n\'est pas remplie.\n';
         return false;
      }
      return true;
    }
  }
  return true;
}
function checkAllCriterii(_form,profondeur)
{
  var taille = eval(profondeur);
  var tabCriteria = new Array(taille);
  var result = 1;
  for (i = 1; i<=taille; i++)
  {
    if (eval("_form.Critere"+i)) {
      tabCriteria[i] = eval("_form.Critere"+i).selectedIndex;
    } else {
      tabCriteria[i] = 0; // il est non renseigné
    }
  }
  //Testons la complétude de ts les critères
  for (i=taille; i>0; i--)
  {
    result *= tabCriteria[i];
//    alert(result + " / " + tabCriteria[i] +" / " +i);
  }
  if (result == 0)
  {
    mandatoryMessage += 'Les ' + taille + ' critères sont obligatoires.\n';
    return false;
  }
  return true;
}

// isTelephone (STRING s )
//
// Telephone number must be of form 0Z AB PQ MC DU
// where Z is a number between 1 and 8 a
// and ABPQMCDU are number between 0 and 9

var reTel = /^0[1-8] [0-9][0-9] [0-9][0-9] [0-9][0-9] [0-9][0-9]$/;
function isTelephone (s)

{
       //alert("12");
       return reTel.test(s);
}

function isTelephoneValid(telephone, fieldName ) {


  if (!isTelephone(telephone)) {
    mandatoryMessage += TEL_ERROR + fieldName + TEL_FORMAT_ERROR;
    return false;
  }
  return true;
}


function checkValidTelephone( field, fieldName, mandatory )
{


    if( checkField( field ) ){
        return isTelephoneValid( field.value, fieldName );
   }else{
        if( mandatory == true ){
            mandatoryMessage += FIELD_ERROR + fieldName + MANDATORY_ERROR;
            return false;
        }
    }
    return true;
}

function checkTelephone( field, fieldName )
{
    return checkValidTelephone( field, fieldName, true );
}

function checkOptionalTelephone( field, fieldName )
{
    return checkValidTelephone( field, fieldName, false );
}

// BOI, followed by one or more characters (excepté l'espace), followed by @,
// followed by one or more characters (excepté l'espace), followed by .,
// followed by one or more characters (excepté l'espace), followed by EOI.
var reEmail = /^\S+\@\S+\.\S+$/

// isEmail (STRING s )
//
// Email address must be of form a@b.c -- in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//

function isEmail (s)

{
       //alert("12");
       return reEmail.test(s);
}

function isEmailValid(email, fieldName ) {

  if (!isEmail(email)) {
    mandatoryMessage += EMAIL_ERROR + fieldName + EMAIL_UNEXIST_ERROR;
    return false;
  }
  return true;
}

function checkValidEmail( field, fieldName, mandatory )
{

    if( checkField( field ) ){
        return isEmailValid( field.value, fieldName );
   }else{
        if( mandatory == true ){
            mandatoryMessage += FIELD_ERROR + fieldName + MANDATORY_ERROR;
            return false;
        }
    }
    return true;
}

function checkEmail( field, fieldName )
{
    return checkValidEmail( field, fieldName, true );
}

function checkOptionalEmail( field, fieldName )
{
    return checkValidEmail( field, fieldName, false );
}





// BOI, followed by one or more characters, followed by @,
// followed by one or more characters, followed by .,
// followed by one or more characters, followed by EOI.
var reURL = /^.+:\/\/.+\..+$/

// isURL (STRING s )
//
// URL address must be of form a://b.c -- in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//

function isURL (s)

{
       //alert("12");
       return reURL.test(s);
}

function isURLValid(url, fieldName ) {

  if (!isURL(url)) {
    mandatoryMessage += URL_ERROR + fieldName + URL_FORMAT_ERROR;
    return false;
  }
  return true;
}

function checkValidURL( field, fieldName, mandatory )
{

    if( checkField( field ) ){
        return isURLValid( field.value, fieldName );
   }else{
        if( mandatory == true ){
            mandatoryMessage += FIELD_ERROR + fieldName + MANDATORY_ERROR;
            return false;
        }
    }
    return true;
}

function checkURL( field, fieldName )
{
    return checkValidURL( field, fieldName, true );
}

function checkOptionalURL( field, fieldName )
{
    return checkValidURL( field, fieldName, false );
}

function isDate (s) {
       return reDate.test(s);
}

function checkAlphaString(field, fieldName ) {
    return checkValidAlphaString( field, fieldName, true );
}

function checkOptionalAlphaString(field, fieldName ) {
    return checkValidAlphaString( field, fieldName, false );
}

function checkValidAlphaString(field, fieldName, mandatory ) {
    if( checkField( field ) ){
      return isAlphaStringValid( field.value, fieldName);
    }else{
      if( mandatory == true ){
        mandatoryMessage += FIELD_ERROR + fieldName + MANDATORY_ERROR;
        return false;
      }
    }
    return true;
}

var reAlphaString = /^[0-9a-zA-Z_]+$/ ;

function isAlphaString(s) {
    return reAlphaString.test(s);
}

function isAlphaStringValid(field, fieldName){
    if (!isAlphaString(field)) {
      mandatoryMessage += FIELD_ERROR + fieldName + ALPHA_STRING_FORMAT_ERROR;
      return false;
    }
    return true;
}

function isSameAndNotNull(s1, s2) {
    // la chaine s1 doit être définie et ne pas être vide.
       /*alert("13s1=-"+s1+ "- s2=-"+s2+"-");
        if (  (s1=="")) {
            alert("s1");
        }
        if (  (s2=="")) {
            alert("s2");
        }*/
    if ( (s1=="") && (s2=="") ) {
        return true;
    }else if ( (s1) && (s1 != "")) {
        // les deux chaines s1 et s2 doivent être identiques.
        if ( s1==s2 )
            return true;
        else
            return false;
    } else {
            return false;
    }
}


// pas compatible Netscape
function desactivateSectors(Secteurs)
{
    //var Secteurs = this.document.formulaire.Secteur; //passé en paramètre de fonction
    if( ! Secteurs.tagName ){
        // s'il n'y a qu'un seul element TagName est présent, ce n'est pas un tableau
        for( i = 0; i<Secteurs.length; ++i ){
            Secteurs[i].value = null;
        }
    }
}
function desactivateSectorsAndRegions(Secteurs, regionIndex)
{
    if( ! Secteurs.tagName ){
	for( i = 0; i<Secteurs.length; ++i ){
	    Secteurs[i].value = null;
	}
    }
    // Attention , RegId est le nom de linput de la region, idem ds la BD !!
    this.document.formulaire.RegId[regionIndex-1].click();
}

function openSmallWindow(url)
  {
    w = window.open(url, 'pop_up', 'toolbar=no ,location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, width=390,height=350,left=200,top=100');
    //width=450,height=400,left=200,top=100');
    w.focus();
  }
function openContactWindow(url) {
  fenetre=window.open(url,'_AIDE_CONTACT_','toolbar=yes ,location=yes, directories=yes, status=yes, menubar=yes, scrollbars=yes,resizable=yes');
  fenetre.focus();
}



/* Contrôle le choix dans une liste déroulante différent de '1 - NON RENSEIGNE' */
function checkSelect(field, fieldName)
{
    if( checkSignedInteger(field, fieldName) ) {
        fieldValue = parseInt(field.value);
        if ( fieldValue > 1 ) {
            return true;
        }
        else {
            mandatoryMessage += FIELD_ERROR + fieldName + MANDATORY_ERROR;
            return false;
        }
    }
}

//var modele=/\/|\&|\:|\@|\=|\$|\,|\-|\_|\.|\!|\~|\'|\;|'+'|'*'|'?'|'('|')'/;
//ne marche pas


/* Contrôle interdisant les caractères spéciaux
; / ? : @ & = + $ , - _ . ! ~ * ' ( )
*/
function checkSpecialCharacter( field, fieldName )
{
    var modele=new RegExp("\/|\&|\:|\=|\,|\-|\_|\!|\~|\'|\;|\\$|\\@|\\.|\\+|\\*|\\?|\\(|\\)");


   if(modele.test(field.value)){
            mandatoryMessage +='\n'+FIELD_ERROR + fieldName + WRONG_CHARACTER_ERROR_2;
            return false;
    }
    return true;
}

/* Contrôle interdisant le caractère %
*/
function checkPercentCharacter( field, fieldName )
{
    var modele=new RegExp("\%");


   if(modele.test(field.value)){
            mandatoryMessage +='\n'+FIELD_ERROR + fieldName + WRONG_PERCENT_CHARACTER_ERROR;
            return false;
    }
    return true;
}


/* Contrôle sur la somme doit être supérieure à un maximum */
function checkValidSignedFloatSum( sum, fieldName, max)
{   //alert ("somme = " + sum);
    // test de la somme > 0
    if ( parseFloat(sum) > max) {
        return true;
    } else {
        mandatoryMessage += '\n'+ fieldName + max;
        return false;
    }
}

/* Initialisation des champs à une valeur */
function initField( field, valInit)
{
    if (field.value.length==0)
    {
	field.value = valInit;
	return true;
    }
}


/* Traduit un format issu de la BD (ex: 999.99) en expression régulière */
function formatBDtoRegExp(formatBD)
{
    var formatRegExp = '^\\s*-?\\s*';
    var car = "";

    for( i = 0; i < formatBD.length; ++i ){
        car = formatBD.substring(i,i+1);
        if( car=="9")  {
            formatRegExp += '\\d?';
        } else if( car=="." || car=="," ){
            formatRegExp += '\\.?';
        }
    }
    formatRegExp += '\\s*$';

    var modele=new RegExp(formatRegExp);
    return modele;
}


//------------------------------------------------------------------------------------------
// Fonction qui supprime tous les caractères non alphabetiques d'une chaine "sourceString"
//-----------------------------------------------------------------------------------------

function trimURL(sourceString){
 var tmpStr="";
 tmpStr = new String(sourceString);
 tmpResult = new String();
 var re = new RegExp("[0-9a-zA-Z]{1}");
 for(var i=0;i<sourceString.length;i++){
 	if(tmpStr.charAt(i).match(re)){
 		tmpResult = tmpResult + tmpStr.charAt(i);
 	}
 }
 if (tmpResult.length<1){
   return "";
   }
 return tmpResult;
 }


 //------------------------------------------------------------------------------------------
 // La banque de document a une profondeur de critères inférieure au rang choisi
//-----------------------------------------------------------------------------------------
 /* Contrôle si une valeur est inférieure à un maximum */
 function checkValidIntegerMax( field, msg, max)
 {
	 // test de la valeur < max
     if ( field <= max) {
		 return true;
     } else {
	     mandatoryMessage += '\n'+ msg;
         return false;
     }
  }



/* Contrôle interdisant les caractères spéciaux (sauf - et _) pour la section URL
; / ? : @ & = + $ ,  . ! ~ * ' ( ) {[]}....
*/

function checkValidSectionURL(field, fieldName, mandatory ) {
    if( checkField( field ) ){
      return isSectionURLValid( field.value, fieldName);
    }else{
      if( mandatory == true ){
        mandatoryMessage += FIELD_ERROR + fieldName + MANDATORY_ERROR;
        return false;
      }
    }
    return true;
}

var reSectionURL = /^[0-9a-zA-Z_-]+$/ ;

function isSectionURL(s) {

    return reSectionURL.test(s);
}

function isSectionURLValid(field, fieldName){
    if (!isSectionURL(field)) {
      mandatoryMessage += FIELD_ERROR + fieldName + SECTION_URL_FORMAT_ERROR;
      return false;
    }
    return true;
}

// -------------------------------------------------------------------
// selectUnselectMatchingOptions(select_object,regex,select/unselect,true/false)
//  This is a general function used by the select functions below, to
//  avoid code duplication
// -------------------------------------------------------------------
function selectUnselectMatchingOptions(obj,regex,which,only) {
	if (window.RegExp) {
		if (which == "select") {
			var selected1=true;
			var selected2=false;
			}
		else if (which == "unselect") {
			var selected1=false;
			var selected2=true;
			}
		else {
			return;
			}
		var re = new RegExp(regex);
		for (var i=0; i<obj.options.length; i++) {
			if (re.test(obj.options[i].text)) {
				obj.options[i].selected = selected1;
				}
			else {
				if (only == true) {
					obj.options[i].selected = selected2;
					}
				}
			}
		}
	}
		
// -------------------------------------------------------------------
// selectMatchingOptions(select_object,regex)
//  This function selects all options that match the regular expression
//  passed in. Currently-selected options will not be changed.
// -------------------------------------------------------------------
function selectMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"select",false);
	}
// -------------------------------------------------------------------
// selectOnlyMatchingOptions(select_object,regex)
//  This function selects all options that match the regular expression
//  passed in. Selected options that don't match will be un-selected.
// -------------------------------------------------------------------
function selectOnlyMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"select",true);
	}
// -------------------------------------------------------------------
// unSelectMatchingOptions(select_object,regex)
//  This function Unselects all options that match the regular expression
//  passed in. 
// -------------------------------------------------------------------
function unSelectMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"unselect",false);
	}
	
// -------------------------------------------------------------------
// sortSelect(select_object)
//   Pass this function a SELECT object and the options will be sorted
//   by their text (display) values
// -------------------------------------------------------------------
function sortSelect(obj) {
	var o = new Array();
	for (var i=0; i<obj.options.length; i++) {
		o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
		}
	o = o.sort( 
		function(a,b) { 
			if ((a.text+"") < (b.text+"")) { return -1; }
			if ((a.text+"") > (b.text+"")) { return 1; }
			return 0;
			} 
		);

	for (var i=0; i<o.length; i++) {
		obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
		}
	}

// -------------------------------------------------------------------
// selectAllOptions(select_object)
//  This function takes a select box and selects all options (in a 
//  multiple select object). This is used when passing values between
//  two select boxes. Select all options in the right box before 
//  submitting the form so the values will be sent to the server.
// -------------------------------------------------------------------
function selectAllOptions(obj) {
	for (var i=0; i<obj.options.length; i++) {
		obj.options[i].selected = true;
		}
	}
	
// -------------------------------------------------------------------
// moveSelectedOptions(select_object,select_object[,autosort(true/false)[,regex]])
//  This function moves options between select boxes. Works best with
//  multi-select boxes to create the common Windows control effect.
//  Passes all selected values from the first object to the second
//  object and re-sorts each box.
//  If a third argument of 'false' is passed, then the lists are not
//  sorted after the move.
//  If a fourth string argument is passed, this will function as a
//  Regular Expression to match against the TEXT or the options. If 
//  the text of an option matches the pattern, it will NOT be moved.
//  It will be treated as an unmoveable option.
//  You can also put this into the <SELECT> object as follows:
//    onDblClick="moveSelectedOptions(this,this.form.target)
//  This way, when the user double-clicks on a value in one box, it
//  will be transferred to the other (in browsers that support the 
//  onDblClick() event handler).
// -------------------------------------------------------------------
function moveSelectedOptions(from,to) {
	// Unselect matching options, if required
	if (arguments.length>3) {
		var regex = arguments[3];
		if (regex != "") {
			unSelectMatchingOptions(from,regex);
			}
		}
	// Move them over
	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected) {
			to.options[to.options.length] = new Option( o.text, o.value, false, false);
			}
		}
	// Delete them from original
	for (var i=(from.options.length-1); i>=0; i--) {
		var o = from.options[i];
		if (o.selected) {
			from.options[i] = null;
			}
		}
	if ((arguments.length<3) || (arguments[2]==true)) {
		sortSelect(from);
		sortSelect(to);
		}
	from.selectedIndex = -1;
	to.selectedIndex = -1;
	}

// -------------------------------------------------------------------
//  addOptionFromTextInput(input_object, select_object)
//  This function inserts a new option in the list from a text input.
// -------------------------------------------------------------------

function addOptionFromTextInput(from, to) {
	
	if (from.value != '') {
		to.options[to.options.length] = new Option( from.value, from.value, false, false);
	}
}
	
// -------------------------------------------------------------------
//  removeSelectedOptions(select_object)
//  This function remove the selected options.
// -------------------------------------------------------------------

function removeSelectedOptions(obj) {
	for (var i=(obj.options.length-1); i>=0; i--) {
		var o = obj.options[i];
		if (o.selected) {
			obj.options[i] = null;
			}
		}		
	}	

// -------------------------------------------------------------------
//  removeSelectedOptionsAfterCheck(select_object, select_object)
//  This function remove the selected options after checking that
//  the option does not exist in another list
// -------------------------------------------------------------------

function removeSelectedOptionsAfterCheck(obj1, obj2) {
	var options = new Object();
	var warning = false;
	
	for (var i=0; i<obj2.options.length; i++) {
		options[obj2.options[i].text] = true;
	}
		
	for (var i=0; i<obj1.options.length; i++) {
		var o = obj1.options[i];
		if (o.selected) {
			if (options[o.text] == null || options[o.text] == "undefined") {
				obj1.options[i] = null;
			} else {
				warning = true;				
			}
		}
	}	
		
	if (warning == true) {
		alert("Une ou plusieurs options n'ont pu être supprimées car elles sont définies comme valeurs par défaut.\n");
	}		
		
}

// -------------------------------------------------------------------
// copySelectedOptions(select_object,select_object[,autosort(true/false)])
//  This function copies options between select boxes instead of 
//  moving items. Duplicates in the target list are not allowed.
// -------------------------------------------------------------------
function copySelectedOptions(from,to) {
	var options = new Object();
	for (var i=0; i<to.options.length; i++) {
		options[to.options[i].text] = true;
		}
	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected) {
			if (options[o.text] == null || options[o.text] == "undefined") {
				to.options[to.options.length] = new Option( o.text, o.value, false, false);
				}
			}
		}
	if ((arguments.length<3) || (arguments[2]==true)) {
		sortSelect(to);
		}
	from.selectedIndex = -1;
	to.selectedIndex = -1;
	}

// -------------------------------------------------------------------
//  copySelectedOptionToInputText(select_object, input_object)
//  This function updates a text input from a select box
// -------------------------------------------------------------------

function copySelectedOptionToInputText(from,to) {

	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected) {
			to.value = o.text;
			}
		}
	}

// -------------------------------------------------------------------
// moveAllOptions(select_object,select_object[,autosort(true/false)[,regex]])
//  Move all options from one select box to another.
// -------------------------------------------------------------------
function moveAllOptions(from,to) {
	selectAllOptions(from);
	if (arguments.length==2) {
		moveSelectedOptions(from,to);
		}
	else if (arguments.length==3) {
		moveSelectedOptions(from,to,arguments[2]);
		}
	else if (arguments.length==4) {
		moveSelectedOptions(from,to,arguments[2],arguments[3]);
		}
	}

// -------------------------------------------------------------------
// copyAllOptions(select_object,select_object[,autosort(true/false)])
//  Copy all options from one select box to another, instead of
//  removing items. Duplicates in the target list are not allowed.
// -------------------------------------------------------------------
function copyAllOptions(from,to) {
	selectAllOptions(from);
	if (arguments.length==2) {
		copySelectedOptions(from,to);
		}
	else if (arguments.length==3) {
		copySelectedOptions(from,to,arguments[2]);
		}
	}

// -------------------------------------------------------------------
// swapOptions(select_object,option1,option2)
//  Swap positions of two options in a select list
// -------------------------------------------------------------------
function swapOptions(obj,i,j) {
	var o = obj.options;
	var i_selected = o[i].selected;
	var j_selected = o[j].selected;
	var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
	var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);
	o[i] = temp2;
	o[j] = temp;
	o[i].selected = j_selected;
	o[j].selected = i_selected;
	}
	
// -------------------------------------------------------------------
// moveOptionUp(select_object)
//  Move selected option in a select list up one
// -------------------------------------------------------------------
function moveOptionUp(obj) {
	// If > 1 option selected, do nothing
	var selectedCount=0;
	for (i=0; i<obj.options.length; i++) {
		if (obj.options[i].selected) {
			selectedCount++;
			}
		}
	if (selectedCount > 1) {
		return;
		}
	// If this is the first item in the list, do nothing
	var i = obj.selectedIndex;
	if (i <= 0) {
		return;
		}
	swapOptions(obj,i,i-1);
	obj.options[i-1].selected = true;
	}

// -------------------------------------------------------------------
// moveOptionDown(select_object)
//  Move selected option in a select list down one
// -------------------------------------------------------------------
function moveOptionDown(obj) {
	// If > 1 option selected, do nothing
	var selectedCount=0;
	for (i=0; i<obj.options.length; i++) {
		if (obj.options[i].selected) {
			selectedCount++;
			}
		}
	if (selectedCount > 1) {
		return;
		}
	// If this is the last item in the list, do nothing
	var i = obj.selectedIndex;
	if (i == (obj.options.length-1)) {
		return;
		}
	swapOptions(obj,i,i+1);
	obj.options[i+1].selected = true;
	}


function addChildInputComponent( child ){
    this.listOfChild[ this.listOfChild.length ] = child;
    return;
}

function checkInputComponent(){
    var ro = (!this.self.checked) || this.self.disabled;
    var child = null;
    for( var i=0; i< this.listOfChild.length; ++i ){
        child = this.listOfChild[i];
        if( child.tagName == 'TABLE'){
            child.className = ro ? 'info-admin-fond' : 'cadre-t-synthese';
        }else{
            if( child.self ){
                child.self.disabled = ro;
                child.check();
            }else{
                child.disabled = ro;
                if( (child.type!='radio') && (child.type!='checkbox') ){
                    child.className = ro ? 'READONLY' : null;
                }
            }
        }
    }
    return;
}

function CheckboxMaster( checkbox ){
    this.listOfChild = new Array(0);
    this.self = checkbox;
    this.addChild = addChildInputComponent;
    this.check = checkInputComponent;
    return this;
}

function openWindow(url){
    openNewScrollWindow( url );
}

function openNewScrollWindow(url)
{
    w = window.open(url, 'pop_up'+new Date().getTime(), 'toolbar=no ,location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes');
    w.focus();
}

function openNewSizedScrollWindow(url, width, height)
{
    w = window.open(url, 'pop_up'+new Date().getTime(), 'toolbar=no ,location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width='+width+', height='+height );
    w.focus();
}

function openContactWindow(url) {
  fenetre=window.open(url,'_AIDE_CONTACT_','toolbar=yes ,location=yes, directories=yes, status=yes, menubar=yes, scrollbars=yes,resizable=yes');
  fenetre.focus();
}
     
function openScrollWindow(url) {
    fenetre=window.open(url,'pop_up'+new Date().getTime(),'toolbar=yes ,location=yes, directories=yes, status=yes, menubar=yes, scrollbars=yes,resizable=yes');
    fenetre.focus();
}
    

function retourPageAppelante( url) {
	opener.location=url;
	self.close();
 }	


