init_forms();

//==============================================================================
//==============================================================================
function init_forms()
{
  try
  {
    var iform, form, ielem, elem, classNames, iclass, className;
//    var tabIndex = 0;
    var prevElement = null;
    for (iform=0; iform<document.forms.length; iform++)
    {
      form = document.forms[iform];
      for (ielem=0; ielem<form.elements.length; ielem++)
      {
        elem = form.elements[ielem];
        if ((elem.type != null) && (elem.type != "hidden"))
        {
//          elem.tabIndex = tabIndex++;
          elem.prevElement = prevElement;
          elem.nextElement = null;
          if (prevElement != null)
          {
            prevElement.nextElement = elem;
          }
          prevElement = elem;
        }
        if ((elem.type == "text") && (elem.className) && (elem.className.length > 0))
        {
          classNames = trim(elem.className.replace(/  /g, " ")).split(" ");
          for (iclass=0; iclass<classNames.length; iclass++)
          {
            className = classNames[iclass];
            switch(className)
            {
              case "upper":
              case "lower":
              case "capitalized":
              case "int":
              case "phone":
              case "email":
              case "web":
              case "siret":
              case "tva":
              case "accise":
                if (elem.onblur != null) { elem.onblur_org = elem.onblur; }
                elem.onblur = eval(className+"_onblur");
                break;

              case "date":
                if (elem.onblur != null) { elem.onblur_org = elem.onblur; }
                elem.onblur = eval(className+"_onblur");
/*
                if ((iclass == 0) && (classNames.length == 2) && (classNames[1] == "calendar"))
                {
                  elem.onclick = calendar_onclick;
                }
*/
                break;

              case "float":
              case "float0":
              case "float1":
              case "float2":
              case "float3":
              case "float4":
              case "float5":
                elem.style.textAlign = "right";
                if (elem.onfocus != null) { elem.onfocus_org = elem.onfocus; }
                if (elem.onblur != null) { elem.onblur_org = elem.onblur; }
                elem.onfocus = float_onfocus;
                elem.onblur = float_onblur;
                break;
/*
              case "texte":
                if (elem.onfocus != null) { elem.onfocus_org = elem.onfocus; }
                if (elem.onblur != null) { elem.onblur_org = elem.onblur; }
                elem.onfocus = texte_onfocus;
                elem.onblur = texte_onblur;
                break;
*/
              case "time":
              case "timeHHMMSS":
                if (elem.onblur != null) { elem.onblur_org = elem.onblur; }
                elem.onblur = time_onblur;
                break;

              default:
                break;
            }
          }
        }
      }
    }
  }
  catch (exception)
  {
    processError(exception, "ctrl.js", "init_forms", 82);
  }
}

//==============================================================================
//==============================================================================
function trace(text_p)
{
  try
  {
    var div = document.getElementById("trace_output");
    if (div != null)
    {
      div.innerHTML += text_p + "<br />";
    }
  }
  catch (exception)
  {
    alert("Erreur (" + exception.name + ") : " + exception.message);
  }
}

function getDefaultSelectedIndex(select_p)
{
  for (var i=0; i<select_p.options.length; i++)
  {
    if (select_p.options[i].defaultSelected == true)
    {
      return i;
    }
  }
  return 0;
}

function selectChanged(select_p)
{
  try
  {
    for (var i=0; i<select_p.options.length; i++)
    {
      if (select_p.options[i].selected != select_p.options[i].defaultSelected)
      {
        return true;
      }
    }
  }
  catch (exception)
  {
    processError(exception, "ctrl.js", "selectChanged", 126);
  }
  return false;
}

function form_changed(form_p)
{
  var result = true;
  try
  {
    var form = (form_p != null) ? form_p : document.forms[0];
    if (form != null)
    {
      result = false;
      var nbElems = 0;
      var elem, changed;
      for (var ielem=0; (ielem<form.elements.length)/*&&(result==false)*/; ielem++)
      {
        elem = form.elements[ielem];
        changed = false;
        if ((elem.name != null) && (elem.name.length > 0) && (elem.type != null))
        {
          if ((elem.type == "text") || (elem.type == "textarea"))
          {
            if (elem.value != elem.defaultValue) { changed = true; }
            nbElems++;
          }
          else if ((elem.type == "checkbox") || (elem.type == "radio"))
          {
            if (elem.checked != elem.defaultChecked) { changed = true; }
            nbElems++;
          }
          else if (elem.type == "select-one")
          {
            if (elem.selectedIndex != getDefaultSelectedIndex(elem)) { changed = true; }
            nbElems++;
          }
          else if (elem.type == "select-multiple")
          {
            if (selectChanged(elem) == true) { changed = true; }
            nbElems++;
          }
          if (changed == true)
          {
            //trace(elem.name + " has changed !");
            result = true;
          }
        }
      }
      if (nbElems == 0)
      {
        result = true;
      }
    }
  }
  catch (exception)
  {
    processError(exception, "ctrl.js", "form_changed", 183);
  }
  return result;
}

function confirmerAnnuler(information_p, operation_p, location_p)
{
  var result = false;
  try
  {
    if (information_p == null)
    {
      information_p = "cette information";
    }
    if (operation_p != null)
    {
      if (operation_p == "c") { operation_p = "création"; }
      else if (operation_p == "m") { operation_p = "modification"; }
    }
    else
    {
      operation_p = "modification";
    }
    if ( (form_changed() == false)
      || (confirm("Voulez-vous vraiment abandonner la " + operation_p + " de " + information_p + " ?") == true) )
    {
      document.location = (location_p != null) ? location_p : "lister.php";
      result = true;
    }
  }
  catch (exception)
  {
    processError(exception, "ctrl.js", "form_changed", 183);
  }
  return result;
}

function confirmerDupliquer(information_p)
{
  return confirm("Voulez-vous vraiment dupliquer " + information_p + " ?");
}

function reload(form_p, action_p)
{
  form_p.action = action_p;
  form_p.submit();
}

function trim(string_p)
{
  while (string_p.substring(0,1) == ' ')
  {
    string_p = string_p.substring(1, string_p.length);
  }
  while (string_p.substring(string_p.length-1, string_p.length) == ' ')
  {
    string_p = string_p.substring(0, string_p.length-1);
  }
  return string_p;
}

function purge(string_p)
{
  string_p = trim(string_p);
  while (string_p.indexOf('  ') > 0)
  {
    string_p = string_p.replace(/  /g, ' ');
  }
  return string_p;
}

function upper_onblur(event)
{
  if (this.onblur_org != null) { this.onblur_org(); }
  this.value = purge(this.value.toUpperCase());
}

function lower_onblur(event)
{
  if (this.onblur_org != null) { this.onblur_org(); }
  this.value = purge(this.value.toLowerCase());
}

function capitalized_onblur(event)
{
  if (this.onblur_org != null) { this.onblur_org(); }
  capitalized = "";
  lower = purge(this.value.toLowerCase());
  lastc = ' ';
  for (i=0; i<lower.length; i++)
  {
    chr = lower.charAt(i);
    code = parseInt(lower.charCodeAt(i));
    if ((code >= 97) && (code <= 122))
    {
      if ((lastc == ' ') || (lastc == '-'))
      {
        chr = chr.toUpperCase();
      }
    }
    capitalized += chr;
    lastc = chr;
  }
  this.value = capitalized;
}

function texte_onfocus(event)
{
  if (this.onfocus_org != null) { this.onfocus_org(); }
  this.style.textAlign = "left";
}

function texte_onblur(event)
{
  if (this.onblur_org != null) { this.onblur_org(); }
  this.style.textAlign = "right";
}

function int_onfocus(event)
{
  if (this.onfocus_org != null) { this.onfocus_org(); }
  this.style.textAlign = "left";
}

function int_onblur(event)
{
  if (this.onblur_org != null) { this.onblur_org(); }
  if (this.value.length == 0) { return; }
  number = "";
  for (i=0; i<this.value.length; i++)
  {
    c = this.value.charAt(i);
    if ((isNaN(parseInt(c)) == false) || (c == '.') || ((c == '-') && (number.length == 0)))
    {
      number += c;
    }
    else if (c == ',')
    {
      number += '.';
    }
  }
  number = String(Math.round(number));
  this.value = number;
  //this.style.textAlign = "right";
}

function float_onfocus(event)
{
  if (this.onfocus_org != null) { this.onfocus_org(); }
  this.style.textAlign = "left";
}

function float_onblur(event)
{
  if (this.onblur_org != null) { this.onblur_org(); }
  if (this.value.length == 0) { return; }
  var decimals_p = (this.className == "float") ? 2 : parseInt(this.className.substr(5));
  var dec_point_p = ',';
  var thousands_sep_p = ' ';
  number = "";
  if ( (this.value.indexOf("+") > 0) || (this.value.indexOf("-") > 0)
    || (this.value.indexOf("*") > 0) || (this.value.indexOf("/") > 0) )
  {
    number = eval(this.value);
  }
  else
  {
    for (i=0; i<this.value.length; i++)
    {
      c = this.value.charAt(i);
      if ((isNaN(parseInt(c)) == false) || (c == '.') || ((c == '-') && (number.length == 0)))
      {
        number += c;
      }
      else if (c == ',')
      {
        number += '.';
      }
    }
  }
  mdiv = 1.00;
  for (i=0; i<decimals_p; i++) { mdiv *= 10.00; }
  number = String(Math.round(number*mdiv)/mdiv);
  sep = number.indexOf('.');
  if (sep < 0)
  {
    if (decimals_p > 0)
    {
      number += ".";
    }
    sep = 0;
  }
  else
  {
    sep = number.length - (sep+1);
  }
  while (sep < decimals_p)
  {
    number += "0";
    sep++;
  }
  if (dec_point_p != '.')
  {
    number = number.replace(/\./g, dec_point_p);
  }
  if (thousands_sep_p.length > 0)
  {
    sep = number.indexOf(dec_point_p);
    if (sep < 0) { sep = number.length; }
    while (sep > 3)
    {
      number = number.substr(0,sep-3) + thousands_sep_p + number.substr(sep-3);
      sep -= 3;
    }
  }
  this.value = number;
  this.style.textAlign = "right";
}

function date_onblur(event)
{
  if (this.onblur_org != null) { this.onblur_org(); }
  if (this.value.length == 0) { return; }
  var error = "";
  var input = "";
  var currentDate = new Date();
  var yyyy = currentDate.getFullYear();
  var mm = currentDate.getMonth()+1;
  var dd = currentDate.getDate();
  if (mm < 10) { mm = "0" + String(mm); }
  if (dd < 10) { dd = "0" + String(dd); }
  for (i=0; i<this.value.length; i++)
  {
    if (isNaN(c = parseInt(this.value.charAt(i))) == false)
    {
      input += String(c);
    }
  }
  if (input.length > 0)
  {
    d = parseFloat(input.substr(0, (input.length==1)?1:2));
    if ((d >= 1) && (d <= 31))
    {
      dd = ((d < 10) ? "0" : "") + String(d);
      if (input.length > 2)
      {
        m = parseFloat(input.substr(2, (input.length==3)?1:2));
        if ((m >= 1) && (m <= 12))
        {
          if ((d == 31) && ((m == 2) || (m == 4) || (m == 6) || (m == 9) || (m == 11)))
          {
            error = "Ce mois ne compte pas 31 jours.";
          }
          else
          {
            mm = ((m < 10) ? "0" : "") + String(m);
            if (input.length > 4)
            {
              y = parseFloat(input.substr(4));
              if (y < 10) { yyyy = "200" + String(y); }
              else if (y < 100) { yyyy = "19" + String(y); }
              else if (y < 1000) { yyyy = "0" + String(y); }
              else { yyyy = String(y); }
            }
          }
        }
        else
        {
          error = m + " n'est pas un mois correct.";
        }
      }
    }
    else
    {
      error = d + " n'est pas un jour correct.";
    }
  }
  if (error.length == 0)
  {
    this.value = dd + "/" + mm + "/" + yyyy;
    this.style.backgroundColor = "";
  }
  else
  {
    this.style.backgroundColor = "#ff4040";
    alert(error);
    this.focus();
  }
}

function calendar_onclick(event_p)
{
  try
  {
    var elem = null;
    if ((event_p != null) && (event_p.target != null))
    {
      elem = event_p.target;
    }
    else if ((event != null) && (event.srcElement != null))
    {
      elem = event.srcElement;
    }
    if ((elem != null) && (window.cal_show != null))
    {
      if (window.select_visibility != null)
      {
        select_visibility('hidden');
        cal_show(elem, select_visibility);
      }
      else
      {
        cal_show(elem, null);
      }
    }
  }
  catch (exception)
  {
    processError(exception, "crtl.js", "calendar_onclick", 507);
  }
}

function time_onblur(event)
{
  if (this.onblur_org != null) { this.onblur_org(); }
  if (this.value.length == 0) { return; }
  var error = "";
  var input = "";
  var seconds = (this.className == "timeHHMMSS") ? true : false;
  var currentDate = new Date();
  var hh = currentDate.getHours();
  var mm = "00"; //currentDate.getMinutes()+1;
  var ss = "00"; //currentDate.getSeconds();
  if (hh < 10) { hh = "0" + String(hh); }
  //if (mm < 10) { mm = "0" + String(mm); }
  //if (ss < 10) { ss = "0" + String(ss); }
  for (i=0; i<this.value.length; i++)
  {
    if (isNaN(c = parseInt(this.value.charAt(i))) == false)
    {
      input += String(c);
    }
  }
  if (input.length > 0)
  {
    h = parseFloat(input.substr(0, (input.length==1)?1:2));
    if ((h >= 0) && (h <= 23))
    {
      hh = ((h < 10) ? "0" : "") + String(h);
      if (input.length > 2)
      {
        m = parseFloat(input.substr(2, (input.length==3)?1:2));
        if ((m >= 0) && (m <= 59))
        {
          mm = ((m < 10) ? "0" : "") + String(m);
          if ((seconds == true) && (input.length > 4))
          {
            s = parseFloat(input.substr(4));
            if ((s >= 0) && (s <= 59))
            {
              ss = ((s < 10) ? "0" : "") + String(s);
            }
            else
            {
              error = s + " n'est pas un nombre de secondes correct.";
            }
          }
        }
        else
        {
          error = m + " n'est pas un nombre de minutes correct.";
        }
      }
    }
    else
    {
      error = h + " n'est pas une heure correcte.";
    }
  }
  if (error.length == 0)
  {
    this.value = hh + ":" + mm;
    if (seconds == true) {  this.value += ":" + ss; }
    this.style.backgroundColor = "";
  }
  else
  {
    this.style.backgroundColor = "#ff4040";
    alert(error);
    this.focus();
  }
}

function phone_onblur(event)
{
  if (this.onblur_org != null) { this.onblur_org(); }
  if (this.value.length == 0) { return; }
  sep_p = ' ';
  var input = "";
  var digits = 0;
  var i, c;
  if (this.value.charAt(0) == '+')
  {
    input = "+";
    for (i=0; i<this.value.length; i++)
    {
      if (isNaN(c = parseInt(this.value.charAt(i))) == false)
      {
        if ((digits == 2) || ((digits > 2) && ((digits%2) == 1))) { input += sep_p; }
        input += String(c);
        digits++;
      }
    }
  }
  else if ((this.value.charAt(0) == '0') && (this.value.charAt(1) == '0'))
  {
    input = this.value;
  }
  else
  {
    for (i=0; i<this.value.length; i++)
    {
      if (isNaN(c = parseInt(this.value.charAt(i))) == false)
      {
        if ((digits > 0) && ((digits%2) == 0)) { input += sep_p; }
        input += String(c);
        digits++;
      }
    }
  }
  this.value = input;
}

function email_onblur(event)
{
  if (this.onblur_org != null) { this.onblur_org(); }
  if (this.value.length == 0) { return; }
}

function web_onblur(event)
{
  if (this.onblur_org != null) { this.onblur_org(); }
  if (this.value.length == 0) { return; }
}

function siret_onblur(event)
{
  if (this.onblur_org != null) { this.onblur_org(); }
  if (this.value.length == 0) { return; }
  sep_p = ' ';
  var input = "";
  var digits = 0;
  var i, c;
  for (i=0; i<this.value.length; i++)
  {
    if (isNaN(c = parseInt(this.value.charAt(i))) == false)
    {
      if ((digits > 0) && (digits < 10) && ((digits%3) == 0)) { input += sep_p; }
      input += String(c);
      digits++;
    }
  }
  this.value = input;
}

function tva_onblur(event)
{
  if (this.onblur_org != null) { this.onblur_org(); }
  if (this.value.length == 0) { return; }
  sep_p = ' ';
  var input = "";
  var chars = 0;
  var i, c, code, digit;
  for (i=0; i<this.value.length; i++)
  {
    c = "";
    if (chars < 2)
    {
      code = parseInt(this.value.toUpperCase().charCodeAt(i));
      if ((code >= 65) && (code <= 90))
      {
        c = this.value.charAt(i).toUpperCase();
      }
    }
    else
    {
      if (isNaN(digit = parseInt(this.value.charAt(i))) == false)
      {
        c = String(digit);
      }
    }
    if (c.length == 1)
    {
      if ((chars == 2) || (chars == 4) || (chars == 7) || (chars == 10)) { input += sep_p; }
      input += c;
      chars++;
    }
  }
  this.value = input;
}

function accise_onblur(event)
{
  if (this.onblur_org != null) { this.onblur_org(); }
  if (this.value.length == 0) { return; }
  sep_p = ' ';
  var input = "";
  var chars = 0;
  var i, c, code, digit;
  for (i=0; i<this.value.length; i++)
  {
    c = "";
    if (chars < 5)
    {
      code = parseInt(this.value.toUpperCase().charCodeAt(i));
      if ((code >= 65) && (code <= 90))
      {
        c = this.value.charAt(i).toUpperCase();
      }
    }
    else
    {
      if (isNaN(digit = parseInt(this.value.charAt(i))) == false)
      {
        c = String(digit);
      }
    }
    if (c.length == 1)
    {
      if ((chars == 2) || (chars == 7) || (chars == 9)) { input += sep_p; }
      input += c;
      chars++;
    }
  }
  this.value = input;
}



function float_from_sql(float_p, decimals_p, dec_point_p, thousands_sep_p)
{
  if (decimals_p == null) { decimals_p = 2; }
  if (dec_point_p == null) { dec_point_p = ','; }
  if (thousands_sep_p == null) { thousands_sep_p = ' '; }
  mdiv = 1.00;
  for (i=0; i<decimals_p; i++) { mdiv *= 10.00; }
  float_p = String(Math.round(float_p*mdiv)/mdiv);
  sep = float_p.indexOf('.');
  if (sep < 0)
  {
    if (decimals_p > 0)
    {
      float_p += ".";
    }
    sep = 0;
  }
  else
  {
    sep = float_p.length - (sep+1);
  }
  while (sep < decimals_p)
  {
    float_p += "0";
    sep++;
  }
  if (dec_point_p != '.')
  {
    float_p = float_p.replace(/\./g, dec_point_p);
  }
  if (thousands_sep_p.length > 0)
  {
    sep = float_p.indexOf(dec_point_p);
    if (sep < 0) { sep = float_p.length; }
    while (sep > 3)
    {
      float_p = float_p.substr(0,sep-3) + thousands_sep_p + float_p.substr(sep-3);
      sep -= 3;
    }
  }
  return float_p;
}

function float_to_sql(float_p)
{
  if (float_p.length > 0)
  {
    float_p = float_p.replace(/,/g, ".");
    float_p = float_p.replace(/ /g, "");
    float_p = float_p * 1;
    if (isNaN(float_p) == true) { float_p = 0.00; }
  }
  else
  {
    float_p = 0.00;
  }
  return float_p;
}

function strid(string_p)
{
  var string = "";
  var strid_from = "áàâäéèêëíîïóôöùûüÿçñ& '\"«»-_~.,;:()[]{}+/*°%";
  var strid_to   = "aaaaeeeeiiiooouuuycn                        ";
  var lower = purge(string_p.toLowerCase());
  var chr, code, pos;
  for (var i=0; i<lower.length; i++)
  {
    chr = lower.charAt(i);
    code = parseInt(lower.charCodeAt(i));
    if ((code >= 97) && (code <= 122))
    {
      string += chr;
    }
    else if ((pos = strid_from.indexOf(chr)) >= 0)
    {
      string += strid_to.charAt(pos);
    }
  }
  string = purge(string);
  string = string.replace(/ /g, '-');
  return string;
}

function ajouter_valeur(select_p, message_p)
{
  try
  {
    valeur = prompt("Veuillez saisir " + message_p + " :", "");
    if ((valeur != null) && (valeur.length > 0))
    {
      option_nouveau = select_p.options[select_p.options.length-1];
      select_p.options[select_p.options.length-1] = new Option(valeur, valeur);
      select_p.options[select_p.options.length] = option_nouveau;
      select_p.value = valeur;
    }
    else
    {
      select_p.value = "";
    }
  }
  catch (exception)
  {
    alert("Erreur (" + exception.name + ") : " + exception.message);
  } 
}

function help(message_p)
{
  try
  {
    if ((div = document.getElementById("help_zone")) != null)
    {
      div.innerHTML = message_p;
    }
  }
  catch (exception)
  {
    alert("Erreur (" + exception.name + ") : " + exception.message);
  }  
}

function onglet(parent_p, id_p)
{
  try
  {
    // Masquer les onglets visibles
    if ((div = document.getElementById(parent_p)) != null)
    {
      sheets = div.getElementsByTagName("*");
      for (i=0; i<sheets.length; i++)
      {
        if (sheets[i].className == "TabSheet")
        {
          sheets[i].style.display = "none"; // visibility = "hidden";
        }
      }
    }
    // Afficher l'onglets sélectionné
    if ((div = document.getElementById(id_p)) != null)
    {
      div.style.display = "block"; // visibility = "visible";
    }
  }
  catch (exception)
  {
    alert("Erreur (" + exception.name + ") : " + exception.message);
  }
}
