//First lets initiate some variables

var isEditable= false;
var isIE;
var isGecko;
var isSafari;
var isKonqueror;
var browser = navigator.userAgent.toLowerCase();
function editor(obj)
{
  obj.disabled=true;
  obj.style.display='none';
  initiateEditor();
  createEditorButtons(obj.value,obj.title);
  displayEditor(obj.value,obj.title);
}
function initiateEditor() {
 //check what browser is in use
 isIE = ((browser.indexOf("msie") != -1) && (browser.indexOf("opera") == -1) && (browser.indexOf("webtv") == -1));
 isGecko = (browser.indexOf("gecko") != -1);
 isSafari = (browser.indexOf("safari") != -1);
 isKonqueror = (browser.indexOf("konqueror") != -1);

 //enable designMode if the browser is not safari or konqueror.
 if (document.getElementById && document.designMode && !isSafari && !isKonqueror) {
   isEditable= true;
 }
}
//Javascript function dislpayEditor will create the textarea.
//function displayEditor(editor, html,width,height) {
  function displayEditor(pWhere,editor) {
   if(isEditable){
        var obj_where=document.getElementById(pWhere);
        var obj_textArea=document.getElementById(editor);
        obj_iframe=document.createElement('iframe');
        obj_textArea.parentNode.insertBefore(obj_iframe,obj_textArea);
        //var obj_iframe=CreateAppend_('iframe',obj_where);
        obj_iframe.id=editor+'_iframe';
        obj_iframe.name=editor+'_iframe';
        obj_iframe.width='600px';
        obj_iframe.height='300px';
        designer(editor+'_iframe',reemplazar(obj_textArea.value,'A'));


        obj_textArea.style.display='none';
   }else
   {
     return false;
   }
}

//this is designer function that enables designMode and writes defalut text to the text area
function designer(editor, html) {
     var mainContent=  html ;
//assign the frame(textarea) to the edit variable using that frames id
     var edit = document.getElementById(editor).contentWindow.document;
//write the content to the textarea
      edit.write(mainContent);
      edit.close();
//enable the designMode
      edit.designMode =  "On" ;
     //document.getElementById(content).contentDocument.designMode = "on";

}

function updateEditor(editor) {
	if (!isEditable) return;
//assign the value of the textarea to the hidden field. 
	var hiddenField = document.getElementById('hidden' + editor);
	if (hiddenField.value == null) hiddenField.value = "";
		hiddenField.value = document.getElementById(editor).contentWindow.document.body.innerHTML;
}

function pedirLink()
{

  var StrLink="http://";
  StrLink=prompt("Direccion enlace", "http://")
  return StrLink;
}


function iframe2textArea(pIde)
{
obj=getById_(pIde);
obj_iframe=getById_(pIde+'_iframe');
switch(obj.style.display)
{
  case 'block':

  obj.style.display='none';
  obj_iframe.style.display='block';
  obj_iframe.contentWindow.document.body.innerHTML=reemplazar(obj.value,'A');
  //obj.value=obj_iframe.contentWindow.document.body.innerHTML;
  break;
  case 'none':

  obj.style.display='block';
  obj_iframe.style.display='none';
  obj.value=reemplazar(obj_iframe.contentWindow.document.body.innerHTML,'B');
  break;
  default:

  obj.style.display='none';
  obj_iframe.style.display='block';
  obj_iframe.contentWindow.document.body.innerHTML=reemplazar(obj.value,'A');
  //obj.value=obj_iframe.contentWindow.document.body.innerHTML;
  break;

}

}
function CreateAppend_(tipo,where)
{
  var obj=document.createElement(tipo);
  where.appendChild(obj);
  return obj;
}

function executor(editor, command, option) {
// first we assign the content of the textarea to the variable mainField
    switch(command)
  {
    case 'hilitecolor':
        var command=window.ActiveXObject?'backcolor':'hilitecolor';
    break;
  }

    var mainField = getById_(editor).contentWindow;
 // then we will use execCommand to execute the option on the textarea making sure the textarea stays in focus
   try {
          mainField.focus();
          //********************

          //alert(command);
          switch (command)
          {
          case 'createAnchor':
          //alert(command);
          mainField.document.execCommand('CreateLink',false, option+"_target=blank_");
          //alert(mainField.document.selection);
          var Ranger=mainField.document.selection.createRange();
         // var htmlText=Ranger.htmlText.replace("href=","target=\"_blank\" href=");
         //Ranger.pasteHTML(htmlText);
          break;
          default:
           mainField.document.execCommand(command,false, option);
          break;
          }
          //*******************

          //mainField.document.execCommand(command, false, option);
          mainField.focus();
    } catch (e) { }
}
function executorTrue(editor, command, option) {
  
  switch(command)
  {
    case 'hilitecolor':
        var command=window.ActiveXObject?'backcolor':'hilitecolor';
    break;
  }
// first we assign the content of the textarea to the variable mainField
    var mainField = getById_(editor).contentWindow;
 // then we will use execCommand to execute the option on the textarea making sure the textarea stays in focus
   try {
          mainField.focus();
          mainField.document.execCommand(command, true, option);
          mainField.focus();
    } catch (e) { }
}
function createFunction(pEditor,pCommand,pOption)
{
  if (pOption!=pCommand)
  {
   var fnc= function(){executor(pEditor,pCommand,pedirLink());}
  }
  else
  {
    var fnc= function(){executor(pEditor,pCommand,'');}
  }

  return fnc;
}
function GetSelectedValue(pSelectId)
{
  obj_select=getById_(pSelectId);
  return obj_select.value;
}
function createFunctionIII(pEditor,pCommand)
{

   var fnc= function(){
     executor(pEditor,pCommand,GetSelectedValue(pCommand));
     }
   return fnc;
}
function createEditorSelectOptions(pObjSelect,pArrSelectsIII)
{
  

  var ArrValues =pArrSelectsIII[1].split(" ");
  var ArrTexts  =pArrSelectsIII[2].split(" ");
  var c=0;
   for (c=0;c<ArrValues.length;c++)
  {
    var obj_option=CreateAppend_('option',pObjSelect);
    obj_option.value=ArrValues[c];
    obj_option.text=ArrTexts[c];
    switch(pArrSelectsIII[0])
    {
      case 'forecolor':
      obj_option.style.background=ArrValues[c];
      obj_option.text='color';
      break;
      case'hilitecolor':
      obj_option.style.background=ArrValues[c];
       obj_option.text='fondo';
      break;
      case 'fontsize':
      obj_option.style.fontsize=ArrValues[c]+"pt";
      break;
      default:
      //obj_option.style.fontFamily=ArrValues[c];
      break;

    }
  }
}
function createEditorSelects(pWhereId,pEditor)
{
/*
#ffcc66
#ffcc33
#ff9900
#ffffcc
pequeña
red blue gris
#0000ff #ff0000 #444444 #999999
*/
  var StrSelects="";
  //var StrSelects="fontsize:1 2 3 5:size1 size2 size3 size5\n";
  StrSelects   +="hilitecolor:white #ffcc99 #ff9999 #ff6699 #ff3366 #ff3333 #220000:white #ffcc99 #ff9999 #ff6699 #ff3366 #ff3333 #220000\n";
  StrSelects   +="forecolor:black #ffcc99 #ff9999 #ff6699 #ff3366 #ff3333 #220000:black #ffcc99 #ff9999 #ff6699 #ff3366 #ff3333 #220000";
 // StrSelects   +="hilitecolor:white #ffccff #ff99ff #ff66ff #ff9900:white #ffccff #ff99ff #ff66ff #ff9900\n";
 // StrSelects   +="forecolor:black #0000ff #ff0000 #444444 #999999:black #0000ff #ff0000 #444444 #999999\n";
  //StrSelects   +="fontName:Arial Verdana Courier:Arial Verd Couri";

  var ArrSelects=StrSelects.split("\n");
  var where=getById_(pWhereId);
  var c=0;
   for (c=0;c<ArrSelects.length;c++)
  {
    var ArrSelectsIII=ArrSelects[c].split(":")
    var obj_select=CreateAppend_('select',where);
    obj_select.id=ArrSelectsIII[0];
    createEditorSelectOptions(obj_select,ArrSelectsIII);

   var fnc=createFunctionIII(pEditor+'_iframe',ArrSelectsIII[0]);
    if(obj_select.addEventListener)
    {
      obj_select.addEventListener("change",fnc, false);
    }
    else
    {
      obj_select.attachEvent("onchange",fnc);
    }
  }

}
/*
function createEditorButtosAvanced(pWhereId,pEditor)
{
   var StrButtons="saveas;htmlmode;killword;inserttable;selectall";
   var ArrButtons= StrButtons.split(";");
   var c=0;
   var where=getById_(pWhereId);
  for (c=0;c<ArrButtons.length;c++)
  {
     var obj=CreateAppend_('button',where);

    var img=CreateAppend_('img',obj)
    img.src='.//include//img//control//'+ArrButtons[c]+'.gif';
    img.alt=ArrButtons[c];

    var fnc=createFunction(pEditor+'_iframe',ArrButtons[c],ArrButtons[c]);
    //{executorTrue(pWhereId+'_iframe',ArrButtons[c],false);}

    if(obj.addEventListener)
    {
      obj.addEventListener("click", fnc,false);
    }
    else
    {
      obj.attachEvent("onclick", fnc,false);
    }
  }
}
*/
function createEditorButtons(pWhereId,pEditor)
{
  //execCommand("ForeColor",false,"#FF0033");

  var StrButtons="bold;underline;italic;strikethrough;subscript;superscript;removeformat;inserthorizontalrule;justifyleft;justifycenter;justifyright;justifyfull;indent;outdent";
  StrButtons+=";CreateLink;createAnchor;Unlink;InsertImage;undo;redo;InsertOrderedList;InsertUnorderedList;InsertParagraph";
  var StrButtons2="bold;underline;italic;strikethrough;subscript;superscript;removeformat;inserthorizontalrule;justifyleft;justifycenter;justifyright;justifyfull;indent;outdent";
  StrButtons2+=";*CreateLink;*createAnchor;Unlink;*InsertImage;undo;redo;InsertOrderedList;InsertUnorderedList;InsertParagraph";


  //createEditorButtosAvanced(pWhereId,pEditor);
   createEditorSelects(pWhereId,pEditor);
  var ArrButtons= StrButtons.split(";");
   var ArrButtons2= StrButtons2.split(";");

  var where=getById_(pWhereId);
  var c=0;

  for (c=0;c<ArrButtons.length;c++)
  {
    var obj=CreateAppend_('button',where);
    obj.style.padding='0px';
    var img=CreateAppend_('img',obj)
    img.src='.//include//img//control//'+ArrButtons[c]+'.gif';
    img.alt=ArrButtons[c];
    img.style.padding='0px';
    var fnc=createFunction(pEditor+'_iframe',ArrButtons[c],ArrButtons2[c]);

    if(obj.addEventListener)
    {
      obj.addEventListener("click",fnc, false);
    }
    else
    {
      obj.attachEvent("onclick",fnc);
    }
  }
   var obj=CreateAppend_('button',where);
   obj.id='htm_';
   var img=CreateAppend_('img',obj);
   img.src='.//include//img//control//html.gif';
    obj.style.padding='0px';

   if(obj.addEventListener)
    {
    obj.addEventListener("click",function(){iframe2textArea(pEditor);}, false);

    }
    else
    {
     obj.attachEvent("onclick",function(){iframe2textArea(pEditor);});

    }
}
function reemplazar(HTML,pvar)
{


  var StrThisA =";a;\"";
  var Str4ThisA=";a;'";

  var StrThisB ="\n;strong>";
  var Str4ThisB=" ;b>";
  var StrThis="";
  var Str4This="";

  switch (pvar)
  {
    case 'A':
    StrThis = StrThisA;
    Str4This= Str4ThisA;
    break;
    case 'B':
    StrThis= StrThisB;
    Str4This= Str4ThisB;
    break;
    default:
    alert('default');
     StrThis = StrThisA;
     Str4This= Str4ThisA;
    break;
  }

  var ArrThis =StrThis.split(";");
  var Arr4This=Str4This.split(";");


  var ii=0;
  var i2=1;//ArrThis.lenght;
  var HTML_=HTML;
   do{
     HTML_=HTML;

     for (ii=0;ii<i2;ii++)
     {
       //alert('a'+ii+ArrThis[ii]+' por '+Arr4This[ii]);
       HTML=HTML.replace(ArrThis[ii],Arr4This[ii]);
      // alert('b'+ii);
     }
     //HTML=HTML.replace("\n","<br/>");
     //HTML=HTML.replace("{[","src='");
     //HTML=HTML.replace("]}","'");
     //HTML=HTML.replace("[","<");
     //HTML=HTML.replace("]",">");
     }while(HTML!=HTML_)
   return HTML;
}
function previewer(pIdeSrc,pIdeTarget)
{
 var Src=getById(pIdeSrc);
 var Target=getById(pIdeTarget);
 var HTML=Src.value;
 var HTML_=HTML;
   do{
   HTML_=HTML;
   HTML=HTML.replace("\n\n","</p>");
   HTML=HTML.replace("\n","<br>");
   HTML=HTML.replace("{[","src='");
   HTML=HTML.replace("]}","'");
   HTML=HTML.replace("[","<");
   HTML=HTML.replace("]",">");
   }while(HTML!=HTML_)
  Target.innerHTML="<p>"+HTML+"</p>";
}

