
document.write('<style type="text/css">\n');
document.write('.btn     { width: 22px; height: 22px; border: 1px solid buttonface; margin: 0; padding: 0; }\n');
document.write('.btnOver { width: 22px; height: 22px; border: 1px outset; }\n');
document.write('.btnDown { width: 22px; height: 22px; border: 1px inset; background-color: buttonhighlight; }\n');
document.write('.btnNA   { width: 22px; height: 22px; border: 1px solid buttonface; filter: alpha(opacity=25); }\n');
document.write('.cMenu     { background-color: threedface; color: menutext; cursor: Default; font-family: MS Sans Serif; font-size: 8pt; padding: 2 12 2 16; }');
document.write('.cMenuOver { background-color: highlight; color: highlighttext; cursor: Default; font-family: MS Sans Serif; font-size: 8pt; padding: 2 12 2 16; }');
document.write('.cMenuDivOuter { background-color: threedface; height: 9 }');
document.write('.cMenuDivInner { margin: 0 4 0 4; border-width: 1; border-style: solid; border-color: threedshadow threedhighlight threedhighlight threedshadow; }');
document.write('</style>\n');


/* ---------------------------------------------------------------------- *\
  Funcion    : editor_ConfigPorDefecto
  Descripcion : configuracion por defecto del wysiwyg 
\* ---------------------------------------------------------------------- */

function editor_configPorDefecto(nombreObj) {

this.version = "2.03"

this.width =  "auto";
this.height = "auto";
this.bodyStyle = 'background-color: #FFFFFF; font-family: "Verdana"; font-size: x-small;';
this.imgURL = _editor_url + 'images/';
this.debug  = 0;

this.replaceNextlines = 0; 
this.plaintextInput = 0;   

this.toolbar = [
    ['fontname'],
    ['fontsize'],
    ['bold','italic','underline','separator'],
    ['justifyleft','justifycenter','justifyright','separator'],
    ['OrderedList','UnOrderedList','Outdent','Indent','separator'],
    ['forecolor','backcolor','separator'],
//    ['HorizontalRule','Createlink','InsertImage','InsertTable','separator']];
    ['HorizontalRule','Createlink','InsertImage','separator']];
	//'htmlmodo',

this.fontnames = {
    "Arial":           "arial, helvetica, sans-serif",
    "Courier New":     "courier new, courier, mono",
    "Georgia":         "Georgia, Times New Roman, Times, Serif",
    "Tahoma":          "Tahoma, Arial, Helvetica, sans-serif",
    "Times New Roman": "times new roman, times, serif",
    "Verdana":         "Verdana, Arial, Helvetica, sans-serif",
    "impact":          "impact",
    "WingDings":       "WingDings"};

this.fontsizes = {
    "8":  "1",
    "10": "2",
    "12": "3",
    "14": "4",
    "18": "5",
    "24": "6",
    "36": "7"
  };

this.btnList = {
    // Nombre boton:  ID comando,           	titulo,  	              	al hacer click,                   imagen,             
    "bold":           ['Bold',                 'Negrita',            		'editor_accion(this.id)',  			'ed_format_bold.gif'],
    "italic":         ['Italic',               'Cursiva',            		'editor_accion(this.id)',  			'ed_format_italic.gif'],
    "underline":      ['Underline',            'Subrayado',          		'editor_accion(this.id)',  			'ed_format_underline.gif'], 
    "subscript":      ['SubScript',            'Subíndice',          		'editor_accion(this.id)',  			'ed_format_sub.gif'],
    "superscript":    ['SuperScript',          'Superíndice',        		'editor_accion(this.id)',  			'ed_format_sup.gif'],
    "justifyleft":    ['JustifyLeft',          'Alinear a la izquierda',	'editor_accion(this.id)',  			'ed_align_left.gif'],
    "justifycenter":  ['JustifyCenter',        'Centrar',     				'editor_accion(this.id)',  			'ed_align_center.gif'],
    "justifyright":   ['JustifyRight',         'Alinear a la derecha', 		'editor_accion(this.id)',  			'ed_align_right.gif'],
    "orderedlist":    ['InsertOrderedList',    'Numeración',    	   		'editor_accion(this.id)',  			'ed_list_num.gif'],
    "unorderedlist":  ['InsertUnorderedList',  'Viñetas',		      		'editor_accion(this.id)',  			'ed_list_bullet.gif'],
    "outdent":        ['Outdent',              'Reducir sangría',    		'editor_accion(this.id)',  			'ed_indent_less.gif'],
    "indent":         ['Indent',               'Aumentar sangría',    		'editor_accion(this.id)',  			'ed_indent_more.gif'],
    "forecolor":      ['ForeColor',            'Color de fuente',     		'editor_accion(this.id)',  			'ed_color_fg.gif'],
    "backcolor":      ['BackColor',            'Resaltar',			   		'editor_accion(this.id)',  			'ed_color_bg.gif'],
    "horizontalrule": ['InsertHorizontalRule', 'Linea horizontal',    		'editor_accion(this.id)',			'ed_hr.gif'],
    "createlink":     ['CreateLink',           'Insertar Enlace',  	  		'editor_accion(this.id)',  			'ed_link.gif'],
    "insertimage":    ['InsertImage',          'Insertar Imagen',      		'editor_accion(this.id)',  			'ed_image.gif'],
    "inserttable":    ['InsertTable',          'Insertar Tabla',       		'editor_accion(this.id)',  			'insert_table.gif']
    //"htmlmodo":       ['Htmlmodo',             'Ver Código HTML',   		'editor_modo(\''+nombreObj+'\')', 	'ed_html.gif']
   };
}

/* ---------------------------------------------------------------------- *\
  Funcion     : editor_generar
  Descripcion : reemplaza el textarea por wysiwyg
  Uso         : editor_generar("id_textarea",[alto],[ancho]);
  Argumentos  : nombreObj - ID of textarea to replace
                an       - ancho del wysiwyg
                al       - alto del wysiwyg
\* ---------------------------------------------------------------------- */


function editor_generar(nombreObj,ConfigUsuario) {
 var config = new editor_configPorDefecto(nombreObj);
  if (ConfigUsuario) { 
    for (var thisName in ConfigUsuario) {
      if (ConfigUsuario[thisName]) { config[thisName] = ConfigUsuario[thisName]; }
    }
  }
  document.all[nombreObj].config = config;                  
  
  var obj    = document.all[nombreObj];
  if (!config.width || config.width == "auto") {
    if      (obj.style.width) { config.width = obj.style.width; }      
    else if (obj.cols)        { config.width = (obj.cols * 8) + 22; }  
    else                      { config.width = '100%'; }               
  }
  if (!config.height || config.height == "auto") {
    if      (obj.style.height) { config.height = obj.style.height; }   
    else if (obj.rows)         { config.height = obj.rows * 17 }       
    else                       { config.height = '200'; }              
  }

  var tblOpen  = '<table border=0 cellspacing=0 cellpadding=0 style="float: left;"  unselectable="on"><tr><td style="border: none; padding: 1 0 0 0"><nobr>';
  var tblClose = '</nobr></td></tr></table>\n';

  // contruye los botones de la barra de herramientas

  var toolbar = '';
  var btnGroup, btnItem, aboutEditor;
  for (var btnGroup in config.toolbar) {

    // linebreak
    if (config.toolbar[btnGroup].length == 1 &&
        config.toolbar[btnGroup][0].toLowerCase() == "linebreak") {
      toolbar += '<br clear="all">';
      continue;
    }

    toolbar += tblOpen;
    for (var btnItem in config.toolbar[btnGroup]) {
      var btnName = config.toolbar[btnGroup][btnItem].toLowerCase();

      // nombre de funte
      if (btnName == "fontname") {
        toolbar += '<select id="_' +nombreObj+ '_FontName" onChange="editor_accion(this.id)" unselectable="on" style="margin: 1 2 0 2; font-size: 12px;">';
        for (var fontname in config.fontnames) {
          toolbar += '<option value="' +config.fontnames[fontname]+ '">' +fontname+ '</option>'
        }
        toolbar += '</select>';
        continue;
      }

      // tamaño de fuente
      if (btnName == "fontsize") {
        toolbar += '<select id="_' +nombreObj+ '_FontSize" onChange="editor_accion(this.id)" unselectable="on" style="margin: 1 2 0 0; font-size: 12px;">';
        for (var fontsize in config.fontsizes) {
          toolbar += '<option value="' +config.fontsizes[fontsize]+ '">' +fontsize+ '</option>'
        }
        toolbar += '</select>\n';
        continue;
      }

      // font style
      if (btnName == "fontstyle") {
        toolbar += '<select id="_' +nombreObj+ '_FontStyle" onChange="editor_accion(this.id)" unselectable="on" style="margin: 1 2 0 0; font-size: 12px;">';
        + '<option value="">Font Style</option>';
        for (var i in config.fontstyles) {
          var fontstyle = config.fontstyles[i];
          toolbar += '<option value="' +fontstyle.className+ '">' +fontstyle.name+ '</option>'
        }
        toolbar += '</select>';
        continue;
      }

      // separador
      if (btnName == "separator") {
        toolbar += '<span style="border: 1px inset; width: 1px; font-size: 16px; height: 16px; margin: 0 3 0 3"></span>';
        continue;
      }

      // botones
      var btnObj = config.btnList[btnName];
      if (btnName == 'linebreak') { alert("htmlArea error: 'linebreak' must be in a subgroup by itself, not with other buttons.\n\nhtmlArea wysiwyg editor not created."); return; }
      if (!btnObj) { alert("htmlArea error: button '" +btnName+ "' not found in button list when creating the wysiwyg editor for '"+nombreObj+"'.\nPlease make sure you entered the button name correctly.\n\nhtmlArea wysiwyg editor not created."); return; }
      var btnCmdID   = btnObj[0];
      var btnTitle   = btnObj[1];
      var btnOnClick = btnObj[2];
      var btnImage   = btnObj[3];
      toolbar += '<button title="' +btnTitle+ '" id="_' +nombreObj+ '_' +btnCmdID+ '" class="btn" onClick="' +btnOnClick+ '" onmouseover="if(this.className==\'btn\'){this.className=\'btnOver\'}" onmouseout="if(this.className==\'btnOver\'){this.className=\'btn\'}" unselectable="on"><img src="' +config.imgURL + btnImage+ '" border=0 unselectable="on"></button>';


    } 
    toolbar += tblClose;
  } 

  // construye editor

  var editor = '<span id="_editor_toolbar"><table border=0 cellspacing=0 cellpadding=0 bgcolor="buttonface" style="padding: 1 0 0 2" width=' + config.width + ' unselectable="on"><tr><td>\n'
  + toolbar
  + '</td></tr></table>\n'
  + '</td></tr></table></span>\n'
  + '<textarea ID="_' +nombreObj + '_editor" style="width:' +config.width+ '; height:' +config.height+ '; margin-top: -1px; margin-bottom: -1px;" wrap=soft></textarea>';

  // añade menu contextuales
  editor += '<div id="_' +nombreObj + '_cMenu" style="position: absolute; visibility: hidden;"></div>';

  //  oculta el textarea original e inserta htmlarea
  if (!config.debug) { document.all[nombreObj].style.display = "none"; }

  if (config.plaintextInput) {     //reemplaza los /r y /n por <br>
    var contents = document.all[nombreObj].value;
    contents = contents.replace(/\r\n/g, '<br>');
    contents = contents.replace(/\n/g, '<br>');
    contents = contents.replace(/\r/g, '<br>');
    document.all[nombreObj].value = contents;
  }

  // inserta wysiwyg
  document.all[nombreObj].insertAdjacentHTML('afterEnd', editor)

  // convert htmlarea from textarea to wysiwyg editor
  editor_modo(nombreObj, 'init');

  // llama al filtro de salida 
  for (var idx=0; idx < document.forms.length; idx++) {
    var r = document.forms[idx].attachEvent('onsubmit', function() { editor_filtroSalida(nombreObj); });
    if (!r) { alert("Error attaching event to form!"); }
  }

return true;

}

/* ---------------------------------------------------------------------- *\
  Funcion    : editor_accion
  Descripcion : ejecuta un comando al seleccionar un boton del editor
  Uso       :
  Argumentos   : id_boton - boton id cadena del editor y nombre de la accion
\* ---------------------------------------------------------------------- */

function editor_accion(id_boton) {

  
  var BtnParts = Array();
  BtnParts = id_boton.split("_");
  var nombreObj    = id_boton.replace(/^_(.*)_[^_]*$/, '$1');
  var cmdID      = BtnParts[ BtnParts.length-1 ];
  var button_obj = document.all[id_boton];
  var editor_obj = document.all["_" +nombreObj + "_editor"];
  var config     = document.all[nombreObj].config;


  // checkea modo editor 
  if (editor_obj.tagName.toLowerCase() == 'textarea') { return; }

  var editdoc = editor_obj.contentWindow.document;
  editor_foco(editor_obj);

  var idx = button_obj.selectedIndex;
  var val = (idx != null) ? button_obj[ idx ].value : null;

  if (0) {}  

  // Nombre fuente
  else if (cmdID == 'FontName' && val) {
    editdoc.execCommand(cmdID,0,val);
  }

  // Tamaño Fuente
  else if (cmdID == 'FontSize' && val) {
    editdoc.execCommand(cmdID,0,val);
  }
  // Color de fondo y de letra
  else if (cmdID == 'ForeColor' || cmdID == 'BackColor') {
    var oldcolor = color(editdoc.queryCommandValue(cmdID));
    var newcolor = showModalDialog(_editor_url + "seleccionar_color.html", oldcolor, "resizable: no; help: no; status: no; scroll: no;");
    if (newcolor != null) { editdoc.execCommand(cmdID, false, "#"+newcolor); }
  }

  
  else {
    if (cmdID.toLowerCase() == 'subscript' && editdoc.queryCommandState('superscript')) { editdoc.execCommand('superscript'); }
    if (cmdID.toLowerCase() == 'superscript' && editdoc.queryCommandState('subscript')) { editdoc.execCommand('subscript'); }

    // insertar link
    if (cmdID.toLowerCase() == 'createlink'){
      editdoc.execCommand(cmdID,1);
    }

    // insertar imagen
    else if (cmdID.toLowerCase() == 'insertimage'){
      showModalDialog(_editor_url + "insertar_imagen.html", editdoc, "resizable: no; help: no; status: no; scroll: no; ");
    }

    // insertar tabla
    else if (cmdID.toLowerCase() == 'inserttable'){
      showModalDialog(_editor_url + "insertar_tabla.html?"+nombreObj,
                                 window,
                                 "resizable: yes; help: no; status: no; scroll: no; ");
    }

   else { editdoc.execCommand(cmdID); }
  }

  editor_evento(nombreObj);
}

/* ---------------------------------------------------------------------- *\
  Funcion    	: editor_evento
  Descripcion 	: llamada cada vez que ocurre un evento en el editor
  Uso       	: editor_evento(nombreObj, retardo, nombreEvento)
  Argumentos   	: nombreObj - ID del textarea a reemplazar
                retardo: -1  = ahora, da igual que ocurra
                          0  = ahora
                        1000 = en un 1 sec
\* ---------------------------------------------------------------------- */

function editor_evento(nombreObj,retardo) {
  var config = document.all[nombreObj].config;
  var editor_obj  = document.all["_" +nombreObj+  "_editor"];       // html editor object
  if (retardo == null) { retardo = 0; }
  var editdoc;
  var editEvent = editor_obj.contentWindow ? editor_obj.contentWindow.event : event;

  // catch keypress events
    if (editEvent && editEvent.keyCode) {
      var ord       = editEvent.keyCode;    // orden ascii de las teclas pulsadas
      var ctrlKey   = editEvent.ctrlKey;
      var altKey    = editEvent.altKey;
      var shiftKey  = editEvent.shiftKey;

      if (ord == 16) { return; }  // ignora la tecla mayusculas
      if (ord == 17) { return; }  // ignore la tecla ctrl
      if (ord == 18) { return; }  // ignore la tecla alt

      if (ctrlKey && (ord == 122 || ord == 90)) {     
        return;
      }
      if ((ctrlKey && (ord == 121 || ord == 89)) ||
          ctrlKey && shiftKey && (ord == 122 || ord == 90)) {   

        return;
      }
    }

  if (retardo > 0) { return setTimeout(function(){ editor_evento(nombreObj); }, retardo); }

  if (this.tooSoon == 1 && retardo >= 0) { this.queue = 1; return; } 
  this.tooSoon = 1;
  setTimeout(function(){
    this.tooSoon = 0;
    if (this.queue) { editor_evento(nombreObj,-1); };
    this.queue = 0;
    }, 333);  // 1/3 segundos


  editor_modSalida(nombreObj);
  editor_modBarraH(nombreObj);
}

/* ---------------------------------------------------------------------- *\
  Funcion     : editor_modBarraH
  Descripcion : modifica el estado de la barra de herramientas
  UsO         :
  Argumentos  : nombreObj - ID del textarea a reemplazar
                accion  - habilitar, deshabilitar, o modificar (accion por defecto)
\* ---------------------------------------------------------------------- */

function editor_modBarraH(nombreObj,action) {
  var config = document.all[nombreObj].config;
  var editor_obj  = document.all["_" +nombreObj+  "_editor"];

  // deshabilitar o habilitar la barra de herramientas

  if (action == "enable" || action == "disable") {
    var tbItems = new Array('FontName','FontSize','FontStyle');                           
    for (var btnName in config.btnList) { tbItems.push(config.btnList[btnName][0]); } 

    for (var idxN in tbItems) {
      var cmdID = tbItems[idxN].toLowerCase();
      var tbObj = document.all["_" +nombreObj+ "_" +tbItems[idxN]];
      if (cmdID == "htmlmodo" || cmdID == "about" || cmdID == "showhelp" || cmdID == "popupeditor") { continue; } 
      if (tbObj == null) { continue; }
      var isBtn = (tbObj.tagName.toLowerCase() == "button") ? true : false;

      if (action == "enable")  { tbObj.disabled = false; if (isBtn) { tbObj.className = 'btn' }}
      if (action == "disable") { tbObj.disabled = true;  if (isBtn) { tbObj.className = 'btnNA' }}
    }
    return;
  }

  // modificar el estado de la barra de herramientas

  if (editor_obj.tagName.toLowerCase() == 'textarea') { return; }   // no modificar el estado en modo de edicion de texto
  var editdoc = editor_obj.contentWindow.document;

  var fontname_obj = document.all["_" +nombreObj+ "_FontName"];
  if (fontname_obj) {
    var fontname = editdoc.queryCommandValue('FontName');
    if (fontname == null) { fontname_obj.value = null; }
    else {
      var found = 0;
      for (i=0; i<fontname_obj.length; i++) {
        if (fontname.toLowerCase() == fontname_obj[i].text.toLowerCase()) {
          fontname_obj.selectedIndex = i;
          found = 1;
        }
      }
      if (found != 1) { fontname_obj.value = null; }     // para fuentes que no estan en la lista
    }
  }

  var fontsize_obj = document.all["_" +nombreObj+ "_FontSize"];
  if (fontsize_obj) {
    var fontsize = editdoc.queryCommandValue('FontSize');
    if (fontsize == null) { fontsize_obj.value = null; }
    else {
      var found = 0;
      for (i=0; i<fontsize_obj.length; i++) {
        if (fontsize == fontsize_obj[i].value) { fontsize_obj.selectedIndex = i; found=1; }
      }
      if (found != 1) { fontsize_obj.value = null; }     // para tamaños que no estan en la lista
    }
  }

  // modifica el estado del boton
  var IDList = Array('Bold','Italic','Underline','StrikeThrough','SubScript','SuperScript','JustifyLeft','JustifyCenter','JustifyRight','InsertOrderedList','InsertUnorderedList');
  for (i=0; i<IDList.length; i++) {
    var btnObj = document.all["_" +nombreObj+ "_" +IDList[i]];
    if (btnObj == null) { continue; }
    var cmdActive = editdoc.queryCommandState( IDList[i] );

    if (!cmdActive)  {                                  
      if (btnObj.className != 'btn') { btnObj.className = 'btn'; }
      if (btnObj.disabled  != false) { btnObj.disabled = false; }
    } else if (cmdActive)  {                            
      if (btnObj.className != 'btnDown') { btnObj.className = 'btnDown'; }
      if (btnObj.disabled  != false)   { btnObj.disabled = false; }
    }
  }
}

/* ---------------------------------------------------------------------- *\
  Funcion     : editor_modSalida
  Descripcion : modifica las casillas de salida ocultas por datos del wysiwg
\* ---------------------------------------------------------------------- */

function editor_modSalida(nombreObj) {
  var config     = document.all[nombreObj].config;
  var editor_obj  = document.all["_" +nombreObj+  "_editor"];       // editor html
  var editEvent = editor_obj.contentWindow ? editor_obj.contentWindow.event : event;
  var isTextarea = (editor_obj.tagName.toLowerCase() == 'textarea');
  var editdoc = isTextarea ? null : editor_obj.contentWindow.document;

  var contents;
  if (isTextarea) { contents = editor_obj.value; }
  else            { contents = editdoc.body.innerHTML; }

  if (config.lastUpdateOutput && config.lastUpdateOutput == contents) { return; }
  else { config.lastUpdateOutput = contents; }

  document.all[nombreObj].value = contents;

}

/* ---------------------------------------------------------------------- *\
  Function    : editor_filtroSalida
  Description :
\* ---------------------------------------------------------------------- */

function editor_filtroSalida(nombreObj) {
  editor_modSalida(nombreObj);
  var contents = document.all[nombreObj].value;
  var config   = document.all[nombreObj].config;

  if (contents.toLowerCase() == '<p>&nbsp;</p>') { contents = ""; }
  var filterTag = function(tagBody,tagName,tagAttr) {
    tagName = tagName.toLowerCase();
    var closingTag = (tagBody.match(/^<\//)) ? true : false;

    if (tagName == 'img') { tagBody = tagBody.replace(/(src\s*=\s*.)[^*]*(\*\*\*)/, "$1$2"); }
    if (tagName == 'a')   { tagBody = tagBody.replace(/(href\s*=\s*.)[^*]*(\*\*\*)/, "$1$2"); }
    return tagBody;
  };


  RegExp.lastIndex = 0;
    var matchTag = /<\/?(\w+)((?:[^'">]*|'[^']*'|"[^"]*")*)>/g;   

  contents = contents.replace(matchTag, filterTag);

  if (config.replaceNextlines) { 
    contents = contents.replace(/\r\n/g, ' ');
    contents = contents.replace(/\n/g, ' ');
    contents = contents.replace(/\r/g, ' ');
  }

  document.all[nombreObj].value = contents;

}

/* ---------------------------------------------------------------------- *\
  Funcion     : editor_modo
  Descripcion : cambia el modo entre WYSIWYG y editor de HTML
  Uso         : editor_modo(nombreObj, modo);
  Argumentos  : nombreObj - boton id cadena para el editor y nombre de la accion
                modo      - inicial, editor de texto, o wysiwyg
\* ---------------------------------------------------------------------- */

function editor_modo(nombreObj, modo) {
  var config     = document.all[nombreObj].config;
  var editor_obj = document.all["_" +nombreObj + "_editor"];

  if (document.readyState != 'complete') {
    setTimeout(function() { editor_modo(nombreObj,modo) }, 25);
    return;
  }

  // define diferentes editores
  var TextEdit   = '<textarea ID="_' +nombreObj + '_editor" style="width:' +editor_obj.style.width+ '; height:' +editor_obj.style.height+ '; margin-top: -1px; margin-bottom: -1px;"></textarea>';
  var RichEdit   = '<iframe ID="_' +nombreObj+ '_editor"    style="width:' +editor_obj.style.width+ '; height:' +editor_obj.style.height+ ';"></iframe>';

  if (modo == "textedit" || editor_obj.tagName.toLowerCase() == 'iframe') {
    config.modo = "textedit";
    var editdoc = editor_obj.contentWindow.document;
    var contents = editdoc.body.createTextRange().htmlText;
    editor_obj.outerHTML = TextEdit;
    editor_obj = document.all["_" +nombreObj + "_editor"];
    editor_obj.value = contents;
    editor_evento(nombreObj);

    editor_modBarraH(nombreObj, "disable");  

    editor_obj.onkeydown   = function() { editor_evento(nombreObj); }
    editor_obj.onkeypress  = function() { editor_evento(nombreObj); }
    editor_obj.onkeyup     = function() { editor_evento(nombreObj); }
    editor_obj.onmouseup   = function() { editor_evento(nombreObj); }
    editor_obj.ondrop      = function() { editor_evento(nombreObj, 100); }     
    editor_obj.oncut       = function() { editor_evento(nombreObj, 100); }
    editor_obj.onpaste     = function() { editor_evento(nombreObj, 100); }
    editor_obj.onblur      = function() { editor_evento(nombreObj, -1); }

    editor_modSalida(nombreObj);
    editor_foco(editor_obj);
  }
  else {
    config.modo = "wysiwyg";
    var contents = editor_obj.value;
    if (modo == 'init') { contents = document.all[nombreObj].value; } 

    editor_obj.outerHTML = RichEdit;
    editor_obj = document.all["_" +nombreObj + "_editor"];

    var html = "";
    html += '<html><head>\n';
    if (config.stylesheet) {
      html += '<link href="' +config.stylesheet+ '" rel="stylesheet" type="text/css">\n';
    }
    html += '<style>\n';
    html += 'body {' +config.bodyStyle+ '} \n';
    for (var i in config.fontstyles) {
      var fontstyle = config.fontstyles[i];
      if (fontstyle.classStyle) {
        html += '.' +fontstyle.className+ ' {' +fontstyle.classStyle+ '}\n';
      }
    }
    html += '</style>\n'
      + '</head>\n'
      + '<body contenteditable="true" topmargin=1 leftmargin=1'
      +'>'
      + contents
      + '</body>\n'
      + '</html>\n';

    var editdoc = editor_obj.contentWindow.document;

    editdoc.open();
    editdoc.write(html);
    editdoc.close();

    editor_modBarraH(nombreObj, "enable");  
    editdoc.nombreObj = nombreObj;
	
    editdoc.onkeydown      = function() { editor_evento(nombreObj); }
    editdoc.onkeypress     = function() { editor_evento(nombreObj); }
    editdoc.onkeyup        = function() { editor_evento(nombreObj); }
    editdoc.onmouseup      = function() { editor_evento(nombreObj); }
    editdoc.body.ondrop    = function() { editor_evento(nombreObj, 100); }     
    editdoc.body.oncut     = function() { editor_evento(nombreObj, 100); }
    editdoc.body.onpaste   = function() { editor_evento(nombreObj, 100); }
    editdoc.body.onblur    = function() { editor_evento(nombreObj, -1); }


    if (modo != 'init') {             
      editor_foco(editor_obj);
    }

  }

  if (modo != 'init') {             
    editor_evento(nombreObj);
  }

}

/* ---------------------------------------------------------------------- *\
  Function    : editor_foco
  Description : trae el foco al editor
  Usage       : editor_foco(editor_obj);
  Arguments   : editor_obj - objeto del editor
\* ---------------------------------------------------------------------- */

function editor_foco(editor_obj) {

  if (editor_obj.tagName.toLowerCase() == 'textarea') {         
    var myfunc = function() { editor_obj.focus(); };
    setTimeout(myfunc,100);                                     
  }

  else {                                                        
    var editdoc = editor_obj.contentWindow.document;            
    var editorRange = editdoc.body.createTextRange();           
    var curRange    = editdoc.selection.createRange();          

    if (curRange.length == null &&                              
        !editorRange.inRange(curRange)) {                       
      editorRange.collapse();                                   
      editorRange.select();                                     
      curRange = editorRange;
    }
  }

}

/* ---------------------------------------------------------------------- *\
  Function    : editor_about
  Description : display "about this editor" popup
\* ---------------------------------------------------------------------- */

function editor_about(nombreObj) {
  showModalDialog(_editor_url + "about.html", window, "resizable: yes; help: no; status: no; scroll: no; ");
}

/* ---------------------------------------------------------------------- *\
  Funcion     : color
  Descripcion : convierte el valor del color de decimal a hexadecimal
  Usage       : var hex = color('65535');   // retorna FFFF00
  Arguments   : valor   - valor dec
\* ---------------------------------------------------------------------- */

function color(value) {
  var hex_string = "";
  for (var hexpair = 0; hexpair < 3; hexpair++) {
    var myByte = value & 0xFF;            
    value >>= 8;                        
    var nybble2 = myByte & 0x0F;          
    var nybble1 = (myByte >> 4) & 0x0F;   
    hex_string += nybble1.toString(16); 
    hex_string += nybble2.toString(16); 
  }
  return hex_string.toUpperCase();
}

/* ---------------------------------------------------------------------- *\
  Funcion     : editor_insertaHTML
  Descripcion : inserta cadena. 
  Uso         : editor_insertaHTML(nombreObj, str1, [str2], reqSelection)
  Argumentos  : nombreObj - ID del textarea
                str1 - HTML o texto a insertar
                str2 - HTML o texto a insertar (argumento opcional)
                reqSelection - (1 o 0) 
\* ---------------------------------------------------------------------- */

function editor_insertaHTML(nombreObj, str1,str2, reqSel) {
  var config     = document.all[nombreObj].config;
  var editor_obj = document.all["_" +nombreObj + "_editor"];   
  if (str1 == null) { str1 = ''; }
  if (str2 == null) { str2 = ''; }

  if (document.all[nombreObj] && editor_obj == null) {
    document.all[nombreObj].focus();
    document.all[nombreObj].value = document.all[nombreObj].value + str1 + str2;
    return;
  }

  if (editor_obj == null) { return alert("Unable to insert HTML.  Invalid object name '" +nombreObj+ "'."); }

  editor_foco(editor_obj);

  var tagname = editor_obj.tagName.toLowerCase();
  var sRange;

  if (tagname == 'iframe') {
    var editdoc = editor_obj.contentWindow.document;
    sRange  = editdoc.selection.createRange();
    var sHtml   = sRange.htmlText;

    if (sRange.length) { return alert("Unable to insert HTML.  Try highlighting content instead of selecting it."); }

    var oldHandler = window.onerror;
    window.onerror = function() { alert("Unable to insert HTML for current selection."); return true; } // partial table selections cause errors
    if (sHtml.length) {                                 
      if (str2) { sRange.pasteHTML(str1 +sHtml+ str2) } 
      else      { sRange.pasteHTML(str1); }             
    } else {                                            
      if (reqSel) { return alert("Unable to insert HTML.  You must select something first."); }
      sRange.pasteHTML(str1 + str2);                   
    }
    window.onerror = oldHandler;
  }
  
  else if (tagname == 'textarea') {
    editor_obj.focus();
    sRange  = document.selection.createRange();
    var sText   = sRange.text;
   
    if (sText.length) {                                 
      if (str2) { sRange.text = str1 +sText+ str2; }  
      else      { sRange.text = str1; }               
    } else {                                           
      if (reqSel) { return alert("Unable to insert HTML.  You must select something first."); }
      sRange.text = str1 + str2;                        
    }
  }
  else { alert("Unable to insert HTML.  Unknown object tag type '" +tagname+ "'."); }

 
  sRange.collapse(false); 
  sRange.select();        

}

/* ---------------------------------------------------------------------- *\
  Function    : editor_consigueHTML
  Description : retorna el contedio HTML de editor 
  Usage       : var myHTML = editor_consigueHTML('nombreObj');
\* ---------------------------------------------------------------------- */

function editor_consigueHTML(nombreObj) {
  var editor_obj = document.all["_" +nombreObj + "_editor"];
  var isTextarea = (editor_obj.tagName.toLowerCase() == 'textarea');

  if (isTextarea) { return editor_obj.value; }
  else            { return editor_obj.contentWindow.document.body.innerHTML; }
}

/* ---------------------------------------------------------------------- *\
  Function    : editor_colocaHTML
  Description : coloca el contenido HTML del editor 
  Usage       : editor_colocaHTML('nombreObj',"<b>html</b> <u>aki</u>");
\* ---------------------------------------------------------------------- */

function editor_colocaHTML(nombreObj, html) {
  var editor_obj = document.all["_" +nombreObj + "_editor"];
  var isTextarea = (editor_obj.tagName.toLowerCase() == 'textarea');

  if (isTextarea) { editor_obj.value = html; }
  else            { editor_obj.contentWindow.document.body.innerHTML = html; }
}

/* ---------------------------------------------------------------------- *\
  Function    : editor_aniadeHTML
  Description : añade contenido HTML del editor
  Usage       : editor_aniadeHTML('nombreObj',"<b>html</b> <u>aki</u>");
\* ---------------------------------------------------------------------- */

function editor_aniadeHTML(nombreObj, html) {
  var editor_obj = document.all["_" +nombreObj + "_editor"];
  var isTextarea = (editor_obj.tagName.toLowerCase() == 'textarea');

  if (isTextarea) { editor_obj.value += html; }
  else            { editor_obj.contentWindow.document.body.innerHTML += html; }
}

/* ---------------------------------------------------------------- */

function _isMouseOver(obj,event) {       // determina si el raton esta sobre el objeto
  var mouseX    = event.clientX;
  var mouseY    = event.clientY;

  var objTop    = obj.offsetTop;
  var objBottom = obj.offsetTop + obj.offsetHeight;
  var objLeft   = obj.offsetLeft;
  var objRight  = obj.offsetLeft + obj.offsetWidth;

  if (mouseX >= objLeft && mouseX <= objRight &&
      mouseY >= objTop  && mouseY <= objBottom) { return true; }

  return false;
}

/* ---------------------------------------------------------------- */

function editor_cMenu_generar(editorWin,nombreObj) {
  var parentWin = window;
  editorWin.event.returnValue = false;  
  
  var cMenuOptions = [ 
    ['Cut', 'Ctrl-X', function() {}],
    ['Copy', 'Ctrl-C', function() {}],
    ['Paste', 'Ctrl-C', function() {}],
    ['Delete', 'DEL', function() {}],
    ['---', null, null],
    ['Select All', 'Ctrl-A', function() {}],
    ['Clear All', '', function() {}],
    ['---', null, null],
    ['About this editor...', '', function() {
      alert("about this editor");
    }]];
    editor_cMenu.options = cMenuOptions; 

  var cMenuHeader = ''
    + '<div id="_'+nombreObj+'_cMenu" onblur="editor_cMenu(this);" oncontextmenu="return false;" onselectstart="return false"'
    + '  style="position: absolute; visibility: hidden; cursor: default; width: 167px; background-color: threedface;'
    + '         border: solid 1px; border-color: threedlightshadow threeddarkshadow threeddarkshadow threedlightshadow;">'
    + '<table border=0 cellspacing=0 cellpadding=0 width="100%" style="width: 167px; background-color: threedface; border: solid 1px; border-color: threedhighlight threedshadow threedshadow threedhighlight;">'
    + ' <tr><td colspan=2 height=1></td></tr>';

  var cMenuList = '';

  var cMenuFooter = ''
    + ' <tr><td colspan=2 height=1></td></tr>'
    + '</table></div>';

  for (var menuIdx in editor_cMenu.options) {
    var nombreMenu = editor_cMenu.options[menuIdx][0];
    var menuKey  = editor_cMenu.options[menuIdx][1];
    var menuCode = editor_cMenu.options[menuIdx][2];

    // separator
    if (nombreMenu == "---" || nombreMenu == "separator") {
      cMenuList += ' <tr><td colspan=2 class="cMenuDivOuter"><div class="cMenuDivInner"></div></td></tr>';
    }

    // menu option
    else {
      cMenuList += '<tr class="cMenu" onMouseOver="editor_cMenu(this)" onMouseOut="editor_cMenu(this)" onClick="editor_cMenu(this, \'' +menuIdx+ '\',\'' +nombreObj+ '\')">';
      if (menuKey) { cMenuList += ' <td align=left class="cMenu">' +nombreMenu+ '</td><td align=right class="cMenu">' +menuKey+ '</td>'; }
      else         { cMenuList += ' <td colspan=2 class="cMenu">' +nombreMenu+ '</td>'; }
      cMenuList += '</tr>';
    }
  }

  var cMenuHTML = cMenuHeader + cMenuList + cMenuFooter;


  document.all['_'+nombreObj+'_cMenu'].outerHTML = cMenuHTML;

  editor_cMenu_colocarPosicion(parentWin, editorWin, nombreObj);

  parentWin['_'+nombreObj+'_cMenu'].style.visibility = 'visible';
  parentWin['_'+nombreObj+'_cMenu'].focus();

}

/* ---------------------------------------------------------------- */

function editor_cMenu_colocarPosicion(parentWin, editorWin, nombreObj) {      // set object position that won't overlap window edge
  var event    = editorWin.event;
  var cMenuObj = parentWin['_'+nombreObj+'_cMenu'];
  var mouseX   = event.clientX + parentWin.document.all['_'+nombreObj+'_editor'].offsetLeft;
  var mouseY   = event.clientY + parentWin.document.all['_'+nombreObj+'_editor'].offsetTop;
  var cMenuH   = cMenuObj.offsetHeight;
  var cMenuW   = cMenuObj.offsetWidth;
  var pageH    = document.body.clientHeight + document.body.scrollTop;
  var pageW    = document.body.clientWidth + document.body.scrollLeft;

  // set horzontal position
  if (mouseX + 5 + cMenuW > pageW) { var left = mouseX - cMenuW - 5; } 
  else                            { var left = mouseX + 5; }

  // set vertical position
  if (mouseY + 5 + cMenuH > pageH) { var top = mouseY - cMenuH + 5; } 
  else                            { var top = mouseY + 5; }

  cMenuObj.style.top = top;
  cMenuObj.style.left = left;

}

/* ---------------------------------------------------------------- */

function editor_cMenu(obj,menuIdx,nombreObj) {
  var action = event.type;
  if      (action == "mouseover" && !obj.disabled && obj.tagName.toLowerCase() == 'tr') {
    obj.className = 'cMenuOver';
    for (var i=0; i < obj.cells.length; i++) { obj.cells[i].className = 'cMenuOver'; }
  }
  else if (action == "mouseout" && !obj.disabled && obj.tagName.toLowerCase() == 'tr')  {
    obj.className = 'cMenu';
    for (var i=0; i < obj.cells.length; i++) { obj.cells[i].className = 'cMenu'; }
  }
  else if (action == "click" && !obj.disabled) {
    document.all['_'+nombreObj+'_cMenu'].style.visibility = "hidden";
    var menucode = editor_cMenu.options[menuIdx][2];
    menucode();
  }
  else if (action == "blur") {
    if (!_isMouseOver(obj,event)) { obj.style.visibility = 'hidden'; }
    else {
      if (obj.style.visibility != "hidden") { obj.focus(); }
    }
  }
  else { alert("editor_cMenu, unknown action: " + action); }
}

/* ---------------------------------------------------------------------- */
