/****************************************************************************/
/**                                                                        **/
/**          __  /  - ____   __   __  __                                   **/
/**        /  / /  / / / / /  / /_  /__/                                   **/
/**       /__/ /_ / / / / /__/ __/ /__                                     **/
/**       __/            /                                                 **/
/**           PHP Library (v 1.16b)                                        **/
/**                                                                        **/
/**       Copyright (c) 2000-2002 Glimpse - Licence LGPL                   **/
/**       http://glimpselib.fr.fm - glimpse@glimpse.fr.fm                  **/
/**                                                                        **/
/**                                                                        **/
/****************************************************************************/


// Function to strip CRLF and space characters at the begining and the end of a string
function String_trim() {
  var p1=0, p2=this.length-1;
  while ((this.charCodeAt(p1) == 32 || this.charCodeAt(p1) == 10 || this.charCodeAt(p1) == 13) && p1 < this.length) p1++;
  while ((this.charCodeAt(p2) == 32 || this.charCodeAt(p2) == 10 || this.charCodeAt(p2) == 13) && p2 >= 0) p2--;
  if (p1 >= this.length && p2 <= -1) return '';
  else return this.substring(p1, p2+1);
}
String.prototype.trim = String_trim;


// Function to test if a string is empty (or white spaces fullfilled)
function String_isEmpty() {
  var s=this.trim();
  if (s.length) return false;
  else return true;
}
String.prototype.isEmpty = String_isEmpty;


// Function to test if the given string represents an integer
function String_isInteger() {
  var i, s=new String(this.trim());
  for (i=0; i<s.length; i++) {
    if (s.charCodeAt(i) < 48 || s.charCodeAt(i) > 57) return false;
  }
  return true;
}
String.prototype.isInteger = String_isInteger;


// Function to test if the given string represents a floating point number
function String_isDecimal(m,n) {
  var i, s=new String(this.trim()), nbDots=0, nbDigits=0;
  for (i=0; i<s.length; i++) {
    if ((s.charCodeAt(i) < 48 || s.charCodeAt(i) > 57) && s.charCodeAt(i) != 46) return false;
    if (s.charCodeAt(i) == 46) nbDots++;
    else nbDigits++;
  }
  if (nbDots > 1 || nbDigits < 1) return false;
  return true;
}
String.prototype.isDecimal = String_isDecimal;


// Function to test if the given string represents a date
function String_isDate() {
  var result = true;
  var s = new String(this.trim());
  //test francais
  // dd/mm/yyyy
  var re = /[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{2,4}/;
  if (re.test(s)) {
    var d = s.split('/');
    var day = parseFloat(d[0]);
    var month = parseFloat(d[1]);
    if (month > 12 || month < 1) result = false;
    var dl = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    if (isLeapYear(d[2])) dl[1] = 29;
    if (day > dl[month-1] || day < 1) result = false;
  }
  // dd/mm/yyyy hh:mm:ss
  var re = /[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{2,4} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}/;
  if (re.test(s)) {
    var d = s.split('/');
    var day = parseFloat(d[0]);
    var month = parseFloat(d[1]);
    if (month > 12 || month < 1) result = false;
    var dl = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    var dd = d[2].split(' ');
    if (isLeapYear(dd[0])) dl[1] = 29;
    if (day > dl[month-1] || day < 1) result = false;
    var ddd = dd[1].split(':');
    var hour = parseFloat(ddd[0]);
    var minute = parseFloat(ddd[1]);
    var seconde = parseFloat(ddd[2]);
    if (hour > 24 || hour < 1) result = false;
    if (minute > 60 || minute < 1) result = false;
    if (seconde > 60 || seconde < 1) result = false;
  }
  // test anglais
  // yyyy-mm-dd
  var re = /[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2}/;
  if (re.test(s)) {
    var d = s.split('-');
    var day = parseFloat(d[2]);
    var month = parseFloat(d[1]);
    if (month > 12 || month < 1) result = false;
    var dl = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    if (isLeapYear(d[0])) dl[1] = 29;
    if (day > dl[month-1] || day < 1) result = false;
  }
  // yyyy-mm-dd hh:mm:ss
  var re = /[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}/;
  if (re.test(s)) {
    var d = s.split('-');
    var dd = d[2].split(' ');
    var day = parseFloat(dd[0]);
    var month = parseFloat(d[1]);
    if (month > 12 || month < 1) result = false;
    var dl = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    if (isLeapYear(d[0])) dl[1] = 29;
    if (day > dl[month-1] || day < 1) result = false;
    var ddd = dd[1].split(':');
    var hour = parseFloat(ddd[0]);
    var minute = parseFloat(ddd[1]);
    var seconde = parseFloat(ddd[2]);
    if (hour > 24 || hour < 1) result = false;
    if (minute > 60 || minute < 1) result = false;
    if (seconde > 60 || seconde < 1) result = false;
  }
  return result;
}
String.prototype.isDate = String_isDate;

// Function to test if the given string represents an e-mail address
function String_isEmail() {
  var s = new String(this.trim());
  var re = /[a-z0-9\.\-_]+@[a-z0-9\-]+\.+[a-z]{2,7}/i;
  return re.test(s);
}
String.prototype.isEmail = String_isEmail;

// Function to test if the given string represents an html link
function String_isLink() {
  //var s = new String(this.trim());
  //var re = /[a-z0-9\.\-_]+@[a-z0-9\-]+\.+[a-z]{2,7}/i;
  //return re.test(s);
  return true;
}
String.prototype.isLink = String_isLink;

// Function to test if the given string represents an alphanumeric string
function String_isAlphanumeric() {
  var s = new String(this.trim());
  var re = /[~`!@§£µ¨°_²€#\$\%\^&\*\(\)\+=\{\[\}\]\|\\:;<,>\.\/\?\f\n\r\t\v\"]/i;
  return !re.test(s);
}
String.prototype.isAlphanumeric = String_isAlphanumeric;



// Function to test if a year is a leap year (used by String.isDate)
function isLeapYear(year) {
  if (!(year%4)) {
    if (!(year%100)) {
      if (!((year/100)%4)) return true;
    } else {
      return true;
    }
  } else {
    return false;
  }
}


function String_hasFormat(pattern) {
  if (pattern.charAt(0)!='^') pattern = '^'+pattern;
  if (pattern.charAt(pattern.length-1)!='$') pattern += '$';
  var rexp = new RegExp(pattern, 'g');
  return rexp.test(this);
}
String.prototype.hasFormat = String_hasFormat;


function String_toUCWords() {
  var v = this.toLowerCase();
  var seps = new Array(" ", "-");
  var s, i;
  for (s=0; s<seps.length; s++) {
    var words = v.split(seps[s]);
    for (i=0; i<words.length; i++) words[i] = words[i].substring(0, 1).toUpperCase()+words[i].substring(1, words[i].length)
    v = words.join(seps[s]);//
  }
  return v
}
String.prototype.toUCWords = String_toUCWords;


function String_getFileExt() {
  var p = this.lastIndexOf('.');
  if (p == -1) return ('');
  else return this.substring(p+1, this.length).toLowerCase();
}
String.prototype.getFileExt = String_getFileExt;




function initForms(doc) {
  if (!doc) doc = document;
  for (var i=0; i<doc.forms.length; i++) {
    var form = doc.forms[i];
    form.doSubmit = form_doSubmit;
    form.test = form_test;
    form.setField = form_setField;
    form.setFieldNeeded = form_setFieldNeeded;
    form.fields = new Array();
    form.registerFunction = form_registerFunction;
    form.extraTestFunction = new Array();
    form.focusOnError = true;
    form.msgFieldSeparator = ', ';
    form.okJavaScript = '';
    for (var j=0; j<form.elements.length; j++) {
      switch (form.elements[j].type) {
        case 'textarea' :
        case 'text' :
        case 'password' :
        case 'select-one' :
        case 'select-multiple' :
        case 'file' :
          form.setField(form.elements[j].name, 'string', false, form.elements[j].name);
        break;
      }
    }
  }
}


function form_registerFunction(functionName) {
  this.extraTestFunction[this.extraTestFunction.length] = functionName;
}


function form_doSubmit() {
  if (this.test()) this.submit()
}


function form_test () {
  var docField, usrField, name, type, format, missing = '', incorrect = '', outOfRange = '', incorrectFileType = '', tooLong = '', tooSmall = '', 
      needEqualField = '', needCheckedToValidateForm = '',  value = '', toFocus = null, label, msg = '', tmpMsg = '';

  for (var i=0; i<this.elements.length; i++) {

    docField = this.elements[i]
    name = docField.name
    type = docField.type
    usrField = this.fields[name];
    if (!usrField) continue;
    label = name

    switch (type) {

      case 'file' :
        if (usrField.label) if (usrField.label.length) label = usrField.label;
        value = docField.value;
        if (usrField.needed && !value.length) {
          if (missing.length) missing += this.msgFieldSeparator;
          missing += label;
          if (toFocus == null) toFocus = docField;
        } else {
          var ex = usrField.extraOptions;
          if (ex.length && value.length) {
            var toTest = '';
            switch (ex.substring(0, 5)) {
              case "type:" :
                toTest = value.getFileExt();
              break;
              case "name:" :
                var p = value.lastIndexOf("/");
                if (p == -1) p = value.lastIndexOf("\\");
                if (p == -1) toTest = value;
                else toTest = value.substring(p + 1, value.length);
              break;
            }
            if (usrField.extraOptions.indexOf(','+toTest+',') == -1) {
              if (usrField.strict) {
                if (incorrectFileType.length) incorrectFileType += this.msgFieldSeparator;
                incorrectFileType += label;
                if (toFocus == null) toFocus = docField;
              } else {
                var conf = confirm(usrField.msg)
                if (conf == false) return false;
                if (toFocus == null) toFocus = docField;
              }
            }
          }
        }
      break;

      case 'textarea' :
        if (usrField.label) if (usrField.label.length) label = usrField.label
        value = docField.value;
        if (usrField.maxLength != null && value.length > usrField.maxLength) {
          tmpMsg = _FORM_ALERT_TOO_LONG;
          tmpMsg = tmpMsg.replace('NAME', label);
          tmpMsg = tmpMsg.replace('MAX', usrField.maxLength);
          tooLong += "\n"+tmpMsg;
        }
        if (usrField.minLength != null && value.length < usrField.minLength) {
          tmpMsg = _FORM_ALERT_TOO_SMALL;
          tmpMsg = tmpMsg.replace('NAME', label);
          tmpMsg = tmpMsg.replace('MIN', usrField.minLength);
          tooSmall += "\n"+tmpMsg;
        }

      case 'text' :
      case 'password' :
        if (usrField.label) if (usrField.label.length) label = usrField.label
        value = docField.value;
        if (usrField.needed && !value.length) {
          if (missing.length) missing += ', '
          missing += label
          if (toFocus == null) toFocus = docField
        } else {
          if (usrField.type=='date') {
            if (!value.isDate() && value.length) {
              if (incorrect.length) incorrect += this.msgFieldSeparator;
              incorrect += label
              if (toFocus == null) toFocus = docField
            }
          } else if (usrField.type=='email') {
            if (!value.isEmail() && value.length) {
              if (incorrect.length) incorrect += this.msgFieldSeparator;
              incorrect += label
              if (toFocus == null) toFocus = docField
            }
          } else if (usrField.type=='link') {
            if (!value.islink() && value.length) {
              if (incorrect.length) incorrect += this.msgFieldSeparator;
              incorrect += label
              if (toFocus == null) toFocus = docField
            }
          } else if (usrField.type=='alphanumeric') {
            if (!value.isAlphanumeric() && value.length) {
              if (incorrect.length) incorrect += this.msgFieldSeparator;
              incorrect += label
              if (toFocus == null) toFocus = docField
            }
          } else {
            if (usrField.format.length) {
              if (value.hasFormat(usrField.format) == false) {
                if (incorrect.length) incorrect += this.msgFieldSeparator;
                incorrect += label
                if (toFocus == null) toFocus = docField
              }
            }
          }

          var err = 0;
          if (usrField.type == 'integer' || usrField.type == 'decimal') {
            if (usrField.minValue != null) if (parseFloat(value) < usrField.minValue) err = 1;
            if (usrField.maxValue != null) if (parseFloat(value) > usrField.maxValue) err += 2;
            if (err) {
              tmpMsg = _FORM_ALERT_OUT_OF_RANGE;
              tmpMsg = tmpMsg.replace('NAME', label);
              tmpMsg = tmpMsg.replace('LBOUND', usrField.minValue);
              tmpMsg = tmpMsg.replace('UBOUND', usrField.maxValue);
              outOfRange += "\n"+tmpMsg;
              if (toFocus == null) toFocus = docField
            }
          }
          if (usrField.minLength != null && value.length < usrField.minLength) {
            if (value.length == 0 && !usrField.needed) {
              // si le champ n'est pas obligatoire on n'aplique pas la regle des carateres minimum
            } else {
              tmpMsg = _FORM_ALERT_TOO_SMALL;
              tmpMsg = tmpMsg.replace('NAME', label);
              tmpMsg = tmpMsg.replace('MIN', usrField.minLength);
              tooSmall += "\n"+tmpMsg;
            }
          }
          if (usrField.needEqualField != null) /* && value.length < usrField.minLength)*/ {
            var docField2 = null;
            for (var i2=0; i2<this.elements.length; i2++) {
              if (this.elements[i2].name == usrField.needEqualField) {
                docField2 = this.elements[i2];
              }
            }
            if (docField2 != null)
            if (value != docField2.value) {
              tmpMsg = _FORM_ALERT_CONTENT_FIELD_DIFFERENT;
              tmpMsg = tmpMsg.replace('NAME1', label);
              tmpMsg = tmpMsg.replace('NAME2', this.fields[usrField.needEqualField].label);
              needEqualField += "\n"+tmpMsg;
            }
          }
        }

      break

      case 'select-one' :
        label = name
        if (usrField.label) if (usrField.label.length) label = usrField.label
        if (docField.selectedIndex!=-1) value = docField.options[docField.selectedIndex].value
        if (usrField.needed && !value.length) {
          if (missing.length) missing += this.msgFieldSeparator;
          missing += label
          if (toFocus == null) toFocus = docField
        }
      break

      case 'select-multiple' :
        var _nbSelected = 0;
        label = name;
        if (usrField.label) if (usrField.label.length) label = usrField.label;
        for (var j=0; j<docField.options.length; j++) {
          if (docField.options[j].selected && docField.options[j].value.length) _nbSelected++;
        }
        if (usrField.needed && !_nbSelected) {
          if (missing.length) missing += this.msgFieldSeparator;
          missing += label;
          if (toFocus == null) toFocus = docField;
        }
      break
      
      case 'checkbox' :
        if (usrField.needCheckedToValidateForm != null) {
          if (!docField.checked) {
            tmpMsg = _FORM_ALERT_CHECKBOX_NOT_CHECKED;
            tmpMsg = tmpMsg.replace('NAME', usrField.label);
            needCheckedToValidateForm += "\n"+tmpMsg;
          }
        }
      break
    }
  }

  if (missing.length) missing = "\n"+_FORM_ALERT_MISSING_FIELD+missing;
  if (incorrect.length) incorrect = "\n"+_FORM_ALERT_INCORRECT_FORMAT+incorrect;
  if (incorrectFileType.length) incorrectFileType = "\n"+_FORM_ALERT_INCORRECT_FILE_TYPE+incorrectFileType;
  if (missing.length || incorrect.length || incorrectFileType.length || outOfRange.length || tooLong.length || tooSmall.length || needEqualField.length || needCheckedToValidateForm.length) {
    msg = _FORM_ALERT_MAIN_MESSAGE + missing + incorrect + incorrectFileType + outOfRange + tooLong + tooSmall + needEqualField + needCheckedToValidateForm;
  }

  if (msg.length) {
    alert(msg);
    if (this.focusOnError) {
      if (toFocus) {
        toFocus.focus();
        if (toFocus.select) toFocus.select();
      }
    }
    return false;
  } else {
    if (this.extraTestFunction.length) {
      for (var i=0; i<this.extraTestFunction.length; i++) {
        if (!eval(this.extraTestFunction[i]+'()')) return false;
      }
    }
    if (this.okJavaScript.length) eval(this.okJavaScript);
    return true;
  }
}


function form_setField(name, format, needed, label, extra, msg, strict) {
  this.fields[name] = new form_fieldObject(name, format, needed, label, extra, msg, strict);
}


function form_fieldObject(name, format, needed, label, extra, msg, strict) {
  this.name = name;
  this.msg = msg;
  this.strict = strict;
  if (!format) format = '';
  switch (format) {
    case 'integer' :
      this.type = 'integer';
      format = '[0-9]*';
    break;
    case 'decimal' :
      this.type = 'decimal';
      format = '^[0-9]*(\\.[0-9]+){0,1}$';
    break;
    case 'date' :
      this.type = 'date';
      format = '([0-3]?[0-9]\/[012]?[0-9]\/[0-9]{4})?';
      format_en = '([0-3][0-9]{4}-[012]?[0-9]-[0-3]?[0-9])?';
    break;
    case 'string' :
      this.type = 'string';
      format = '';
    break;
    case 'alphanumeric' :
      this.type = 'alphanumeric';
      //format = '^[a-zA-Z0-9]+$';
      format = '';
    break;
    case 'strnumber' :
      this.type = 'strnumber';
      format = '[0-9]*';
    break;
    case 'email' :
      this.type = 'email';
      format = '';
    break;
    case 'link' :
      this.type = 'link';
      //format = '(((https?)|(ftp)|(rtsp)|(rtp)|(rtmp)|(mms)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)';
      format = '';
    break;
    default :
      var re = new RegExp("^decimal\\(([0-9]+),([0-9]+)\\)$", "ig");
      var m = re.exec(format);
      if (m) {
        format = '^\\-{0,1}[0-9]{0,'+RegExp.$1+'}(\\.[0-9]{1,'+RegExp.$1+'}){0,1}$';
        this.type = "decimal";
      } else {
        this.type = 'string';
      }
    break;
  }
  if (!needed) needed = false;
  if (!label) label = '';
  this.needed = needed;
  this.format = format;
  this.label = label;
  this.extraOptions = extra ? extra : '';
  this.minValue = null;
  this.maxValue = null;
  this.maxLength = null;
  this.needEqualField = null;
  this.needCheckedToValidateForm = false;
}

function form_fieldObject_setLBound(bound) {
        this.minValue = bound;
}
form_fieldObject.prototype.setLBound = form_fieldObject_setLBound;

function form_fieldObject_setUBound(bound) {
        this.maxValue = bound;
}
form_fieldObject.prototype.setUBound = form_fieldObject_setUBound;

function form_fieldObject_setMaxLength(l) {
        this.maxLength = l;
}
form_fieldObject.prototype.setMaxLength = form_fieldObject_setMaxLength;

function form_fieldObject_setMinLength(l) {
        this.minLength = l;
}
form_fieldObject.prototype.setMinLength = form_fieldObject_setMinLength;

function form_fieldObject_setNeedEqualField(field_s) {
        this.needEqualField = field_s;
}
form_fieldObject.prototype.setNeedEqualField = form_fieldObject_setNeedEqualField;

function form_fieldObject_setNeedCheckedToValidateForm(b) {
        this.needCheckedToValidateForm = b;
}
form_fieldObject.prototype.setNeedCheckedToValidateForm = form_fieldObject_setNeedCheckedToValidateForm;


// Function to show default text in an empty mandatory text field when losing focus
function showDefaultTextInInput(obj, defaultText) {
  if (!obj.value.length) obj.value=defaultText;
}

// Function to clear the default text in a mandatory text field when focus is given
function clearDefaultTextInInput(obj, defaultText) {
  if (obj.value == defaultText) obj.value="";
}

// Function to toggle checkbox state (checked/unchecked)
function toggleCheckbox(cb) {
  if (cb.disabled) return;
  if (cb.checked == true) cb.checked = false;
  else cb.checked = true;
}


// Function to check a radio button
function setRadio(radio, index) {
  if (_customizedFormWidgets) {
    eval(radio.name+'_radioGrp.set('+index+')');
  } else {
    if (radio.name) radio.checked = true;
    else radio[index].checked = true;
  }
}

// Function to format a date field automatically
function autoFormatDate(t, currentDay, currentMonth, currentYear) {

  var tab, i;
  var seps = "/.;:,-", sep = "", newDate = "";
  var date = t.value.trim();
  var def = new Array(currentDay, currentMonth, currentYear);
  if (!date.length) return;

  // separate date and hour in the string...
  var dateandhour = date.split(" ");
  if (dateandhour.length>1) {
    var date = dateandhour[0];
    var hour = dateandhour[1];
  }
    
  // Finds a separator in the string...
  for (i=0; i<seps.length; i++) {
    tab = date.split(seps.charAt(i));
    if (tab.length>1) {
      sep = seps.charAt(i);
      break;
    }
  }
  if (sep == "/") {
    for (i=0; i<tab.length; i++) {
      tab[i] = tab[i].trim();
      if (!tab[i].length) newDate += def[i];
      else {
        tab[i] = parseFloat(tab[i]);
        if (i!=2) {
          if (tab[i]<10) newDate += "0"+tab[i];
          else newDate += tab[i];
        } else {
          if (tab[i]<10) newDate += currentYear.substring(0, 3)+tab[i];
          else if (tab[i]<100) newDate += currentYear.substring(0, 2)+tab[i];
               else if (tab[i]<1000) newDate += currentYear.substring(0, 1)+tab[i];
                    else newDate += tab[i];
        }
      }
      if (i<tab.length-1) newDate += "/";
    }
  
    if (tab.length == 1) {
       // The month and the year are not specified: appending them to the string
      newDate += "/"+currentMonth+"/"+currentYear;
    }
  
    if (tab.length == 2) {
      // The year is not specified: appending it to the string
      newDate += "/"+currentYear;
    }
  } else 
  if (sep == "-") {
    def = new Array(currentYear, currentMonth, currentDay);
    for (i=0; i<tab.length; i++) {
      tab[i] = tab[i].trim();
      if (!tab[i].length) newDate += def[i];
      else {
        tab[i] = parseFloat(tab[i]);
        if (i!=0) {
          if (tab[i]<10) newDate += "0"+tab[i];
          else newDate += tab[i];
        } else {
          if (tab[i]<10) newDate += currentYear.substring(0, 3)+tab[i];
          else if (tab[i]<100) newDate += currentYear.substring(0, 2)+tab[i];
               else if (tab[i]<1000) newDate += currentYear.substring(0, 1)+tab[i];
                    else newDate += tab[i];
        }
      }
      if (i<tab.length-1) newDate += "-";
    }
  
    if (tab.length == 1) {
       // The month and the year are not specified: appending them to the string
      newDate += "-"+currentMonth+"-"+currentYear;
    }
  
    if (tab.length == 2) {
      // The year is not specified: appending it to the string
      newDate += "-"+currentYear;
    }
  }
  
  // Sets the input field to the newly formated date
  t.value = newDate;
}

function setFormNumber(f, s, min, max) {
  if (f.disabled) return;
  var v = f.value;
  if (!v.length) v = "0";
  v = parseFloat(v);
  if (v+s >= min && v+s <= max) {
    f.value = v+s;
  }
}

function fieldToUpperCase(field) {
  field.value = field.value.toUpperCase();
}

function fieldToLowerCase(field) {
  field.value = field.value.toLowerCase();
}

function fieldToUCWords(field) {
  field.value = field.value.toUCWords();
}

function form_setFieldNeeded(fieldName, bool) {
  if (this.fields[fieldName]) this.fields[fieldName].needed = bool;
  if (bool == true) document.images[fieldName+'_needed_IMG'].src = _needed_form_field_icon;
  else document.images[fieldName+'_needed_IMG'].src = _not_needed_form_field_icon;
}

function parseNum(val) {
  var v2 = parseFloat(val);
  if (isNaN(v2)) return (0);
  else return (v2);
}