/*
 * Ever Ezida (c) 2004 
 * @author tdn, sau
 */
 
/*
* Variables globales utilisée dans les .js utilisé dans la saisie marc
*/
var schemaTypeRoot      = 0;
var schemaTypeLeaf      = 1;
var schemaTypeSelection = 2;
var schemaTypeSet       = 3;
var schemaTypeSql       = 4;

// -----------------------------------------------------------------------------
// Un générateur d'identifiant entier unique 
// -----------------------------------------------------------------------------
function IdFactory()
{
   this.counter = 0;
   return this;
}
//
IdFactory.prototype.getNextId = function ()
{
   this.counter ++;
   return this.counter;
}
//
IdFactory.prototype.getCurrentId = function ()
{
   return this.counter;
}
//
IdFactory.prototype.setCurrentId = function (id)
{
   this.counter = id;
}

// -----------------------------------------------------------------------------
// Gestion des onglets
// type : 1 : Horizontal, 2 : vertical
// -----------------------------------------------------------------------------
var allHtmlTabViews = new Array();

function HtmlTabView(div, type, styleSelected, styleNotSelected)
{
   this.type = type;
   this.div = div;
   this.items = new Array();
   this.selectedIndex = 0;
   this.styleSelected = styleSelected;
   this.styleNotSelected = styleNotSelected;
   
   allHtmlTabViews[div.id] = this;
   
   return this;
}
// Ajoute un onglet
HtmlTabView.prototype.add = function (label, action)
{
   var tab = new HtmlTab(label, action);
   this.items[this.items.length] = tab;  
}
// Handlet appelé pour mettre à jour les onglets
function HtmlTabView_setCurrentTab(divId, idx)
{
   var tabview = allHtmlTabViews[divId];
   tabview.selectedIndex = idx;
   tabview.refresh();
   eval ("window." + tabview.items[idx].action);
   
}
// Génère le code HTML dans la div
HtmlTabView.prototype.refresh = function ()
{
   var ret = "";
   
   if ( this.type == 1 )
   {
      ret += "<table cellspacing='0' border='0' cellpadding='0'>";
      ret += "<tr>";
      for(var i=0; i<this.items.length; i++)
      {
         var style = (this.selectedIndex == i) ? this.styleSelected : this.styleNotSelected;
         ret += "<td nowrap='true' class='" + style + "'>";
         ret += "<a href=\"javascript:HtmlTabView_setCurrentTab('" + this.div.id + "'," + i + ");";
         ret += "\" ";
         //ret += this.items[i].action + "\" ";
         ret += "class='" + style + "'>&nbsp;" + this.items[i].label + "&nbsp;</a>";
         ret += "</td>";
      }
      ret += "</tr></table>";
      // Fin des onglets
      /*
      ret += "<table border='0' cellspacing='0' width='100%'><tr>";
      ret += "<td class='" + this.styleSelected + "'>";
      ret += "<table border='0' cellspacing='0' cellpadding ='0' height='3'><tr>";
      ret += "<td class='" + this.styleSelected + "'>";
      ret += "</td></tr></table></td></tr></table>";
      */
   }
   else
   {
      ret += "<table width='100%' cellspacing='0' border='0' cellpadding='0'>";
      for(var i=0; i<this.items.length; i++)
      {
         var style = (this.selectedIndex == i) ? this.styleSelected : this.styleNotSelected;
         ret += "<tr><td nowrap='true' class='" + style + "'>";
         ret += "<a href=\"javascript:HtmlTabView_setCurrentTab('" + this.div.id + "'," + i + ");";
         ret += "\" ";
         //ret += this.items[i].action + "\" ";
         ret += "class='" + style + "'>&nbsp;" + this.items[i].label + "&nbsp;</a>";
         //ret += "</td></tr><tr><td height='3'></td></tr>";
         ret += "</td></tr>";
      }
      ret += "</table>";
   }

   
   this.div.innerHTML = ret;
}

 

// Onglet onglet privé
function HtmlTab(label, action)
{
   this.label = label;
   this.action = action;
   return this;
}

// -----------------------------------------------------------------------------
//
function StringUtil_trim(str)
{
   return StringUtil_trimright(StringUtil_trimleft(str));
}
function StringUtil_trimleft(str)
{
   if ( str == null ) return;
   return str.replace( /^\s+/g, '');
} 
function StringUtil_trimright(str)
{
   if ( str == null ) return;
   return str.replace( /\s+$/g, '');
}

function StringUtil_toUpperCase(str)
{
   if ( str == null ) return;
   return str.toUpperCase();
}

String.prototype.trimleft = function ()
{
   return StringUtil_trimleft(this);
}
String.prototype.trimright = function ()
{
   return StringUtil_trimright(this);
}
String.prototype.trim = function ()
{
   return StringUtil_trim(this);
}
// Remplace dans la chaîne plusieurs occurrences à la suite de sep par un seul
// et renvoie la chaîne transformée
String.prototype.compressSepar = function(sep)
{
   var len = this.length;
   var ret = "";
   for (var i=0; i<len; i++)
   {
      var c = this.charAt(i);
      if ( c != sep ) ret += c;
   }
   return ret;
} 
// Renvoie la chaine de caractère passée en paramètre, 
// en ayant décodé les caractères octal \**** 
function decodeOctal(s)
{
   if ( s == null ) return null;
   var ret = "";
   var code = "";
   
   var len = s.length;
   for (var i=0; i<len; i++)
   {
      var c = s.charAt(i);
      switch ( c )
      {
         case '0':
         case '1':
         case '2':
         case '3':
         case '4':
         case '5':
         case '6':
         case '7':
            if ( code.length > 0 )
               code += c;
            else
               ret += c;
            break;
         case '\\':
         default:
         {
            // Il y avait quelque chose en cours, le décoder d'abord
            switch ( code.length )
            {
               case 0 : // rien encore dans code
                  if ( c == '\\')
                  {
                     code = c; // débute un nouveau
                  }
                  else
                  {
                     ret += c;
                  }
                  break;
               case 1 : // seulement \, on l'ajoute
                  ret += "\\";
                  if ( c != '\\' )
                  {
                     ret += c;
                     code = "";   
                  }
                  break;
               default : // \x au moins, à décoder
                  // Décodage et ajout du caractère
                  var toDecode = code.substring(1); // ne garde pas \
                  var icode = parseInt(toDecode, 8); 
                  ret += String.fromCharCode(icode);

                  if ( c == '\\')
                  {
                     // débute un nouveau
                     code = c;
                  }
                  else
                  {
                     ret += c;
                     code = "";
                  }
            }
         }
      }
   } // for
   
   // Ne pas oublier le dernier code !
   if ( code != null && code.length > 1) 
   {
      if ( code.length == 1 )
         ret += '\\';
      else
      {
         var toDecode = code.substring(1); // ne garde pas \
         var icode = parseInt(toDecode, 8); 
         ret += String.fromCharCode(icode);
      }
   } 
   return ret;   
}

// tdn 24/06/2005 Attention : les noms de fonctions 
// normalizeFieldName et unNormalizeFieldName prêtaient à confusion.
// Normaliser doit signifier 'Nom au norme XML'. 
// J'ajoute Tools_decorateFieldName pour lever l'ambiguité
function Tools_decorateFieldName(name)
{
   return unNormalizeFieldName(name);
}

// Si le nom commence par un chiffre, prefixe le nom avec le caractère underscore '_'
function normalizeFieldName(name)
{
  if ( ! isNaN(name.charAt(0)) )
     name = "_" + name;
  return name;
}

// Si le nom commence par '_', saute le premier caractère
function unNormalizeFieldName(name)
{
  if ( name.charAt(0) == '_' )
     name = name.substring(1);
  return name;
}

//
function appendDebug(txt)
{
   printDebug(txt, true);
}

//
function printDebug(txt, append)
{
   // Ouvre la fenêtre
   var win = window.open("", "win_debug",
  "toolbar=0,location=0,directories=0,menuBar=0,scrollbars=yes,resizable=yes" +
  ",width=" + 750 + ",height=" + 800 +
  ",top=" + 50 + ",left=" + 50);
   win.focus();
   
   if ( append == true ) if (win.document) if ( win.document.forms[0])
      txt = win.document.forms[0].elements["text"].value + '\n' + txt;

   // Passage suivant
   if (win.document) if ( win.document.forms[0])
   {
      win.document.forms[0].elements["text"].value = txt;
      return;  
   }
   // Premier passage
   win.document.write("<html><body><form name='frm'>");
   win.document.write("<input type='button' onclick='window.close()' value='Fermer' /><br />");
   win.document.write("<textarea name='text' cols='80' rows='40'>");
   win.document.writeln(txt);
   win.document.writeln("</textarea>");
   win.document.write("</form></body></html>");
   win.document.close();
   
}

// -----------------------------------------------------------------------------
// Objet RecordId
// A partir d'un recordId, permet de diposer des ces composantes
// Format d'un recordId :
// recordId = source:table:internalId|documentId
// -----------------------------------------------------------------------------
function RecordId(recordId)
{
   this.recordId = recordId;
   this.source = "default";
   this.table = "";
   this.internalId = "";
   this.documentId = "";
   
   if (recordId  &&  recordId != "")
      this.init();
      
   return this;
}

// Initialise les éléments de l'objet
RecordId.prototype.init = function ()
{
   var res = this.splitId();
   this.source = res[0];
   this.table = res[1];
   this.internalId = res[2];
   this.documentId = res[3];
}      

// Renvoie le recordId formaté
RecordId.prototype.getRecordId = function ()
{
   if (this.table != ""  &&  this.internalId != "")
      this.recordId = this.source + ':' + this.table  + ':' + this.internalId;
   return this.recordId;
}
// Renvoie la source
RecordId.prototype.getSource = function ()
{
   return this.source;
}
// Positionne la source
RecordId.prototype.setSource = function (source)
{
   this.source = source;
}
// Renvoie la table
RecordId.prototype.getTable = function ()
{
   return this.table;
}
// Positionne la table
RecordId.prototype.setTable = function (table)
{
   this.table = table;
}
// Renvoie l'internalId / le recordKey
RecordId.prototype.getInternalId = function ()
{
   return this.internalId;
}
// Positionne l'internalId / le recordKey
RecordId.prototype.setInternalId = function (internalId)
{
   this.internalId = internalId;
}
// Renvoie le documentId
RecordId.prototype.getDocumentId = function ()
{
   return this.documentId;
}
    
// Retourne les composantes clé de l'identifiant
// ret[0] ==> source
// ret[1] ==> table
// ret[2] ==> internalId <=> recordKey
// ret[3] ==> documentId : vaut null si pas de document attaché
RecordId.prototype.splitId = function ()
{
   var ret = new Array(4);
     
   // Découpe la valeur suivant '|' et ':' en partant de la fin
   // documentId éventuellement
   var recId = this.recordId;
   var pos = recId.lastIndexOf('|');
   if ( pos > - 1 )
   {
      ret[3]= recId.substring(pos+1);
      recId = recId.substring(0, pos);
   }
   // internalId <=> recordKey 
   pos = recId.lastIndexOf(':');
   if ( pos > -1)
   {
      ret[2] = recId.substring(pos+1);
      recId = recId.substring(0, pos);
   }
   // sourceName:TableName
   pos = recId.lastIndexOf(':');
   if ( pos > -1)
   {
      ret[1] = recId.substring(pos+1);
      ret[0] = recId.substring(0,pos); 
   }  
   
   return ret;
}


//-------------------------------------------------------
// Clone un tableau
function arrayClone (array)
{
   if ( ! array ) return null;
   var ret = new Array();
   for (var i in array)
   {
      ret[i] = array[i];
   }
   return ret;
}
