/*licence/ 

Module écrit, supporté par la société Alkante SAS <alkante@alkante.com>

Nom du module : Alkanet::Library
Librairie js et php globale à Alkanet.
Ce module appartient au framework Alkanet.

Ce logiciel est régi par la licence CeCILL-C soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL-C telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site http://www.cecill.info.

En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.

A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.

Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL-C, et que vous en avez accepté les
termes.

/licence*/

 verStr = navigator.appVersion;
app = navigator.appName;
version = parseFloat(verStr);
if( (app.indexOf('Netscape') != -1)&&(version <= 4.75) ) {
  // alert('netscape <= 4,75');
  var navigateur = "ecrit";
}
navigateur = navigator.appName;
x = null;
y = null;

/**
 * @brief Définition de document.getElementById si n'existe pas
 */
if (!document.getElementById){
  function _getElementById(elt_id)
  {
    var oElt = null;
    if ( document.getElementById && document.getElementById( elt_id ) ) {// Pour les navigateurs récents
       oElt = document.getElementById( elt_id );
    }
    else if ( document.all && document.all[ elt_id ] ) {// Pour les veilles versions
      oElt = document.all[ elt_id ];
    }
    else if ( document.layers && document.layers[ elt_id ] ) {// Pour les très veilles versions
      oElt = document.layers[ elt_id ];
    }
    return oElt;
  }
  document.getElementById = _getElementById;
}

/**
 * @brief Fonctions diverses
 */
function position(e) {
  var nH2, h2, v;
  x = (navigator.appName.substring(0,3) == "Net") ? e.pageX : event.x; //+document.body.scrollLeft;
  y = (navigator.appName.substring(0,3) == "Net") ? e.pageY : event.y; //+document.body.sc
}
function MM_reloadPage(init) { //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_showHideLayers() { //v3.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
  if  ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

/** Mémorise le niveau de la dernière popup ouverte, =0 pas de popup ouverte */
var iLevelAlkPopup = 0;

/**
 * @brief Retourne la référence de la fenêtre popup de niveau iLevel
 * @param iLevel   Niveau de la popup
 * @return Retourne la référence sur la fenêtre de niveau iLevel
 */
function GetWindowByNiv(iLevel)
{
  if( iLevel <=0 ) {
    return window;
  } 
  return top.window.document.getElementById("alkIFrameNiv"+iLevel.toString()).contentWindow;
}

/**
 * @brief Création d'une popup de niveau iLevel
 * @param iLevel  Niveau de la popup =1 pour la première
 * @return Retourne une référence sur le layer caractérisant la popup
 */
function addPopup(iLevel)
{
  var oWind = top.window;
  var oPopup = oWind.document.createElement("div");
  if( oPopup ) {
    oPopup.id        = "alkPopupNiv"+iLevel;
    oPopup.className = "windPopupNiv"+iLevel;
    oPopup.iAlkLevel = iLevel;
    var oStyle = ( oPopup.style ? oPopup.style : oPopup );
    oStyle.zIndex = 20000+(iLevel*2);
    // scrollHeight fonctionne : ie6, ie7 et firefox
    oStyle.height = top.document.documentElement.scrollHeight+"px";
    oWind.document.body.appendChild(oPopup);
    return oPopup;
  }
  return null;
}

/**
 * @brief Ferme la dernière popup ouverte
 * @param strUrlToken  url de réaffichage de l'opener. 
 *                     si la chaine ne contient pas .php, le paramètre est considéré comme un token
 *                     sur l'url alkanet.php
 *                     si la chaine = reload, un reload est effectué sur l'opener
 */
function removePopup(strUrlToken)
{
  var bClose = false;
  var iLevel = top.iLevelAlkPopup;
  var oOpenerIFrame = null;
  var iLevelNext = 0;
  var oPopup = top.document.getElementById("alkPopupNiv"+iLevel.toString());
  if( oPopup ) {
    // reaffiche l'opener si le tokenClose ou l'url sont fournis
    if( typeof(strUrlToken)!="undefined" && strUrlToken != "" ) {
      var iLevelOpener = iLevel-1;
      oOpenerIFrame = top.window;
      if( iLevelOpener >= 1 ) {
        oOpenerIFrame = top.document.getElementById("alkIFrameNiv"+iLevelOpener.toString());
      }

      // le paramètre &r=1 est présent pour éviter l'utilisation du cache navigateur
      if( strUrlToken == "reload" && oOpenerIFrame==top.window ) {
        oOpenerIFrame.location.reload();
      } else {
        var strUrl = ( strUrlToken.indexOf(".php")>-1 
                       ? strUrlToken+(strUrlToken.substr(-4)==".php" ? "?" : "&")+"r=1"
                       : ( isToken(strUrlToken)
                           ? "alkanet.php?token="+strUrlToken+"&r=1"
                           : strUrlToken ));
        if( oOpenerIFrame==top.window ) {
          oOpenerIFrame.location = strUrl;
        } else {
          oOpenerIFrame.src = strUrl;
        }
      }
    }
    
    top.iLevelAlkPopup = top.iLevelAlkPopup - 1;
    iLevelNext = top.iLevelAlkPopup;
    if (oPopup.popupFrame){
      oPopup.popupFrame.parentNode.removeChild(oPopup.popupFrame);
    }
    if ( iLevel==1 && oPopup.popupMsg ) {
      oPopup.popupMsg.parentNode.removeChild(oPopup.popupMsg);
    }
    oPopup.parentNode.removeChild(oPopup);
    delete(oPopup);
    bClose = true;
  }
  return bClose;
}

/**
 * @brief Ferme toute les popup ouvertes
 */
function removeAllPopup()
{
  var bClose = false;
  for(iLevel=1; iLevel<=top.iLevelAlkPopup; iLevel++) {
    var oOpenerIFrame = null;
    var oPopup = top.document.getElementById("alkPopupNiv"+iLevel.toString());
    if( oPopup ) {
      if( oPopup.popupFrame ) {
        oPopup.popupFrame.parentNode.removeChild(oPopup.popupFrame);
      }
      if( iLevel==1 && oPopup.popupMsg ) {
        oPopup.popupMsg.parentNode.removeChild(oPopup.popupMsg);
      }
      oPopup.parentNode.removeChild(oPopup);
      delete(oPopup);
      bClose = true;
    }
  }
  top.iLevelAlkPopup = 0;      
  
  return bClose;
}


/**
 * @brief ferme une fenêtre popup
 * @param strUrlToken  url de réaffichage de l'opener. 
 *                     si la chaine ne contient pas .php, le paramètre est considéré comme un token
 *                     sur l'url alkanet.php
 */
function closeWindow(strUrlToken) 
{ 
  return removePopup(strUrlToken);
}

/**
 * Verifie si le paramètre est un token
 * Vérification indépendante du mode de calcul
 * La regle utilisée : ne contient que des caractères hexa
 * @param strToken  valeur du token à tester
 * @return bool
 */
function isToken(strToken)
{
  var strPattern = "0123456789abcdef";
  var bRes = ( strToken.length % 2 == 0 );
  if( bRes ) {
    for(i=0; i < strToken.length; i++) {
      bRes=  bRes && ( strPattern.indexOf(strToken[i]) >= 0 );
    } 
  }
  return bRes;
}

/**
 * @brief ferme toutes les fenêtres popup ouverte
 * @param strUrlToken  url de réaffichage de l'opener. 
 *                     si la chaine ne contient pas .php, le paramètre est considéré comme un token
 *                     sur l'url alkanet.php
 */
function closeAllWindow(strUrlToken) 
{ 
  if( typeof(strUrlToken)!="undefined" && strUrlToken != "" ) {
    var oOpenerIFrame = top.window;
    if( strUrlToken == "reload" ) {
      oOpenerIFrame.location.reload();
    } else {
      var strUrl = ( strUrlToken.indexOf(".php")>-1 
                     ? strUrlToken+(strUrlToken.substr(-4)==".php" ? "?" : "&")+"r=1"
                     : ( isToken(strUrlToken)
                         ? "alkanet.php?token="+strUrlToken+"&r=1"
                         : strUrlToken ));
      oOpenerIFrame.location = strUrl;  
    }
    return true;
  }
  return removeAllPopup();
}

/**
 * @brief Crée une iframe cachée nommée 'footerExec' si n'existe pas, utilise l'existant sinon
 * @param strUrl Url à lire
 * @param @optionnal frameName Nom de la frame cachée
 */
function OpenFooterExec(strUrl)
{
  var strName = (arguments.length>1 ? arguments[1] : "footerExec");
  var oIFrame;
  if ( top.document.getElementById(strName) ) {
    oIFrame = top.document.getElementById(strName);
  } else {
    var oIFrame = top.document.createElement("iframe");
    oIFrame.id = strName;
    oIFrame.name = strName;
    oIFrame.style.display = 'none';
    top.document.body.appendChild(oIFrame);
    oIFrame.contentWindow.name = oIFrame.name;
  }
  AddWindOpener(oIFrame.name, top.window);
  oIFrame.src = strUrl;
  if ( arguments.length>2 && arguments[2] ){
  	return oIFrame;
  }
}

/**
 * @brief Simule l'ouverture d'une fenêtre popup dans un layer et iframe combinés
 * @param strUrl  url de iframe
 * @param iHeight hauteur de l'iframe
 * @param iWidth  largeur de l'iframe
 * @param strName Nom de l'iFrame
 * @return Une référence sur l'iframe ouverte
 */
function OpenWindow(strUrl, iHeight, iWidth, strName)
{
  if( top.iLevelAlkPopup > 4 ) {
    alert("Conception à revoir. Trop de popup.");
    return null;
  }
  
  var oWind = top;
  var oPopup = addPopup(top.iLevelAlkPopup+1);
  if( oPopup ) {
    top.iLevelAlkPopup = top.iLevelAlkPopup + 1;
    
    var windowWidth = ( top.window.innerWidth 
                        ? top.window.innerWidth 
                        : top.window.document.body.clientWidth );
    var windowHeight = ( top.window.innerHeight 
                         ? top.window.innerHeight 
                         : ( top.document.getElementsByTagName('html')[0].offsetHeight>=top.window.document.body.clientHeight
                            ? 0
                            : Math.min(top.document.getElementsByTagName('html')[0].offsetHeight, top.window.document.body.clientHeight) /*top.window.document.body.clientHeight : n'est pas satisfaisant */));
    
    var iLeft = Math.max(0, Math.floor((windowWidth - iWidth ) / 2));
    var iTop  = ( windowHeight>0
                  ? Math.max(0, Math.floor((windowHeight - iHeight ) / 2)) + top.document.documentElement.scrollTop
                  : 50+top.document.documentElement.scrollTop );
    
    var iWidth2 = 150, iHeight2 = 12;
    var iLeft2 = Math.floor((windowWidth - iWidth2 ) / 2);
    var iTop2  = ( windowHeight>0
                   ? Math.floor((windowHeight - iHeight2 ) / 2)+top.document.documentElement.scrollTop
                   : 50+top.document.documentElement.scrollTop );

    var oIFrame = top.document.createElement("iframe");
    oIFrame.id = "alkIFrameNiv"+oPopup.iAlkLevel.toString();
    oIFrame.name = ( !strName ? oIFrame.id : strName );

    var oOpener = window;//GetWindowByNiv(top.iLevelAlkPopup-1);
    AddWindOpener(oIFrame.name, oOpener);

    oIFrame.className = oPopup.className;
    var oStyle = getStyleObj(oIFrame);
    oStyle.width  = iWidth+"px";
    oStyle.height = iHeight+"px";
    
    var oPopup2 = createAbsoluteDiv("alkPopupFrameNiv"+top.iLevelAlkPopup, 
                                    iWidth, iHeight, iTop, iLeft, 20001+(top.iLevelAlkPopup*2));
    if ( !oPopup2 ) return;
    var oStyle = getStyleObj(oPopup2);
    oStyle.display = "block";
    
    if ( oWind.document.getElementById("alkPopupMsg") ){
      oPopup3 = oWind.document.getElementById("alkPopupMsg");
      var oStyle = getStyleObj(oPopup3);
      oStyle.display = "block";
    }
    else {
      var oPopup3 = createAbsoluteDiv("alkPopupMsg", iWidth2, iHeight2, iTop2, iLeft2, 30000);
      if ( !oPopup3 ) return;
      oPopup3.className = "windPopupMsg";
      oPopup3.innerHTML = "Chargement en cours...";
    }
    oIFrame.popupMsg = oPopup3;
    oIFrame.popupFrame = oPopup2;
    oIFrame.popupBackground = oPopup;
    oIFrame.iLevel = top.iLevelAlkPopup;
    
    oPopup.popupMsg = oPopup3;
    oPopup.popupFrame = oPopup2;
    
    oWind.document.body.appendChild(oPopup2);
    oPopup2.appendChild(oIFrame);
    oIFrame.src = strUrl;
    oWind.document.body.appendChild(oPopup3);
    oIFrame.contentWindow.name = oIFrame.name;
  }
  return oIFrame.contentWindow;
}

function HideLoadMsg()
{
  if ( top.document.getElementById("alkPopupMsg") ){
    var oMsg = top.document.getElementById("alkPopupMsg");
    var oStyle = getStyleObj(oMsg);
    oStyle.display = "none";
  }/*
  if ( typeof popupFrame != "undefined" ){
    var oStyle = getStyleObj( popupFrame );
    oStyle.display = "block";
  }*/
}

function createAbsoluteDiv(id, iWidth, iHeight, iTop, iLeft, zIndex){
  var oWind = top;
  var oPopup = oWind.document.createElement("div");
  oPopup.id = id;
  if( oPopup ) {
    var oStyle = getStyleObj(oPopup);
    oStyle.position = "absolute";
    oStyle.width  = iWidth+"px";
    oStyle.height = iHeight+"px";
    oStyle.top    = iTop+"px";
    oStyle.left   = iLeft+"px";
    oStyle.zIndex = zIndex;
  }
  return oPopup;
}

function getStyleObj(oObj)
{
  return ( oObj.style ? oObj.style : oObj );
}

/**
 * @brief Ouvre une vrai fenêtre popup
 * @param strUrl     url de iframe
 * @param iHeight    hauteur de l'iframe
 * @param iWidth     largeur de l'iframe
 * @param strName    Nom de l'iFrame (_blank par défaut)
 * @param strStatus  yes ou no pour afficher la barre de statut (yes par défaut)
 * @param strMenu    yes ou no pour afficher le menu (no par défaut)
 * @return Une référence sur l'iframe ouverte
 * 
 */
function OpenPopupWindow(strUrl, iHeight, iWidth, strName, strStatus, strMenu)
{
  if( !strName ) strName = "_blank";
  if( !strStatus ) strStatus = "yes";
  if( !strMenu ) strMenu = "no";

  var hauteur_popup = (typeof iHeight=="undefined" ? 400 : iHeight);
  var largeur_popup = (typeof iWidth=="undefined" ? 520 : iWidth);
  var H = (screen.height - hauteur_popup) / 2;
  var L = (screen.width - largeur_popup) / 2;

  AddWindOpener(strName, window);

  popupWindow = window.open(strUrl, strName, 
    "status="+strStatus+",menubar="+strMenu+
    ",scrollbars=yes,resizable=yes,height="+hauteur_popup+
    ",width="+largeur_popup+",top="+H+",left="+L);
  if( !popupWindow ) {
    alert("Attention, votre navigateur bloque l'ouverture de fenêtre popup.\n"+
          "Vous devez autoriser l'ouverture de popup pour ce site.");
  } else {
    popupWindow.id = strName;
  }
  return popupWindow;
}

/**
 * @brief Mémorise l'opener pour une fenêtre
 * @param strName  Nom de la fenêtre
 * @param oOpener  Référence sur sa fenêtre opener
 */
function AddWindOpener(strName, oOpener)
{
  if( typeof(top.navigator.AlkOpener) == "undefined" || top.navigator.AlkOpener.constructor.toString().indexOf("Array()") < 0 ) {
    top.navigator.AlkOpener = new Array();
  }
  top.navigator.AlkOpener[strName] = oOpener;
}

/**
 * @brief Retourne la référence sur la fenêtre ouvreuse de la popup courante
 * @return référence sur objet de type window
 */
function GetWindowOpener()
{
  var strName = ( window.name == "" ? "_top" : window.name );
  var oOpener = null;
  if( typeof(top.navigator.AlkOpener[strName]) != "undefined" ) {
    oOpener = top.navigator.AlkOpener[strName];
  }
  return oOpener;
}

/**
 * @brief Appel une url par le biais du javascript (nécessaire lien sur event onclick)
 * @param strUrl  Url de redirection
 */
function AlkGoUrl(strUrl)
{
  window.location = strUrl;
}

/**
 * @brief Affiche une confirmation avec strMsg avant d'appeler strLink
 * @param strLink  Url appelée après confirmation
 * @param strMsg   Message de confirmation
 */
function Confirmation(strLink, strMsg)
{
  var strTmp = "Veuillez confirmer la suppression ?";
  
  if( typeof(strMsg) != 'undefined' ) strTmp = strMsg;
  var res = window.confirm(strTmp);
  if( res ) document.location.href = strLink;
}

/**
 * @brief Affiche une confirmation avant d'appeler l'url effectuant
 *        la suppression en utilisant le token
 * @param strToken  token pour suppression
 */
function DeleteData(strToken)
{
  var strMsg = "Veuillez confirmer la suppression de cette information ?";
  if ( arguments.length>1 )
    strMsg = arguments[1];
  Confirmation(ALK_ALKANET_SQL+"?token="+strToken, strMsg);
}

/**
 * @brief Demande confirmation avant de fermer la session
 */
function CloseSession()
{
  var res = window.confirm("Vous allez fermer votre session. Confirmer ?");
  if( res ) top.document.location.href = ALK_ALKANET_IDENT+"?fin=1";
}

/**
 * @brief Ouvre la fenêtre d'aide
 */
function OpenHelp(strToken)
{
   var ht = 400;
   var lg = 950;
   var t = (screen.height-ht)/2;
   var l = (screen.width-lg)/2;
   var strPage = "alkanet_help.php?token="+strToken;
   window.open(strPage, 'WindowHelp',
               'status=yes,scrollbars=yes,resizable=yes,height='+ht+',width='+lg+',top='+t+',left='+l);
}

/**
 * Ouvre la popup de calcul de performance
 */
function OpenPerf(strToken)
{
  OpenWindow("alkanet.php?token="+strToken, "230", "400", "windPerf");
}

/**
 * Ouvre la popup de calcul de performance
 */
function OpenContactAdmin(strToken)
{ 
  OpenWindow("alkanet.php?token="+strToken, "380", "550", "windContact");
}

/**
 * @brief Gestion encodage de token
 * @todo A vérifier
 */

function TextEncode(strParam)
{
  var t = new String("test");
  if (!t.charCodeAt) return strParam;
  strParam = encodeToUTF8(strParam);
  var strEncode = "";
  for(var i=0; i<strParam.length; i++) {
    strEncode += DecToHexa(strParam.charCodeAt(i));
  }
/*
  var bCheckSum = (arguments.length==1 || arguments[1]);
  if ( bCheckSum ){
    var iChecksum = getCheckSumEncodage(strEncode);
    strEncode += TextEncode("&ALK_CHECKSUM="+iChecksum, false);
  }*/
  return strEncode;
}

function TextDecode(strParam)
{  
  var test = "";
  var t = new String("test");
  if (!t.fromCharCode && !String.fromCharCode) return strParam;
  //décodage
  var strDecode = "";
  for(var i=0; i<strParam.length; i+=2 ) {
    strDecode = new String(strDecode) + String.fromCharCode( HexaToDec(strParam.substr(i, 2) ) ) ;
  }

  return decodeFromUTF8(strDecode);
}

function DecToHexa(integer, bIter){
  var tabConv = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F");
  if (integer<=15 ) {
    if( bIter) return tabConv[integer]; 
    return "0"+tabConv[integer];
  }
  var quotient = Math.floor(integer/16);
  var remainder = integer % 16;
  return new String(DecToHexa(quotient,true))+new String(DecToHexa(remainder,true));
}

function HexaToDec(hexa){
  var tabConv = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F");
  if (hexa.length==1){
    for (var j=0; j<tabConv.length; j++){
      if (tabConv[j].toLowerCase()==hexa.toLowerCase()) return j;
    }
    return 0;
  }
  var res = 0;
  for (var p=0; p<hexa.length; p++){
    res = new Number( new Number(res) + new Number(HexaToDec(hexa.charAt(p))*Math.pow(16, hexa.length - p -1)) );
  }
  return res;
}
function encodeToUTF8(strLatin1) 
{
  var strUTF8 = "";

  for (var n = 0; n < strLatin1.length; n++) {
    var c = strLatin1.charCodeAt(n);
    if (c < 128) {
      strUTF8 += String.fromCharCode(c);
    }
    else if((c > 127) && (c < 2048)) {
      strUTF8 += String.fromCharCode((c >> 6) | 192);
      strUTF8 += String.fromCharCode((c & 63) | 128);
    }
    else {
      strUTF8 += String.fromCharCode((c >> 12) | 224);
      strUTF8 += String.fromCharCode(((c >> 6) & 63) | 128);
      strUTF8 += String.fromCharCode((c & 63) | 128);
    }
  }

  return strUTF8;
}
    
function decodeFromUTF8(strUTF8) {
  var strLatin1 = "";
  var i = 0;
  var c = c1 = c2 = 0;

  while ( i < strUTF8.length ) {
    c = strUTF8.charCodeAt(i);
    if (c < 128) {
      strLatin1 += String.fromCharCode(c);
      i++;
    }
    else if((c > 191) && (c < 224)) {
      c2 = strUTF8.charCodeAt(i+1);
      strLatin1 += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
      i += 2;
    }
    else {
      c2 = strUTF8.charCodeAt(i+1);
      c3 = strUTF8.charCodeAt(i+2);
      strLatin1 += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
      i += 3;
    }
  }

  return strLatin1;
}
function getCheckSumEncodage(strToken)
{
  var tabTrad = new Array();
  for(var i=0; i<10; i++) tabTrad[i] = i;
  tabTrad["A"] = tabTrad["a"] = 10;
  tabTrad["B"] = tabTrad["b"] = 11;
  tabTrad["C"] = tabTrad["c"] = 12;
  tabTrad["D"] = tabTrad["d"] = 13;
  tabTrad["E"] = tabTrad["e"] = 14;
  tabTrad["F"] = tabTrad["f"] = 15;
   
  var iChecksum = 0;
  for(i=0; i<strToken.length; i++) {
    iChecksum += parseInt(tabTrad[strToken.charAt(i)]);
  }
  return iChecksum;
}
/**
 * @brief construit un token à partir des paramètres donnés. 
 *        La partie cont_id et appli_id est donnée par la variable globale ALK_APPLI_TOKEN (utilisé par cette fonction)
 * ATTENTION : Les paramètres supplémentaires (strParam) ne doivent pas contenir de caractères accentués
 * @param iTypeSheet  Identifiant du type d'onglet
 * @param iSheet      Identifiant de l'onglet
 * @param iSSheet     Identifiant du sous-onglet
 * @param strParam (option) Chaine de paramètres supplémentaires. ATTENTION : caractères accentués non acceptés
 * @return string : token d'une url
 */
function getToken(iTypeSheet, iSheet, iSSheet, strParam)
{
  if ( typeof strParam=="undefined" )
    strParam = "";
 
  var strAppliToken = "";
  if ( typeof ALK_APPLI_TOKEN=="undefined" ){
    strAppliToken = "";
  }
  else 
    strAppliToken = ALK_APPLI_TOKEN;
  if ( arguments.length>4 ){
    strAppliToken = TextEncode(arguments[4], false);
  }
 
  var strToken = "&iTypeSheet="+iTypeSheet+"&iSheet="+iSheet+"&iSSheet="+iSSheet+strParam;
  strToken = TextEncode(strToken, false);
  strToken = strAppliToken+strToken;
  /*var iChecksum = getCheckSumEncodage(strToken);
  strToken += TextEncode("&ALK_CHECKSUM="+iChecksum, false);*/
  
  return strToken;
}
/**
 * Retourne la chaine d'évaluation d'une variable définie (typeof xxx != 'undefined')
 * @param  param_name    Nom de la variable à évaluer
 * @return string   retourne la chaine d'évaluation d'une variable définie
 */
function getStrIsDefined(param_name)
{
  return "typeof "+param_name+' != "undefined"';
}
/**
 * Change le titre d'un onglet
 * @param iSheet  numero de l'onglet
 * @param newName nouveau titre de l'onglet
 */
function setSheetName(iSheet, newName) 
{
  // un onglet est défini par la structure : 
  // <li id="sheetHeader_contents_contents_sheetXX" ...><a onclick="action...">Sheet Name</a></li>
  var sheet = document.getElementById('sheetHeader_contents_contents_sheet'+iSheet);
  if ( sheet )
    sheet.firstChild.innerHTML = newName;
}
/**
 * Retourne dans une chaine la  liste couples paramètres/valuers d'un formulaire pour une intégration dans URL
 * 
 * @param oForm réfèrence sur le formulaire à analyser. 
 * @return string 
 */
function convertFormValuesToUrlParam(oForm) 
{
  var getstr = "";
  for (i=0; i<oForm.childNodes.length; i++) {
  if (oForm.childNodes[i].tagName == "INPUT") {
        if (oForm.childNodes[i].type == "text") {
           getstr += oForm.childNodes[i].name + "=" + oForm.childNodes[i].value + "&";
        }
        if (oForm.childNodes[i].type == "hidden") {
           getstr += oForm.childNodes[i].name + "=" + oForm.childNodes[i].value + "&";
        }
        if (oForm.childNodes[i].type == "checkbox") {
           if (oForm.childNodes[i].checked) {
              getstr += oForm.childNodes[i].name + "=" + oForm.childNodes[i].value + "&";
           } else {
              getstr += oForm.childNodes[i].name + "=&";
           }
        }
        if (oForm.childNodes[i].type == "radio") {
           if (oForm.childNodes[i].checked) {
              getstr += oForm.childNodes[i].name + "=" + oForm.childNodes[i].value + "&";
           }
        }
     }   
     if (oForm.childNodes[i].tagName == "SELECT") {
        var sel = oForm.childNodes[i];
        getstr += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
     }
     
  }
  return getstr;
}
/**
 * Retourne dans une chaine la  liste couples paramètres/valuers d'un formulaire pour une intégration dans URL
 * 
 * @param thingId nom de l'entité à rendre visible 
 * @return string 
 */
function visible(thingId)
{
  var targetElement;
  targetElement = document.getElementById(thingId);
  if (targetElement.style.display == "none" ){
    targetElement.style.display = "block" ;
  }
}	
/**
 * Retourne dans une chaine la  liste couples paramètres/valuers d'un formulaire pour une intégration dans URL
 * 
 * @param thingId nom de l'entité à rendre invisible 
 * @return string 
 */
function invisible(thingId)
{
  var targetElement;
  targetElement = document.getElementById(thingId) ;
  targetElement.style.display = "none" ;
}
/**
 * Change la propriété display de l'objet block si invisible, none si visible
 * 
 * @param thingId nom de l'entité à rendre visible ou invisible 
 * @return string 
 */
function OpenCloseHtmlBlock(thingId, strClassStyleShow, strClassStyleHide)
{	
  var oTbody = document.getElementById(thingId+"_tbody") ;
  var oTd = document.getElementById(thingId+"_tdtitle") ;
  if (!(oTbody && oTd))
    return;
  if (oTbody.style.display == "none" ){
    oTd.className = oTd.className.replace(new RegExp("("+strClassStyleHide+")", "g"), strClassStyleShow);	        	        
    oTbody.style.display = "" ;
  } else {
    oTd.className = oTd.className.replace(new RegExp("("+strClassStyleShow+")", "g"), strClassStyleHide);
    oTbody.style.display = "none" ;
  }
}
/**
 * charge une nouvelle image
 * @param idImg  identifiant du ctrl image à mettre à jour
 */
function loadSecureImg(idImg)
{
  var oImg = document.getElementById(idImg);
  if( oImg ) {
    var strAlea = new String(Math.random());
    strAlea = strAlea.substr(2);
    oImg.src = ALK_ALKANET_ROOT_URL+"scripts/alkanet/alkanet_security_image.php?i="+strAlea;
  }
}
