/************************************/
/* lineSplit(strSource,splitLength) */
/************************************/
/* Split un texte en x lignes séparées par \n 
 * strSource : le texte source
 * splitLength : la longueur des lignes
 */
function lineSplit(strSource,splitLength){
  if (strSource.length>splitLength){
    return trim(strSource.substr(0,splitLength))+"\r"+lineSplit(strSource.substr(splitLength),splitLength)
  } else { return trim(strSource); }
}

/**********************/
/* correctTa(taField) */
/**********************/
/* Corrige le bug du sigle $ en IMS
 * o : le textarea à corriger
 * <textarea name="LTIDMEM" onKeyUp="correctTa(document.form_mf.LTIDMEM);">
 */
function replaceChar(s, o, n) {
  var newString = "";
  for (i = 0; i < s.length; i++) {
    if (s.charAt(i) == o) newString += n;
    else newString += s.charAt(i);
  }
  return newString;
}
var ILLEGAL_CHARS = "$,<,>";
var REPLACEMENT_CHARS = "dollar,<,>";
function correctTa(o) {
  var text = o.value;
  var ic = ILLEGAL_CHARS.split(",");
  var rc = REPLACEMENT_CHARS.split(",");
  for (i = 0; i < ic.length; i++) {
    if (text.indexOf(ic[i]) != -1) text = replaceChar(text, ic[i], rc[i]);
  }
  if (text != o.value) o.value = text;
  return true;
}

function f_guidance(zoneAGuider) {
  document.form_mf.CDOPTRN.value = " ";
  zoneAGuider.value = "?";
  document.form_mf.submit();

}
/*****************************/
/* switchDiv(dDiv,dispMode) */
/*****************************/
/* dDiv : the div to show/hide
 * dispMode:
 *   on / block  - show
 *   off / none  - hide
 *
 */

function switchDiv(dDiv, dispMode) {
  // dispMode=="on"?document.getElementById(dDiv).style.visibility='visible':document.getElementById(dDiv).style.visibility='hidden'
  switch (dispMode) {
  case "none":
    document.getElementById(dDiv).style.display = "none";
    break;
  case "block":
    document.getElementById(dDiv).style.display = "block";
    break;
  case "on":
    document.getElementById(dDiv).style.visibility = 'visible';
    break;
  default:
    document.getElementById(dDiv).style.visibility = 'hidden';
    break;
  }
}

/*****************************/
/* getAgeFromDate(dd,mm,yy,currentDay,currentMonth,currentYear) */
/*****************************/
/* Donne l'age en annee en fonction de la date passee en parametre.
 * S'assurer que la date est correcte avant d'appeler cette fonction.
 */

function getAgeFromDate(dd, mm, yy, currentDay, currentMonth, currentYear) {
  /*
    days = new Date();
    gdate = days.getDate();
    gmonth = days.getMonth();
    gyear = days.getYear();
    alert(gdate +" " +gmonth+" "+gyear);
    suppression de la date courante du pc par une date recue en parametre
    */
  gdate = currentDay;
  gmonth = currentMonth - 1;
  gyear = currentYear;

  age = gyear - yy;

  if ((mm == (gmonth + 1)) && (dd <= parseInt(gdate))) {
    age = age;
  }
  else {
    if (mm <= (gmonth)) {
      age = age;
    }
    else {
      age = age - 1;
    }
  }
  return age;
}

/**********************************************/
/* Change la class d'un element               */
/**********************************************/
function changeClass(Elem, myClass) {
  var elem;
  if (document.getElementById) {
    elem = document.getElementById(Elem);
  } else if (document.all) {
    elem = document.all[Elem];
  }
  elem.className = myClass;
}

/**********************************************/
/* Fait un submit avec une valeur mid.CLE     */
/**********************************************/
function sendKey(theKey) {
  document.form_mf.CDOPTRN.value = " ";
  document.form_mf.CLE.value = theKey;
  document.form_mf.submit();
}

/**********************************************/
/* Mets le focus sur le premier champs        */
/* ex: initFocus("document.myForm.myField");  */
/**********************************************/
function initFocus(myFirstField) {
  eval(myFirstField + ".focus();");
}

/**************************************/
/* Tabulation automatique IE-Netscape */
/**************************************/
/* Usage:
 * <INPUT TYPE="text" size="2" MAXLENGTH="2" name="DANAIJJ" onKeyUp="return autoTab(this,DANAIMM, 2);">
 * <INPUT TYPE="text" size="2" MAXLENGTH="2" name="DANAIMM">
 */

if (window.Event)
/* Pour netscape 4 */
{
  document.captureEvents(Event.KEYPRESS);
}
function autoTab(obj, nextobj, mlength) {
  /*if (autoTab.arguments.length == 2)
      mlength=obj
      a terminer :-D */
  if (!mlength) {
    mlength = obj.size;
  }
  if (obj.value.length >= mlength) {
    obj.value = obj.value.substr(0, mlength);
    nextobj.focus();
  }
}

/*******************************************/
/* Gestion des ROLL-OVER                   */
/*******************************************/

function img_act(imgName) {   
  imgOn = eval(imgName + "on.src");
  document[imgName].src = imgOn;
}

function img_inact(imgName) {
  imgOff = eval(imgName + "off.src");
  document[imgName].src = imgOff;
}

/********************************************************************************************/
function IsNumeroNational(string) {
  var temp;
  var module;
  var chiffre;
  temp = string;
  if (temp.length != 11) return (false);
  chiffre = temp.substring(0, 9);
  module = temp.substring(9, 11);
  if (chiffre % 97 == (97 - module)) return (true);
}
/********************************************************************************************/

function getQueryStringVal(lQuery) {
  var lDoc = String(document.location);
  var lSignet = "-1";
  var n1 = lDoc.indexOf("?");

  if (n1 > 0) {
    var n2 = lDoc.indexOf("?" + lQuery + "=", n1);
    if (n2 < n1) n2 = lDoc.indexOf("&" + lQuery + "=", n1);
    if (n2 >= n1) {
      n2 = n2 + ("?" + lQuery + "=").length;
      var n3 = lDoc.indexOf("&", n2 + 1);
      if (n3 > n2) lSignet = lDoc.substring(n2, n3);
      else lSignet = lDoc.substring(n2);
    }
  }
  return lSignet;
}

function getQueryStringLikeVal(lDocShort,lQuery) {
  var lDoc = "dummy?"+lDocShort;
  var lSignet = "-1";
  var n1 = lDoc.indexOf("?");

  if (n1 > 0) {
    var n2 = lDoc.indexOf("?" + lQuery + "=", n1);
    if (n2 < n1) n2 = lDoc.indexOf("&" + lQuery + "=", n1);
    if (n2 >= n1) {
      n2 = n2 + ("?" + lQuery + "=").length;
      var n3 = lDoc.indexOf("&", n2 + 1);
      if (n3 > n2) lSignet = lDoc.substring(n2, n3);
      else lSignet = lDoc.substring(n2);
    }
  }
  return lSignet;
}
/********************************************************************************************/

function isEmailAdr(email) {
  var result = false;
  var theStr = new String(email);
  var index = theStr.indexOf("@");
  if (index > 0) {
    var pindex = theStr.indexOf(".", index);
    if ((pindex > index + 1) && (theStr.length > pindex + 1)) result = true;
  }
  return result;
}

/********************************************************************************************/

function remplace(expr, a, b) {
  var i = 0;
  while (i != -1) {
    i = expr.indexOf(a, i);
    if (i >= 0) {
      expr = expr.substring(0, i) + b + expr.substring(i + a.length);
      i += b.length;
    }
  }
  return expr;
}

/********************************************************************************************/

function couperMots(texte, lgMax) {
  var posit = 0;
  var lgMot = 0;
  var part1 = "";
  var part2 = "";
  while (posit < texte.length) {
    if (texte.substr(posit, 1) == ' ' || texte.substr(posit, 1) == '\n') {
      lgMot = 0;
    } else {
      lgMot = lgMot + 1;
      if (lgMot >= lgMax) {
        //ajout d'un blanc
        part1 = texte.substr(0, posit);
        part2 = texte.substr(posit, texte.length - posit);
        texte = part1 + " " + part2;
        lgMot = 0;
      } //end if
    } //end if
    posit = posit + 1;
  } //end while
  return texte;
} //end function
/********************************************************************************************/

// ============================================================================
// nvl(number) : Returns 0 if value is null or value itself if not
//
// PURPOSE: Avoid null values in arithmetic operations
// IN: aNumberValue - the number to check
// RETVAL: number
// ============================================================================
function nvl(aNumberValue) {
  if (aNumberValue == '' || aNumberValue == null) {
    return 0;
  } else {
    return aNumberValue;
  }
}

// ===============================================================================================
// checkNumber(field) : check if field value is a number and focus the field with a warning if not
//
// PURPOSE: Check value of number fields
// IN: aField - the name of the field containing the number
// RETVAL: true/false
// ===============================================================================================
function checkNumber(aField, errMsg) {
  if (isNaN(aField.value)) {
    alert(errMsg);
    aField.value = '';
    aField.focus();
    return false;
  }
  return true;
}

// ----------------------------------
// isEmpty (s)
// ----------------------------------
// Retourne true si le champ s est vide.
function isEmpty(s) {
  return ((s == null) || (s.length == 0));
}

// ----------------------------------
// isInteger2 (s [,eok])
// ----------------------------------
// Retourne true si tous les caracteres du champ s sont des chiffres.
function isInteger2(s) {
  var i;

  if (isEmpty(s)) {
    if (isInteger2.arguments.length == 1) {
      return (false);
    } else {
      return (isInteger2.arguments[1] == true);
    }
  }

  for (i = 0; i < s.length; i++) {
    var c = s.charAt(i);
    if ((c < "0") || (c > "9")) return (false);
  }

  return (true);
}

// ----------------------------------
// addDecimal(myField)
// ----------------------------------
// Ajoute ",00" si necessaire
// Remplace le "." par un "," si necessaire
// IN:  Le champs a corriger (ex: document.monForm.monChamps)
// OUT: Rien. Le champs est corrige
function addDecimal(myField) {
  //On remplace "." par "," si besoin
  if (myField.value.indexOf('.') != -1) {
    myField.value = myField.value.replace('.', ',');
  }

  //Si pas de "," et qu'il y a qque chose dans le champs, on ajoute ",00"
  if (myField.value.indexOf(',') == -1 && myField.value.length > 0) {
    myField.value = myField.value + ',00';
  }
}

// ----------------------------------
// isRadioChecked(myField,errMsg)
// ----------------------------------
// Verifie si on a bien coche *un des radio* du champs
// IN:  Le radio a tester (ex: document.monForm.monRadio)
//      Le message d'erreur
// OUT: True si on a coche une case
//      False sinon + alert de "errMsg"
// IMPORTANT: les radio de longueur 1 (une seule case) posent probleme avec ce genre de script (myField.length)!!!
function isRadioChecked(myField, errMsg) {
  //On boucle sur le nombre de case
  for (i = 0; i < myField.length; i++) {
    //On teste si la case en cours est cochee
    if (myField[i].checked == true) {
      //Si oui
      return true;
    }
  }
  //Si non
  if (errMsg.length > 0) alert(errMsg);
  return false;
}

// ----------------------------------
// unCheck(myField)
// ----------------------------------
// Decoche tous les champs d'un radio
// IN:  Le radio a decocher
// IMPORTANT: les radio de longueur 1 (une seule case) posent probleme avec ce genre de script (myField.length)!!!
function unCheck(myField) {
  //On boucle sur le nombre de case
  for (i = 0; i < myField.length; i++) {
    //On decoche
    myField[i].checked = false;
  }
  return;
}

// ----------------------------------
// isSelected(myField,errMsg)
// ----------------------------------
// Verifie si on a bien choisi une option avec valeur != "" dans un <SELECT>
// IN:  Le select a tester (ex: document.monForm.monSelect)
//      Le message d'erreur
// OUT: True si on a choisi une option valable
//      False sinon + alert de "errMsg"
function isSelected(myField, errMsg) {
  if (myField[myField.selectedIndex].value == "") {
    myField.focus();
    if (errMsg.length > 0) alert(errMsg);
    return false;
  }
  return true;
}

/*****************************************/
/* function checkTel(myField,errMsg,eOk) */
/**************************************************************/
/* Verifie la validite d'un numero de telephone ==>           */
/* Enleve tout les caracteres toleres sauf le '/'             */
/* eOk = empty is ok?                                         */
/**************************************************************/
function checkTel(myField, errMsg, eOk) {
  theNum = myField.value;

  //On enleve les caracteres autorises mais inutiles
  theNum = compact(theNum, ' ');
  theNum = compact(theNum, '.');
  theNum = compact(theNum, '-');
  theNum = compact(theNum, '(');
  theNum = compact(theNum, ')');

  //On s'assure qu'il n'y a pas plus d'un slash. Si oui on le laisse, si non, on les vires
  if (charCount(theNum, '/') > 1) theNum = compact(theNum, '/');

  //Une fois tout compacte, on verifie la longueur du numero et si c'est bien une chaine numerique uniquement ainsi que si c'est vide, si on doit retourner une erreur ou pas :-D
  lTheNum = theNum.length;

  if ((((lTheNum == 9) || (lTheNum == 10) || (lTheNum == 11)) && (isNumeric(compact(theNum, '/')))) || ((lTheNum == 0) && (eOk == true))) {
    myField.value = theNum;
    return true;
  }
  else {
    myField.focus();
    myField.select();

    if (errMsg.length > 0) alert(errMsg);

    return false;
  }
}

/***************************************/
/* function compact(theString,theChar) */
/**************************************************************/
/* Enleve toutes les occurences de "theChar" dans "theString" */
/* Ex: compact("Hello world!",'o'); --> "Hell wrld!"          */
/* Case sensitive !!!                                         */
/**************************************************************/
function compact(theString, theChar) {
  var charPos;
  charPos = theString.indexOf(theChar);
  if (charPos != -1) {
    return theString.substring(0, charPos) + compact(theString.substring(charPos + 1), theChar);
  }
  else {
    return theString;
  }
}

/*****************************************/
/* function charCount(strString,chrChar) */
/**************************************************************/
/* Compte le nombre d'occurence de chrChar dans strString     */
/* Ex: charCount("Hello world!",'o'); --> 2                   */
/* Case sensitive !!!                                         */
/**************************************************************/
function charCount(strString, chrChar) {
  var cpt = 0;
  for (i = 0; i < strString.length; i++) {
    if (strString.charAt(i) == chrChar) cpt++;
  }
  return cpt;
}

/******************************/
/* function checkEmail(myField, errMsg) */
/********************************************************************/
/* Renvoi true si email est une adresse e-mail qui a l'air correcte */
/********************************************************************/
function checkEmail(myField, errMsg) {
  //on vire les eventuels espaces
  myField.value = compact(myField.value, " ");

  //et on check
  var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
  if (filter.test(myField.value)) {
    return true;
  }
  else {
    myField.focus();
    myField.select();

    if (errMsg.length > 0) alert(errMsg);

    return false;
  }
}

/*****************************************/
/* function isNumeric(strString)         */
/**************************************************************/
/* Verifie si strString est numerique                         */
/* strValidChars est la liste des characteres acceptes        */
/**************************************************************/
function isNumeric(strString)
//  check for valid numeric strings
{
  var strValidChars = "0123456789.-";
  var strChar;
  var blnResult = true;

  if (strString.length == 0) return false;

  //  test strString consists of valid characters listed above
  for (i = 0; i < strString.length && blnResult == true; i++) {
    strChar = strString.charAt(i);
    if (strValidChars.indexOf(strChar) == -1) {
      blnResult = false;
    }
  }
  return blnResult;
}

// ---------------------------------------------
// function checkField(myField,errMsg,isAmount)
// ---------------------------------------------
// Verifie si un champs obligatoire est remplis. Affiche errMsg sinon. Ajoute ",00" si isAmout == true
// IN:  Le champs obligatoire (ex: document.monForm.monChamps)
//      Le message d'erreur
//      true s'il faut ajouter ",00"
// OUT: True si le champs est ok
//      False sinon + alert de "errMsg"
function checkField(myField, errMsg, isAmount) {
  if (myField.value == "") {
    myField.focus();
    myField.select();
    if (errMsg.length > 0) alert(errMsg);
    return false;
  }
  if (isAmount) {
    //on vire les blancs
    myField.value = compact(myField.value, ' ');
    //on verifie si on a pas de caractere non admis ex:a,z,e,r,t,*,-, ...
    if (!checkEuro(myField)) {
      if (errMsg.length > 0) {
        myField.focus();
        myField.select();
        alert(errMsg);
      }
      return false;
    }
    //addDecimal(myField);
  }
  return true;
}

function checkEuro(ZoneName) {
  /* Un nombre bien forme ressemble a
         *  10.000,00
         *  10000,00
         *  10000
         * et pas a
         *  10000.00
         * Le resultat doit devenir de type
         * 10000,00
         * 10000,00
         * 10000
         */
  var putComma = 1;
  /* Si putComma = 1 alors on ajoute ",00" meme si l'utilisateur n'a rien entre */
  var Element = new Array(12)
  Element[0] = "0";
  Element[1] = "1";
  Element[2] = "2";
  Element[3] = "3";
  Element[4] = "4";
  Element[5] = "5";
  Element[6] = "6";
  Element[7] = "7";
  Element[8] = "8";
  Element[9] = "9";
  Element[10] = ",";
  Element[11] = ".";
  var StrOk = "";
  var Car = "";
  var tmp = "";
  var Comma = 0;
  var points = 0;
  var temp = 0;
  var CommaPos = -1;
  var part1 = "";
  var part2 = "";

  for (var i = 0; i < ZoneName.value.length; i++) {
    Car = ZoneName.value.substring(i, i + 1);
    if (ZoneName.value.substring(i, i + 1) == ",") Comma = Comma + 1;
    /* determine the number of commas */
    if (ZoneName.value.substring(i, i + 1) == ".") points = points + 1;
    /* determine the number of points */

    for (var counter = 0;
    (counter < 12); counter++) {
      if (Car == Element[counter]) tmp = tmp + "Y";
      /* Is the element a valid caracter of the array */
    }
    StrOk = StrOk + "Y";
  }
  if ((StrOk != tmp) || (Comma > 1)) {
    ZoneName.focus();
    return false;
  }

  /* S'il y a une virgule, on isole la partie entiere dans part1 */
  /* et la partie fractionnaire dans part2 */
  if (Comma == 1) {
    putComma = 1;
    CommaPos = Scan(ZoneName.value, ',');
    part1 = ZoneName.value.substring(0, CommaPos);
    part2 = ZoneName.value.substring(CommaPos + 1, ZoneName.value.length);

    if (part2.length > 2) {
      //alert("Veuillez entrer un maximum de 2 decimales!");
      //return("error");
      return false;
    }
    else if (part2.length == 1) {
      part2 = part2 + "0";
    }
    else if (part2.length == 0) {
      part2 = part2 + "00";
    }
  }
  /* Si pas de virgule, part2 = "00" et on verifie si le montant n'est pas trop grand */
  else if (Comma == 0) {
    part2 = "00";
    /*if (ZoneName.value.length > ZoneLength-3)
                {
                  alert("Le montant introduit est incorrect (1)");
                  ZoneName.focus();
                  return("error");
                }
              */
    part1 = ZoneName.value;
  }
  else {
    //alert("Le montant introduit est incorrect (2)");
    ZoneName.focus();
    //return("error");
    return false;
  }

  /* On regarde si la partie entiere contient des "." ou pas si oui on les enleves */
  if (points == 1) {
    /* un point, on regarde si c'est bien formatte */
    var pointPos = Scan(part1, '.');
    var sPart1 = part1.substring(0, pointPos);
    var sPart2 = part1.substring(pointPos + 1, part1.length);

    if (sPart2.length == 3) {
      /* ex: 10.000 */
      part1 = "" + sPart1 + sPart2;
    }
    else if ((sPart2.length == 2) && (Comma == 0)) {
      /* ex: 10000.50 */
      part1 = sPart1;
      part2 = sPart2;
    }
    else {
      //alert("Le montant introduit est incorrect (3)");
      ZoneName.focus();
      //return("error");
      return false;
    }

  }
  else if ((points > 1)) {
    /* Plus d'un point le montant est incorrect ou trop grand */
    //alert("Le montant introduit est incorrect (4)");
    ZoneName.focus();
    //return("error");
    return false;
  }

  if (part2 == "00" && putComma == 0) ZoneName.value = "" + part1;
  else {
    if (part1 == "") {
      part1 = "0";
    }
    ZoneName.value = "" + part1 + "," + part2;
  }

  return true;
}

function Scan(string, caracter) {
  /* Utilise dans checkeuro !! */
  var temp;
  var i = 0;
  var car = "e";

  if (string == "") return (true);

  temp = string;
  j = string.length;

  for (i = 0; i < j; i++) {
    car = temp.substring(i, i + 1);
    if (car == caracter) return (i);
  }

  return ( - 1);
}

/********************************************/
/* function isInteger(myField,errMsg[,eOk]) */
/********************************************/
/* Renvoie true:
 *  si la valeur du champs 'myField' est un nombre
 *  si le champs est vide ET que 'eOk' == true
 *  false sinon
 */

function isInteger(myField, errMsg) {

  s = myField.value; //recupere la valeur du champs
  s = trim(s);
  if (isEmpty(s)) {
    if (isInteger.arguments.length == 2) {
      alert(errMsg);
      myField.focus();
      return (false);
    } else {
      return (isInteger.arguments[2] == true);
    }
  }

  for (var i = 0; i < s.length; i++) {
    var c = s.charAt(i);
    if ((c < "0") || (c > "9")) {
      myField.focus();
      alert(errMsg);
      return (false);
    }
  }

  return (true);
}

function isEmpty(s) {
  return ((s == null) || (s.length == 0));
}

// ----------------------------------
// function checkEmptyDate(myFields[,errMsg])
// ----------------------------------
// Verifie si les champs d'une date sont bien remplis
// IN:  Une *chaine* contenant le debut du nom des champs contenant le jour, mois, annee
//      exemple: DANAIJJ, DANAIMM, DANAIYY ==> "DANAI"
//      Le message d'erreur
// OUT: True si les champs de la date ne sont pas vide
//      False sinon + alert de "errMsg" + mise a blanc des champs
function checkEmptyDate(myFields, errMsg) {
  myDay = eval(myFields + "JJ");
  myMonth = eval(myFields + "MM");
  myYear = eval(myFields + "AA");
  if ((myDay.value == "") || (myMonth.value == "") || (myYear.value == "")) {
    myDay.focus();
    if (errMsg.length > 0) alert(errMsg);
    return false;
  }
  return true;
}

// ----------------------------------
// function checkDate(myFields[,errMsg])
// ----------------------------------
// Verifie si une date est valide
// IN:  Une *chaine* contenant le debut du nom des champs contenant le jour, mois, annee
//      exemple: DANAIJJ, DANAIMM, DANAIYY ==> "DANAI"
//      Le message d'erreur
// OUT: True si la date est ok
//      False sinon + alert de "errMsg" + mise a blanc des champs
function WRONGcheckDate(myFields, errMsg) {
  myDay = eval(myFields + "JJ");
  myMonth = eval(myFields + "MM");
  myYear = eval(myFields + "AA");

  var testDate = new Date(myYear.value, myMonth.value, myDay.value); //on cree une date en via le constructeur javascript
  var testAnnee = testDate.getYear();
  if ((Math.abs(testAnnee) + "").length < 4) testAnnee = testAnnee + 1900; //on ajuste l'annee qui n'est pas toujours a la bonne longueur a cause du bug de l'an 2000
  validDate = ((testDate.getDate() == myDay.value) && (testDate.getMonth() == myMonth.value) && (testAnnee == myYear.value)); //si la date generee est la meme que la date entree, c'est une date valide!
  if (!validDate) {
    myDay.focus();
    if (errMsg.length > 0) alert(errMsg);
    myDay.value = "";
    myMonth.value = "";
    myYear.value = "";
    return false;
  }
  return true;
}

function checkDate(myFields, errMsg) {
  myDay = eval(myFields + "JJ");
  myMonth = eval(myFields + "MM");
  myYear = eval(myFields + "AA");

  //var errMsg="Veuillez entrer une date valide...";
  if (checkDate.arguments.length == 2) {
    errMsg = checkDate.arguments[1]
  } else {
    errMsg = "";
  }

  //Test si pas de champs vide
  //!!!Attention au "defaults" de la fonction isDate...
  if ((myDay.value == "") || (myMonth.value == "") || (myYear.value == "")) {
    if (errMsg.length > 0) alert(errMsg);
    myDay.focus();
    return false;
  }

  //Test date
  if (!isDate(myDay.value, myMonth.value, myYear.value)) {
    myDay.focus();
    if (errMsg.length > 0) alert(errMsg);
    myDay.value = "";
    myMonth.value = "";
    myYear.value = "";
    return false;
  }
  return true;
}

/********************************************/
/* function isDate (day,month,year)         */
/********************************************/
/* Renvoie true:
 *  si la date est bonne :-D
 *  false sinon
 */
/*
function y2k(number) { return (number < 1000) ? number + 1900 : number; }
function isDate (day,month,year) {
  */
// checks if date passed is valid
// will accept dates in following format:
// isDate(dd,mm,ccyy), or
// isDate(dd,mm) - which defaults to the current year, or
// isDate(dd) - which defaults to the current month and year.
// Note, if passed the month must be between 1 and 12, and the
// year in ccyy format.
/*    var today = new Date();
    year = ((!year) ? y2k(today.getYear()):year);
    month = ((!month) ? today.getMonth():month-1);
    if (!day) return false
    var test = new Date(year,month,day);
    if ( (y2k(test.getYear()) == year) &&
         (month == test.getMonth()) &&
         (day == test.getDate()) )
        return true;
    else
        return false
}
*/
// ----------------------------------
// ***OLD*** isDate	(dd, mm, yyyy)
// ----------------------------------
// Retourne true si la date est valide.
function isDate(dd, mm, yyyy) {
  if (!isInteger2(dd) || !isInteger2(mm) || !isInteger2(yyyy)) {
    return (false);
  }

  if (dd < 1 || dd > 31) {
    return (false);
  }
  if (mm < 1 || mm > 12) {
    return (false);
  }
  if ((yyyy.toString()).length != 4) {
    return (false);
  }
  if ((mm == 4 || mm == 6 || mm == 9 || mm == 11) && dd == 31) {
    return (false);
  }

  if (mm == 2) {
    var isleap = (yyyy % 4 == 0 && (yyyy % 100 != 0 || yyyy % 400 == 0));
    if (dd > 29 || (dd == 29 && !isleap)) {
      return false;
    }
  }

  return (true);
}

// ----------------------------------
// getStandardDate(dd, mm, yyyy)
// ----------------------------------
// Retourne une date au format standard (yyyymmdd).
function getStandardDate(dd, mm, yyyy) {
  if (!isDate(dd, mm, yyyy)) {
    return (false);
  } else {
    if ((dd.toString()).length == 1) {
      dd = '0' + dd;
    }
    if ((mm.toString()).length == 1) {
      mm = '0' + mm;
    }

    return (yyyy.toString() + mm.toString() + dd.toString());
  }
}

// ----------------------------------
// getStandardHour(ss, mm, hh)
// ----------------------------------
// Retourne une heure au format standard (hhmmss).
function getStandardHour(ss, mm, hh) {
  if (!isSecond(ss) || !isMinute(mm) || !isHour(hh)) {
    return (false);
  } else {
    if ((ss.toString()).length == 1) {
      ss = '0' + ss;
    }
    if ((mm.toString()).length == 1) {
      mm = '0' + mm;
    }
    if ((hh.toString()).length == 1) {
      hh = '0' + hh;
    }

    return (hh.toString() + mm.toString() + ss.toString());
  }
}

// ----------------------------------
// isSecond(ss)
// ----------------------------------
//
function isSecond(ss) {
  return (! ((ss < 0) || (ss > 60)))
}

// ----------------------------------
// isMinute(mm)
// ----------------------------------
//
function isMinute(mm) {
  return (! ((mm < 0) || (mm > 60)))
}

// ----------------------------------
// isHour(hh)
// ----------------------------------
//
function isHour(hh) {
  return (! ((hh < 0) || (hh > 24)))
}

// ----------------------------------
// compareDate(date1, date2, sign)
// ----------------------------------
// Comparaison de deux dates au format standard.
// Le champ sign determine le type de comparaison, et peut avoir
// les valeurs suivantes: "<", "<=", ">", ">=", "=".
function compareDate(date1, date2, sign) {
  if (date1.length != 8) {
    return (false);
  }
  if (date2.length != 8) {
    return (false);
  }

  switch (sign) {
  case '<':
    if (date1 >= date2) {
      return (false);
    }
    break;
  case '<=':
    if (date1 > date2) {
      return (false);
    }
    break;
  case '>':
    if (date1 <= date2) {
      return (false);
    }
    break;
  case '>=':
    if (date1 < date2) {
      return (false);
    }
    break;
  case '=':
    if (date1 != date2) {
      return (false);
    }
    break;
  default:
    return (false);
    break;
  }

  return (true);
}

// ----------------------------------
// getSystemDate()
// ----------------------------------
// Retourne la date systeme au format standard (yyyymmdd).
function getSystemDate() {
  return (getStandardDate(getCurrentDay(), getCurrentMonth(), getCurrentYear()));
}

// ----------------------------------
// getSystemTime()
// ----------------------------------
// Retourne l'heure systeme au format standard (hhmm).
function getSystemTime() {
  var hh = getCurrentHours();
  var mm = getCurrentMinutes();
  var ss = getCurrentSeconds();
  return (hh.toString() + mm.toString() + ss.toString());
}

// ----------------------------------
// getCurrentYear()
// ----------------------------------
// Retourne l'annee courante.
function getCurrentYear() {
  var today = new Date();
  today = today.getYear();
  return (today < 1900 ? 1900 + today: today);
}

// ----------------------------------
// getCurrentMonth()
// ----------------------------------
// Retourne le mois de l'annee courante (01-12).
function getCurrentMonth() {
  var today = new Date();
  today = today.getMonth() + 1;
  return (today < 10 ? '0' + today: today);
}

// ----------------------------------
// getCurrentDay()
// ----------------------------------
// Retourne le jour du mois courant (01-31).
function getCurrentDay() {
  var today = new Date();
  today = today.getDate()
  return (today < 10 ? '0' + today: today);
}

// ----------------------------------
// getCurrentHours()
// ----------------------------------
// Retourne l'heure du jour courant (00-23).
function getCurrentHours() {
  var today = new Date();
  today = today.getHours();
  return (today < 10 ? '0' + today: today);

}

// ----------------------------------
// getCurrentMinutes()
// ----------------------------------
// Retourne le nombre de minutes de l'heure courante (00-59).
function getCurrentMinutes() {
  var today = new Date();
  today = today.getMinutes();
  return (today < 10 ? '0' + today: today);
}

// ----------------------------------
// getCurrentSeconds()
// ----------------------------------
// Retourne le nombre de secondes de la minute courante (00-59).
function getCurrentSeconds() {
  var today = new Date();
  today = today.getSeconds();
  return (today < 10 ? '0' + today: today);
}

// ---------------------------------------
// replaceAll(strOld, strFind, strReplace)
// ---------------------------------------
// Fonction : remplace toutes les occurences de strFind contenues dans strOld par strReplace.
// IN : strOld : string dans laquelle s'effectue la recherche
//      strFind : string a rechercher
//      strReplace : string qui remplace strFind
function replaceAll(strOld, strFind, strReplace) {
  var position = 0;
  var strNew = '';

  while (strOld.indexOf(strFind, position) != -1) {
    strNew += strOld.substring(position, strOld.indexOf(strFind, position));
    strNew += strReplace;
    position = (strOld.indexOf(strFind, position) + strFind.length);
  }

  strNew += strOld.substring(position, strOld.length);
  return strNew;
}

// ---------------------------------------
// f_checkEmail(emailStr)
// ---------------------------------------
// Fonction : Verifie la validite syntaxique d'une adresse email
// IN : emailStr : l'adresse a verifier
function f_checkEmail(emailStr) {
  /* The following variable tells the rest of the function whether or not
    to verify that the address ends in a two-letter country or well-known
    TLD.  1 means check it, 0 means don't. */

  var checkTLD = 1;

  /* The following is the list of known TLDs that an e-mail address must end with. */

  var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

  /* The following pattern is used to check if the entered e-mail address
    fits the user@domain format.  It also is used to separate the username
    from the domain. */

  var emailPat = /^(.+)@(.+)$/;

  /* The following string represents the pattern for matching all special
    characters.  We don't want to allow special characters in the address.
    These characters include ( ) < > @ , ; : \ " . [ ] */

  var specialChars = "\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

  /* The following string represents the range of characters allowed in a
    username or domainname.  It really states which chars aren't allowed. */

  var validChars = "\[^\\s" + specialChars + "\]";

  /* The following pattern applies if the "user" is a quoted string (in
    which case, there are no rules about which characters are allowed
    and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
    is a legal e-mail address. */

  var quotedUser = "(\"[^\"]*\")";

  /* The following pattern applies for domains that are IP addresses,
    rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
    e-mail address. NOTE: The square brackets are required. */

  var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

  /* The following string represents an atom (basically a series of non-special characters.) */

  var atom = validChars + '+';

  /* The following string represents one word in the typical username.
    For example, in john.doe@somewhere.com, john and doe are words.
    Basically, a word is either an atom or quoted string. */

  var word = "(" + atom + "|" + quotedUser + ")";

  // The following pattern describes the structure of the user
  var userPat = new RegExp("^" + word + "(\\." + word + ")*$");

  /* The following pattern describes the structure of a normal symbolic
    domain, as opposed to ipDomainPat, shown above. */

  var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$");

  /* Finally, let's start trying to figure out if the supplied address is valid. */

  /* Begin with the coarse pattern to simply break up user@domain into
    different pieces that are easy to analyze. */

  var matchArray = emailStr.match(emailPat);

  if (matchArray == null) {

    /* Too many/few @'s or something; basically, this address doesn't
      even fit the general mould of a valid e-mail address. */

    // alert("Email address seems incorrect (check @ and .'s)");
    return false;
  }

  var user = matchArray[1];
  var domain = matchArray[2];

  // Start by checking that only basic ASCII characters are in the strings (0-127).
  for (i = 0; i < user.length; i++) {
    if (user.charCodeAt(i) > 127) {
      // alert("The username contains invalid characters.");
      return false;
    }
  }

  for (i = 0; i < domain.length; i++) {
    if (domain.charCodeAt(i) > 127) {
      // alert("The domain name contains invalid characters.");
      return false;
    }
  }

  // See if "user" is valid
  if (user.match(userPat) == null) {

    // user is not valid
    // alert("The username doesn't seem to be valid.");
    return false;
  }

  /* if the e-mail address is at an IP address (as opposed to a symbolic
    host name) make sure the IP address is valid. */

  var IPArray = domain.match(ipDomainPat);
  if (IPArray != null) {

    // this is an IP address
    for (var i = 1; i <= 4; i++) {
      if (IPArray[i] > 255) {
        // alert("Destination IP address is invalid!");
        return false;
      }
    }
    return true;
  }

  // Domain is symbolic name.  Check if it's valid.
  var atomPat = new RegExp("^" + atom + "$");
  var domArr = domain.split(".");
  var len = domArr.length;
  for (i = 0; i < len; i++) {
    if (domArr[i].search(atomPat) == -1) {
      // alert("The domain name does not seem to be valid.");
      return false;
    }
  }

  /* domain name seems valid, but now make sure that it ends in a
    known top-level domain (like com, edu, gov) or a two-letter word,
    representing country (uk, nl), and that there's a hostname preceding
    the domain or country. */

  if (checkTLD && domArr[domArr.length - 1].length != 2 && domArr[domArr.length - 1].search(knownDomsPat) == -1) {
    // alert("The address must end in a well-known domain or two letter " + "country.");
    return false;
  }

  // Make sure there's a host name preceding the domain.
  if (len < 2) {
    // alert("This address is missing a hostname!");
    return false;
  }

  // If we've gotten this far, everything's valid!
  return true;
}

// -------------------------------------------------------------------------------
// f_divPrint(divId)
// -------------------------------------------------------------------------------
// Fonction : Permet d'imprimer le contenu d'un div (pages sans les menus par ex.)
//						Imprime la fenetre entiere si le div reference n'existe pas
// IN : divId : id du div a imprimer
function f_divPrint(divId) {
  var browserName = navigator.appName;
  var objectName;

  if (browserName == 'Netscape') {
    if (document.getElementById(divId) == '[object HTMLDivElement]') {
      var transfert = document.getElementById(divId).innerHTML;
      frmPrint.document.getElementById('divPrint').innerHTML = transfert;
      frmPrint.focus();
      frmPrint.print();
    } else {
      window.print();
    }
  } else {
    if (document.getElementById(divId) == '[object]') {
      var transfert = document.getElementById(divId).innerHTML;
      document.frmPrint.document.getElementById('divPrint').innerHTML = transfert;
      document.frmPrint.focus();
      window.print();
    } else {
      window.print();
    }
  }
}

// -------------------------------------------------------------------------------
// pasteit(theField)
// -------------------------------------------------------------------------------
// Fonction : Permet de coller le contenu du presse-papier dans un champ
//
// IN : theField : champ dans lequel on colle les données

function pasteit(theField) {
	var val=eval("document."+theField);
	therange=val.createTextRange();
	therange.execCommand("Paste");
}

// -------------------------------------------------------------------------------
// copyToClipboard(s)
// -------------------------------------------------------------------------------
// Fonction : Permet de copier du texte dans le presse papier
//
// IN : s : texte à copier

function copyToClipboard(s){
	if( window.clipboardData && clipboardData.setData ){
		clipboardData.setData("Text", s);
	} else {
		// This is importent but it's not noted anywhere
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
		// create interface to the clipboard
		var clip = Components.classes['@mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard);
		if (!clip) return;
		// create a transferable
		var trans = Components.classes['@mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable);
		if (!trans) return;
		// specify the data we wish to handle. Plaintext in this case.
		trans.addDataFlavor('text/unicode');
		// To get the data from the transferable we need two new objects
		var str = new Object();
		var len = new Object();
		var str = Components.classes["@mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString);
		var copytext=meintext;
		str.data=copytext;
		trans.setTransferData("text/unicode",str,copytext.length*[[[[2]]]]);
		var clipid=Components.interfaces.nsIClipboard;
		if (!clip) return false;
		clip.setData(trans,null,clipid.kGlobalClipboard);
	}
}