/**
 * Editeur de texte "riche"
 * 
 * Pour transformer un textarea en zone d'édition html,
 * Appeler cette librairie et la feuille de style:
 * 
 * $xpage->js[] = 'libs/rich_text.js';
 * $xpage->css[] = 'libs/rich_text.css';
 * 
 * Ajouter l'une des deux classes sur le textarea:
 *  - "texte-html-mini" => éditeur basique (mise en forme: gras, italique, souligné)
 *  - "texte-html" => éditeur complet (ajout de tableau, d'image)
 *  
 */


addListenner(window, "load", loadRichTextEditor, true);


try {
    user_pref("capability.policy.policynames", "allowclipboard");
    user_pref("capability.policy.allowclipboard.Clipboard.paste", "allAccess");
} catch (e) {}


// Cache les zones de texte si le javascript est activé, évite les "clignotements"
var MainStyle  = '';
    MainStyle += '    <style type="text/css">\r\n';
    MainStyle += '    form textarea.editorarea {\r\n';
    MainStyle += '      display : none;\r\n';
    MainStyle += '    }\r\n';
    MainStyle += '    </style>\r\n';
document.write(MainStyle);


var frameHtmlCode  = '\r\n';
    //frameHtmlCode += '  <head>\r\n';
    frameHtmlCode += '    <style type="text/css">\r\n';
    frameHtmlCode += '      body {\r\n';
    frameHtmlCode += '        text-align : left;\r\n';
    frameHtmlCode += '        background : #f0efef;\r\n';
    frameHtmlCode += '        color : #464646;\r\n';
    frameHtmlCode += '        font-family : Arial, Geneva, Helvetica, Sans-Serif;\r\n';
    frameHtmlCode += '        font-size : 0.7em;\r\n';
    frameHtmlCode += '        padding : 0.4em;\r\n';
    frameHtmlCode += '        margin : 0;\r\n';
    frameHtmlCode += '        border : none;\r\n';
    frameHtmlCode += '        cursor : text;\r\n';
    frameHtmlCode += '        \r\n';
    frameHtmlCode += '      }\r\n';
    frameHtmlCode += '      \r\n';
    frameHtmlCode += '      ';
    frameHtmlCode += '      html {\r\n';
    frameHtmlCode += '        cursor : text;\r\n';
    frameHtmlCode += '      }\r\n';
    frameHtmlCode += '      \r\n';
    frameHtmlCode += '      ul, ol {\r\n';
    frameHtmlCode += '        padding-left : 16px;\r\n';
    frameHtmlCode += '        margin-left : 0;\r\n';
    frameHtmlCode += '        list-style: disc inside\r\n';
    frameHtmlCode += '      }\r\n';
    frameHtmlCode += '      \r\n';
    frameHtmlCode += '      ol {\r\n';
    frameHtmlCode += '        list-style: decimal inside\r\n';
    frameHtmlCode += '      }\r\n';
    frameHtmlCode += '      ';
    frameHtmlCode += '      table td {\r\n';
    frameHtmlCode += '        padding : .5em;\r\n';
    frameHtmlCode += '      }\r\n';
    frameHtmlCode += '      ';
    frameHtmlCode += '    </style>\r\n';
    //frameHtmlCode += '  </head>\r\n';



var iframe_l = new Array;

var toolbarSmall  = new Array('bold', 'italic', 'underline', 'espace', 'justifyleft',
                              'justifyfull', 'justifyright', 'justifycenter', 'espace',
                              'insertorderedlist', 'insertunorderedlist', 'espace',
                              'outdent', 'indent', 'espace', 'createlink');

var toolbarSmall_title  = new Array('Gras', 'Italique', 'Souligné', 'espace', 'Aligné à gauche',
                              'Justifié', 'Aligné a droite', 'Centré', 'espace',
                              'Liste numérique', 'Liste à puce', 'espace',
                              'Diminuer la marge a gauche', 'Augmenter la marge a gauche',
                              'espace', 'Nouveau lien externe');


var toolbarNormal = new Array('formatblock', 'applyFont', 'fontSize', 'espace', 'removeformat',
                              'createlink', 'createinternallink', 'unlink', 'espace', 'copy', 'paste', 'espace', 'inserthorizontalrule',
                              'saut-ligne',
                              'undo', 'redo', 'espace', 'bold', 'italic', 'underline', 'espace', 'justifyleft',
                              'justifycenter', 'justifyfull', 'justifyright', 'espace',
                              'insertorderedlist', 'insertunorderedlist', 'espace', 'outdent',
                              'indent', 'espace', 'forecolor', 'backcolor', 'table', 'insertimage');

var toolbarNormal_title = new Array('Formattage de texte', 'Police', 'Taille du texte', '', 'supprimer le format',
                          'Nouveau lien externe', 'Nouveau lien interne', 'Enlever le lien', '', 'copier', 'coller', '', 'Barre horizontale',
                          '', 'Annuler', 'Refaire', '', 'Gras', 'Italique', 'Souligné', '', 'Aligné à gauche',
                          'Centre', 'Justifié', 'Aligné a droite', '',
                          'Liste numérique', 'Liste à puce', '', 'Diminuer la marge a gauche',
                          'Augmenter la marge a gauche', '', 'Changer la couleur du texte', 'Changer la couleur du fond',
                          'Insérer un tableau', 'Insérer une image');

var formats = new Array('', 'H1', 'H2', 'h3', 'h4', 'h5', 'h6', 'p', 'code', 'pre');
var formats_labels  = new Array('Format', 'Titre 1', 'Titre 2', 'Titre 3',
                        'Titre 4', 'Titre 5', 'Titre 6', 'Paragraphe', 'Code', 'pre');

var polices = new Array('', 'Arial, Helvetica, sans-serif',
                        'Courier New, Courier, mono', 'Times New Roman, Times, serif',
                        'Verdana, Arial, Helvetica, sans-serif');

var polices_labels = new Array('', 'Arial', 'Courier', 'Times', 'Verdana');


var colorpicker = new splashBox('color-picker');


//var editorParam = [];


function buildColorPalette ()
{
    var tableCode = '';
    tableCode += '<table border="0" cellpadding="0" cellspacing="0">';
    var couleurs = new Array;
    var n = 0;
    for (var i = 0; i <= 255; i += 85) {
        for (var j = 0; j <= 255; j += 85) {
            for (var k = 0; k <= 255; k += 85) {
                //if (n < 128)
                couleurs[n++] = 'rgb(' + i + ',' + j + ',' + k + ')';
            }
        }
    }

    //alert(couleurs.length);
    tableCode += '    <tr>';
    for (var i = 0; i < couleurs.length; i++) {
        tableCode += '        <td><a href="javascript:void(0);" style="background-color : ' + couleurs[i] + ';"></a></td>';
        if ((i+1) % 8 == 0) {
            tableCode += '</tr><tr>';
        }
    }
    tableCode += '    </tr>';
    tableCode += '</table>';
    tableCode += '<div id="color-preview">';
    tableCode += '</div>';
    tableCode += '<div class="color-basic">';
    tableCode += '<a href="javascript:void(0);" style="background-color : #000;"></a>';
    tableCode += '<a href="javascript:void(0);" style="background-color : #333;"></a>';
    tableCode += '<a href="javascript:void(0);" style="background-color : #666;"></a>';

    tableCode += '<a href="javascript:void(0);" style="background-color : #999;"></a>';
    tableCode += '<a href="javascript:void(0);" style="background-color : #ccc;"></a>';
    tableCode += '<a href="javascript:void(0);" style="background-color : #fff;"></a>';

    tableCode += '<a href="javascript:void(0);" style="background-color : #f00;"></a>';
    tableCode += '<a href="javascript:void(0);" style="background-color : #0f0;"></a>';
    tableCode += '<a href="javascript:void(0);" style="background-color : #00f;"></a>';

    tableCode += '<a href="javascript:void(0);" style="background-color : #ff0;"></a>';
    tableCode += '<a href="javascript:void(0);" style="background-color : #0ff;"></a>';
    tableCode += '<a href="javascript:void(0);" style="background-color : #f0f;"></a>';

    tableCode += '</div>';
    return tableCode;
}




/**
 * Créé l'objet barre d'outils (gras, italique, etc.)
 */
function getToolBar(id, editorType)
{
    // Creation des outils d'édition de texte
    var toolbar = document.createElement('div');
    var actionsList, labelsList;

    if (editorType != null && editorType == 0) {
        toolbar.className = 'toolbar smalltoolbar';
        actionsList = toolbarSmall;
        labelsList  = toolbarSmall_title;

    } else {
        toolbar.className = 'toolbar';
        actionsList = toolbarNormal;
        labelsList  = toolbarNormal_title;
    }


    var ul = document.createElement('ul');
    for (var k = 0; k < actionsList.length; k++) {

      var action = actionsList[k];
      var li = document.createElement('li');

      if (action == "espace") {
        // rien à faire

      } else if (action == "saut-ligne") {
        // rien à faire

      } else if (action == "formatblock") {
        var select = document.createElement('select');
        select.name = 'format-' + id;
        select.id = 'format-' + id;
        select.className = action;
        select.onchange = formatManager;
        select.setAttribute('tabindex', -1);

        for (var m = 0; m < formats.length; m++) {
            var option = document.createElement('option');
            option.value = '<' + formats[m] + '>';

            if (formats[m] != '') {
                var labelvalue = '<' + formats[m] + '>' + formats_labels[m] + '</' + formats[m] + '><br class="spacer"/>';
                option.innerHTML = labelvalue;
            } else {
                option.appendChild(document.createTextNode(formats_labels[m]));
            }
            select.appendChild(option);
        }
        li.appendChild(select);

      } else if (action == "applyCSS") {
        var select = document.createElement('select');
        select.name = 'css-' + id;
        select.id = 'css-' + id;
        select.className = action;
        select.setAttribute('tabindex', -1);
        //select.onchange = formatManager;

        var option = document.createElement('option');
        option.value = "normal";
        option.appendChild(document.createTextNode('Texte normal'));
        select.appendChild(option);

        var option = document.createElement('option');
        option.value = "error";
        option.appendChild(document.createTextNode('Erreur'));
        select.appendChild(option);

        li.appendChild(select);

      } else if (action == "applyFont") {
        var select = document.createElement('select');
        select.name = 'font-' + id;
        select.id = 'font-' + id;
        select.className = action;
        select.onchange = formatManager;
        select.setAttribute('tabindex', -1);

        for (var m = 0; m < polices.length; m++) {
            var option = document.createElement('option');
            option.value = polices[m];

            if (formats[m] != '') {
                var labelvalue = '<span style="font-family : ' + polices[m] + ';">' + polices_labels[m] + '</span>';
                option.innerHTML = labelvalue;
            } else {
                option.appendChild(document.createTextNode(polices[m]));
            }
            select.appendChild(option);
        }
        li.appendChild(select);

      } else if (action == "fontSize") {
        var select = document.createElement('select');
        select.name = 'size-' + id;
        select.id = 'size-' + id;
        select.className = action;
        select.onchange = formatManager;
        select.setAttribute('tabindex', -1);

        for (var m = 0; m < 8; m++) {
            var option = document.createElement('option');
            option.value = m;

            if (formats[m] != '') {
                var labelvalue = m; //'<span style="font-size : ' + m + ';">' + m + '</span>';
                option.innerHTML = labelvalue;
            } else {
                option.appendChild(document.createTextNode(m));
            }
            select.appendChild(option);
        }
        li.appendChild(select);


        } else {
          // lien de l'action (gras, italique, etc.)
          var a = document.createElement('span');
          //a.href = "#";
          a.onmousedown = formatManager;
          a.onclick = function() { return false; };
          //a.onkeypress = function(e) { formatManager(e, this); return false; };
          //a.className = action;
          a.id = action + '-' + action + '-' + id;
          a.title = labelsList[k];
          //a.setAttribute('tabindex', -1);
          a.appendChild(document.createTextNode(' '));
          li.appendChild(a);
      }

      li.className = action;
      ul.appendChild(li);

      if (action == "inserthorizontalrule") {
          var br = document.createElement('br');
          br.className = 'spacer';
          //ul.appendChild(br);
      }
    }
    toolbar.appendChild(ul);

    return toolbar;
} // end of function "getToolBar()"



/**
 * Met à jour le champ caché correspondant à la zone de texte
 */
function updateField(inputId, frameId)
{
  if (document.getElementById && document.getElementById(frameId).contentWindow) {
    document.getElementById(inputId).value = document.getElementById(frameId).contentWindow.document.body.innerHTML;

  } else if (document.all && document.all[frameId] && document.all[frameId].contentWindow) {
    document.all[inputId].value = document.all[frameId].contentWindow.document.body.innerHTML;
  }
}



function getSel(win)
{
  if (win.getSelection) {
    return win.getSelection();

  } else if (win.document.getSelection) {
    return win.document.getSelection();

  } else if (win.document.selection) {
    return win.document.selection.createRange().text;

  } else return;
}


// Sauvegarde la selection en cours
// (utile pour la palette de couleurs et l'insertion d'images)
var selectionRange;
function setRange(frameId) {
  var obj = new getObj(frameId).obj;
  if (obj.contentWindow) {
      obj = obj.contentWindow;
  }

  if (obj.getSelection) {
      var selection = obj.getSelection();
      selectionRange = selection.getRangeAt(selection.rangeCount - 1).cloneRange();

  } else if (obj.document.selection) {
      selectionRange = obj.document.selection.createRange();
  }

  return selectionRange;
}




  function insertNodeAtSelection(win, insertNode)
  {
      // get current selection
      var sel = getSel(win); //win.getSelection();

      // get the first range of the selection
      // (there's almost always only one range)
      var range = sel.getRangeAt(0);

      // deselect everything
      sel.removeAllRanges();

      // remove content of current selection from document
      range.deleteContents();

      // get location of current selection
      var container = range.startContainer;
      var pos = range.startOffset;

      // make a new range for the new selection
      range=document.createRange();

      if (container.nodeType==3 && insertNode.nodeType==3) {

        // if we insert text in a textnode, do optimized insertion
        container.insertData(pos, insertNode.nodeValue);

        // put cursor after inserted text
        range.setEnd(container, pos+insertNode.length);
        range.setStart(container, pos+insertNode.length);

      } else {


        var afterNode;
        if (container.nodeType==3) {

          // when inserting into a textnode
          // we create 2 new textnodes
          // and put the insertNode in between

          var textNode = container;
          container = textNode.parentNode;
          var text = textNode.nodeValue;

          // text before the split
          var textBefore = text.substr(0,pos);
          // text after the split
          var textAfter = text.substr(pos);

          var beforeNode = document.createTextNode(textBefore);
          afterNode = document.createTextNode(textAfter);

          // insert the 3 new nodes before the old one
          container.insertBefore(afterNode, textNode);
          container.insertBefore(insertNode, afterNode);
          container.insertBefore(beforeNode, insertNode);

          // remove the old node
          container.removeChild(textNode);

        } else {

          // else simply insert the node
          afterNode = container.childNodes[pos];
          container.insertBefore(insertNode, afterNode);
        }

        range.setEnd(afterNode, 0);
        range.setStart(afterNode, 0);
      }

      sel.addRange(range);
  }




function insertHTML(html, frameId, win)
{
  var obj = new getObj(frameId, win).obj;

  if (obj.contentWindow) {
      obj = obj.contentWindow;
  }

  obj.focus();
  if (document.selection) {
    var selPos = obj.document.selection.createRange();
    selPos.pasteHTML(html);
    selPos.collapse(false);
    selPos.select();
  } else {
    obj.document.execCommand('insertHTML', false, html);
  }
}




/**
 * Insère un tableau aux dimensions demandées par l'utilisateur
 */
function insertTable(anchorId, frameId)
{
  var tableInfos;
  try {
      tableInfos = prompt('Saisissez le nombre de lignes et de colonnes separées par une virgule (ex : "2,3"):', '').split(',');
  } catch (e) {}

  if (!tableInfos) return false;
  var rows = tableInfos[0];
  var cols = tableInfos[1];

  var tableHTML = '';
  tableHTML += '<table border="1" class="tableau-editeur" id="matable" cellpadding="0" cellspacing="0">';
  tableHTML += '<tbody>';
  for (var i=0; i < rows; i++) {
    tableHTML += '<tr>';
    for (var j=0; j < cols; j++) {
      tableHTML += '<td>';
      tableHTML += '&nbsp;';
      tableHTML += '</td>';
    }
    tableHTML += '</tr>';
  }
  tableHTML += '</tbody>';
  tableHTML += '</table>';
  insertHTML(tableHTML, frameId);

  return false;

} // end of function "insertTable()"





/**
 * Affiche la palette de couleurs
 */
function showPalette(anchorId, frameId, action)
{
  setRange(frameId);
  colorpicker.attachToAnchor(anchorId, 20, -60);
  colorpicker.toggleVisibility(colorpicker.id, 'visible');

  var listeCellules = colorpicker.obj.getElementsByTagName('a');
  for (var el = 0; el < listeCellules.length; el++) {
      eval('listeCellules[el].onclick = function (e) {colorpicker_getColor(e, this, "' + frameId + '", "' + action + '"); return true;};');
      eval('listeCellules[el].onmouseover = function (e) {document.getElementById("color-preview").style.backgroundColor = this.style.backgroundColor; return true;};');
  }

    //color-preview
  return false;
} // end of function "showPalette()"



/**
 * change la couleur
 */
function colorpicker_getColor(e, o, frameId, action)
{
    var color = '#000000';
    //alert(o.nodeName + ' ' + o.style.backgroundColor);

    if (o.style && o.style.backgroundColor && o.style.backgroundColor != null) {
        color = o.style.backgroundColor;
    }

    if (selectionRange.select) selectionRange.select();
    colorpicker.toggleVisibility(colorpicker.id, 'hidden');
    editor_runCommand(frameId, action, color);

    return true;
}


/**
 * Execute une commande sur une iframe editable
 */
function getFrameElement(frameId, win)
{
  var access = new getObj(frameId, win).obj;

  if (access.contentWindow) {
    return access.contentWindow.document;

  } else if (access.document) {
    return access.document;
  }

  return access;
}

/**
 * Execute une commande sur une iframe editable
 */
function editor_runCommand(frameId, action, value, win)
{
  var option = false;
  var access = getFrameElement(frameId, win);

  if (access.focus) access.focus();
  access.execCommand(action, option, value);
  if (access.focus) access.focus();

  return true;
} // end of function "editor_runCommand()"



function popUpWin (url, win, width, height, options) {
  var leftPos = (screen.availWidth - width) / 2;
  var topPos = (screen.availHeight - height) / 2;
  options += 'width=' + width + ',height=' + height + ',left=' + leftPos + ',top=' + topPos;
  //window.open(url, win, options);
  window.open(url, 'zoomillustration', options + ', toolbar=no, menubar=no, location=no, resizable=yes, scrollbars=yes, status=no');
  return false;
}


/**
 * Change l'apparence d'une partie du texte
 */
function formatManager()
{
  // remonte jusqu'au niveau de l'iframe et du champ cache
  var node = this.parentNode;
  var action = node.className;

  while (node.getElementsByTagName('iframe').length <= 0) {
    node = node.parentNode;
  }
  var inputId = node.getElementsByTagName('input')[0].id;
  var frameId = node.getElementsByTagName('iframe')[0].id;

  // Actions a effectuer
  if (action == 'forecolor' || action == 'backcolor') {
    showPalette(this.id, frameId, action);

  } else if (action == 'insertimage') {
    setRange(frameId);
    //alert(node.nodeName + ' : ' + node.className + ', id : ' + node.id + ', mini : ' + node.imgmini + ', zoom : ' + node.imgzoom);
    var url = 'upload_popup.php?frameid=' + frameId + '&selection=' + selectionRange;
    if (node.imgmini) {
      url += '&imgmini=' + node.imgmini;
    }
    if (node.imgzoom) {
      url += '&imgzoom=' + node.imgzoom;
    }
    if (node.table) {
      url += '&table=' + node.table;
    }
    if (node.tableid) {
      url += '&tableid=' + node.tableid;
    }
    if (node.activerurl) {
      url += '&activerurl=' + node.activerurl;
    }
    if (node.activermini) {
      url += '&activermini=' + node.activermini;
    }
    if (node.activerzoom) {
      url += '&activerzoom=' + node.activerzoom;
    }
    if (node.activeralignement) {
      url += '&activeralignement=' + node.activeralignement;
    }

    //popUpWin (url, win, width, height, options)
    popUpWin(url, 'uploadimage', '650', '300', '');

  } else if (action == 'table') {
    insertTable(this.id, frameId);

  } else if (action == 'formatblock') {
      if (this.value != '') {
          editor_runCommand(frameId, action, this.value);
      }

  } else if (action == 'applyFont') {
      if (this.value != '') {
          editor_runCommand(frameId, 'fontname', this.value);
      }

  } else if (action == 'fontSize') {
      if (this.value != '') {
          editor_runCommand(frameId, 'fontsize', this.value);
      }

  } else if (action == 'createlink') {
      var url;
      url = prompt('Entrez l\'adresse de destination', 'http://');
      if (!url) return false;
      //editor_runCommand(frameId, action, url);
      replaceSelection(frameId, '<a href="' + url + '" target="_blank" class="lien-externe" rel="external">', '</a>', url);


  } else if (action == 'createinternallink') {
      var url;
      url = prompt('Entrez le chemin vers la page à partir de la racine', '');
      if (!url) return false;
      replaceSelection(frameId, '<a href="#LIEN_INTERNE#' + url + '">', '</a>', url);
      return;


  } else if (action != '') {
    editor_runCommand(frameId, action, null);
  }
  updateField(inputId, frameId);

  return false;
} // end of function "formatManager()"



/**
 * replaceSelection
 */
 function replaceSelection(frameId, startCode, endCode, defaultCode)
 {
      // lecture de la sélection si elle existe
      var obj = document.getElementById(frameId); //new getObj(frameId).obj;
      if (obj.contentWindow) {
          obj = obj.contentWindow;
      }
      var selObj, selObjTxt;

      if (obj.document.selection && obj.document.selection.createRange) {
         selObj = obj.document.selection.createRange();
         selObjTxt = selObj.text;

      } else if (obj.getSelection) {
         selObjTxt = selObj = obj.getSelection();
         //selObj.deleteFromDocument();
      }

      // Ecriture
      var htmlStr = startCode;
      if (selObjTxt != '') {
        htmlStr += selObjTxt + endCode;
        insertHTML(htmlStr, frameId);

      } else {
        htmlStr += defaultCode + endCode;
        insertHTML(htmlStr, frameId);
      }

 } // end of "replaceSelection()"





var limite = 0;
function activateIframe(inputId, frameId, value)
{
    if (!value || value == '' || value == null) {
        value = ' '; //&nbsp;
    }

    // Ecrit le contenu de l'iframe

    var frameHtml = '';
    var stylesheet = '';
	//<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> 
	//<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    //frameHtml += '<?xml version="1.0" encoding="ISO-8859-1"?>\r\n';
    frameHtml += '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r\n';
    frameHtml += '<html id="' + frameId + '" xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">\r\n';
    
    //frameHtml += '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">\r\n';
    //frameHtml += '<html id="' + frameId + '">\r\n';
    
    frameHtml += '  <head>\r\n';
    //frameHtml += '      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />\r\n';

    /*styles = document.getElementsByTagName('link');
    for (var i=0; i<styles.length; i++) {
        if (styles[i].rel && styles[i].rel == 'stylesheet') {
            stylesheet += '<link rel="stylesheet" type="text/css" href="' + styles[i].href + '" />';
        }
    }*/

    //frameHtml += stylesheet;
    frameHtml += '  </head>\r\n';
    frameHtml += frameHtmlCode;
    frameHtml += '  <body>';
    frameHtml += value;
    frameHtml += '  </body>';
    frameHtml += '</html>';

    // Active le mode d'edition, charge le texte et ajoute l'action de mise a jour
    try {
        var iframe = new getObj(frameId).obj;
        if (iframe.contentWindow) {
          iframe = iframe.contentWindow;
        }
        iframe = iframe.document;
        iframe.designMode = "on";
        iframe.open();
        iframe.write(frameHtml);
        iframe.close();

        eval('var fAction = function () { updateField("' + inputId + '", "' + frameId + '"); return false; }');

        // Place une fonction de mise a jour sur perte de focus
        if (iframe.addEventListener) {
          iframe.addEventListener("blur", fAction, true);
          iframe.addEventListener("mouseout", fAction, true);

        } else if (iframe.attachEvent) {
          iframe.attachEvent("onblur", fAction, true);
          iframe.attachEvent("onmouseout", fAction, true);

        } else {
          iframe.onmouseout = fAction;
          iframe.onblur = fAction;
        }
        return true;

    } catch (e) {
      limite++;
      //alert('Un probleme est survenu (IE5 n\'est pas supporte pour le moment)');
      //DBG_msg('RichTextEditor: Iframe can\'t be loaded. (IE 5 not supported).', 'error');
      if (limite < 3) {
        setTimeout('activateIframe("' + inputId + '", "' + frameId + '", "' + value + '");', 10);
      }
      return true;
    }
}


/**
 * Remplace les zones de texte de classe "editorarea" par les editeurs de texte "riches"
 */
function loadRichTextEditor()
{
    //DBG_msg('RichTextEditor: Loading...', 'info');
  // Si on n'a pas le minimum, on quitte
  if ((!document.getElementById && !frames) || !document.designMode) {
    return false;
  }

  // liste les zones de texte, ne garde que celles a remplacer
  var editorType = new Array;
  var editorSize = [];
  var editorParam = [];
  var textarea = document.getElementsByTagName('textarea');
  var editorlist = new Array;
  var j = 0;
  for (var i = 0; i < textarea.length; i++) {
     if (/texte-html-mini/.test(textarea[i].className)) {
      textarea[i].className = 'texte-html';
      editorType[j] = 0;

    } else if (/texte-html/.test(textarea[i].className)) {
      editorType[j] = 1;
    }


    if (/texte-html/.test(textarea[i].className) || /texte-html-mini/.test(textarea[i].className)) {
      editorParam[j] = {};
      editorSize[j] = [textarea[i].clientWidth, textarea[i].clientHeight];
      editorlist[j] = textarea[i];

      if (/insertion-mini-/.test(textarea[i].className)) {
        var valeurTaille = textarea[i].className.split('insertion-mini-');
        valeurTaille = valeurTaille[1].split(' ');
        editorParam[j]['img-mini'] = valeurTaille[0];
      }
      if (/insertion-zoom-/.test(textarea[i].className)) {
        var valeurTaille = textarea[i].className.split('insertion-zoom-');
        valeurTaille = valeurTaille[1].split(' ');
        editorParam[j]['img-zoom'] = valeurTaille[0];
      }
      if (/table-/.test(textarea[i].className)) {
        var valeurTaille = textarea[i].className.split('table-');
        valeurTaille = valeurTaille[1].split(' ');
        editorParam[j]['table'] = valeurTaille[0];
      }
      if (/tableid-/.test(textarea[i].className)) {
        var valeurTaille = textarea[i].className.split('tableid-');
        valeurTaille = valeurTaille[1].split(' ');
        editorParam[j]['tableid'] = valeurTaille[0];
      }
      if (/activer-url/.test(textarea[i].className)) {
        editorParam[j]['activer-url'] = true;
      }
      if (/activer-mini/.test(textarea[i].className)) {
        editorParam[j]['activer-mini'] = true;
      }
      if (/activer-zoom/.test(textarea[i].className)) {
        editorParam[j]['activer-zoom'] = true;
      }
      if (/activer-alignement/.test(textarea[i].className)) {
        editorParam[j]['activer-alignement'] = true;
      }
      j++;
    }

  } // end for



  //alert('editorlist.length : ' + editorlist.length);

  // Pour chaque zone de texte à traiter,
  // On cree une iframe, la barre d'outils, et un champ cache
  for (var i = 0; i < editorlist.length; i++) {

    //alert('dimensions : ' + editorSize[i][0] + 'x' + editorSize[i][1]);

    // Cree le code de remplacement de la zone de texte : toolbar + iframe + champ cache
    var frameId  = 'editorframe-' + i;
    var iframe    = document.createElement('iframe');
    iframe.id     = frameId;
    iframe.name   = frameId;
    iframe.setAttribute('name', frameId);
    //iframe.style.width = editorSize[i][0] + 'px';
    iframe.style.height = (editorSize[i][1] + 10) + 'px';

    var input   = document.createElement('input');
    input.type  = "hidden";
    input.name  = editorlist[i].name;
    input.id    = editorlist[i].id;
    input.value = editorlist[i].value;

    var editor    = document.createElement('div');
    if (/error/.test(editorlist[i].className)) {
        editor.className = 'rich-editor error';
    } else {
        editor.className = 'rich-editor';
    }


    if (editorParam[i]['img-mini']) {
      editor['imgmini'] = editorParam[i]['img-mini'];
      editor.setAttribute('imgmini', editorParam[i]['img-mini']);
    }
    if (editorParam[i]['img-zoom']) {
      editor['imgzoom'] = editorParam[i]['img-zoom'];
      editor.setAttribute('imgzoom', editorParam[i]['img-zoom']);
    }
    if (editorParam[i]['table']) {
      editor['table'] = editorParam[i]['table'];
      editor.setAttribute('table', editorParam[i]['table']);
    }
    if (editorParam[i]['tableid']) {
      editor['tableid'] = editorParam[i]['tableid'];
      editor.setAttribute('tableid', editorParam[i]['tableid']);
    }
    if (editorParam[i]['activer-url']) {
      editor['activerurl'] = 1;
      editor.setAttribute('activerurl', 1);
    }
    if (editorParam[i]['activer-mini']) {
      editor['activermini'] = 1;
      editor.setAttribute('activermini', 1);
    }
    if (editorParam[i]['activer-zoom']) {
      editor['activerzoom'] = 1;
      editor.setAttribute('activerzoom', 1);
    }
    if (editorParam[i]['activer-alignement']) {
      editor['activeralignement'] = 1;
      editor.setAttribute('activeralignement', 1);
    }

    editor.style.width = (editorSize[i][0] + 28) + 'px';
    //editor.style.height = (editorSize[i][1] + 50) + 'px';
    var tool_bar = getToolBar(i, editorType[i]);

    editor.appendChild(tool_bar);
    editor.appendChild(iframe);

    editorlist[i].parentNode.replaceChild(editor, editorlist[i]);
    document.getElementById(frameId).parentNode.appendChild(input);

    // Ecrit le contenu de l'iframe
    limite = 0;
    activateIframe(input.id, frameId, editorlist[i].value);

  } // fin du parcours de cette liste

  // initialise la palette de couleurs
  var innerbox = document.createElement('div');
  innerbox.innerHTML = buildColorPalette();

  colorpicker.init(innerbox);
  //DBG_msg('RichTextEditor: Done.', 'info');

  return true;
} // end of function "loadRichTextEditor()"


