var HTRTE = Class.create({
   initialize: function(ID,mode,Width,Height) {
      this.isIE=(navigator.appName.indexOf('Microsoft')>=0)?true:false;
      this.isMz=(navigator.appName=='Netscape')?true:false;
      this.isOp=(navigator.appName=='Opera')?true:false;
      this.mode = mode;
      this.content = $(ID).innerHTML;
      this.ID = 'htrte_' + ID;
      this.height = Height;
      if(Width != ''){
         this.width = 'width="' +(Width + 6) +'"';
      }
      else{
         this.width = '100%';
      }


      this.imagePath = 'HTRTE/icon/'; 
      this.Acommand = new $A([[ 'bold', 'italic', 'underline', 'smiley', 'forecolor', 'fontname', 'fontsize' ]]);       
      this.Afontsize = new $A([8,10,12,14,18,24,36]);
      this.Afontname = new $A([['Arial','arial'],['Arial Black','arial-black'],['Arial Narrow','arial-narrow'],['Courier','courier'],['Courier New','courier-new'],['System','system'],['Tahoma','tahoma'],['Times New Roman','times-new-roman'],['Trebuchet MS','trebuchet-ms'],['Verdana','verdana']]);
      this.Aforecolor = new $A([ ['#000000','Black'], ['#a0522d','Sienna'], ['#556b2f','DarkOliveGreen'], ['#006400','DarkGreen'], ['#483d8b','DarkSlateBlue'], ['#000080','Navy'], ['#4b0082','Indigo'], ['#2f4f4f','DarkSlateGray'], ['#8b0000','DarkRed'], ['#ff8c00','DarkOrange'], ['#808000','Olive'], ['#008000','Green'], ['#008080','Teal'], ['#0000ff','Blue'], ['#708090','SlateGray'], ['#696969','DimGray'], ['#ff0000','Red'], ['#f4a460','SandyBrown'], ['#9acd32','YellowGreen'], ['#2e8b57','SeaGreen'], ['#48d1cc','MediumTurquoise'], ['#4169e1','RoyalBlue'], ['#800080','Purple'], ['#808080','Gray'], ['#ff00ff','Magenta'], ['#ffa500','Orange'], ['#ffff00','Yellow'], ['#00ff00','Lime'], ['#00ffff','Cyan'], ['#00bfff','DeepSkyBlue'], ['#9932cc','DarkOrchid'], ['#c0c0c0','Silver'], ['#ffc0cb','Pink'], ['#f5deb3','Wheat'], ['#fffacd','LemonChiffon'], ['#98fb98','PaleGreen'], ['#afeeee','PaleTurquoise'], ['#add8e6','LightBlue'], ['#dda0dd','Plum'], ['#ffffff','White'] ]);
      this.Asmileys = new $A([[1,':)','Sonrisa'], [2,':(','Triste'], [3,';)','Guiño'], [4,':D','Big grin'], [5,';;)','Batting eyelashes'], [6,'&gt;:D&lt;','Abrazo'], [7,':-/','Confundido'],[8,':x','Love struck'], [9,':"&gt;','Que verguensa'], [10,':-P','Burla'], [11,':-*','Besito'], [12,'=((','Corazon roto'], [13,':-O','Sorprendido'], [14,'X-(','Enfadado'], [15,':-&gt;','Smug'], [16,'B-)','Cool'], [17,':-S','Preocupado'], [18,'#:-S','Uf Casiii'], [19,'&gt;:)','Demonio'], [20,':((','Buaaahh'], [21,':))','Quememeo'], [22,':|','Straight face'], [23,'/:)','Raised eyebrow'], [24,'=))','Que me parto'], [25,'O:-)','Angelito'], [26,':-B','Nerd'], [27,'=;','Talk to the hand'], [28,'I-)','Tenosueño'], [29,'8-|','Rolling eyes'], [30,'L-)','Perdedor'], [31,':-&amp;','toymalito'], [32,':-$','shh no se lo cuentes a nadie'], [33,'[-(','Not talking'], [34,':o)','Payaso'], [35,'8-}','Toto'], [36,'&lt;:-P','Fiesta'], [37,'(:|','Auauahhh'], [38,'=P~','Drooling'], [39,':-?','Pensando'], [40,'#-o','D\'oh'], [41,'=D&gt;','Aplausos'], [42,':-SS','Naibiting'], [43,'@-)','Hipnotizado'], [44,':^O','Mentira'], [45,':-w','Esperando...'], [46,':-&lt;','Sigh'], [47,'&gt;:P','Phbbbt'], [48,'&lt;):)','Vaquero'], [49,':)]','Toy al Teléfono'], [50,':-c','Llamame tu'], [51,'~x(','At wits end'], [52,':-h','Waving'], [53,':-t','Tiempooo!!'], [54,'8-&gt;','Day dreaming']]);


      var nEditor =  '<table cellpadding="3" cellspacing="1" border="0" class="HTRTE" '+(this.width)+'><tr>';

          nEditor += '<td>';
          with(this){
                Acommand.each(function(Tool) {
                nEditor += toolbar(Tool);
                nEditor += menu(Tool);          
             });
          }
          nEditor += '   <table border="0" cellpadding="0" cellspacing="0" style="margin: 2px;" width="100%"> ';
          nEditor += '      <tr>';
          nEditor += '          <td align="right">';
          nEditor += '              <div style="border: #CCCCCC solid 1px; padding:3px; text-align: left;background-color: #FFFFFF;">';
          nEditor += '                 <iframe id="' + this.ID + '"  width="99%" height="'+this.height+'" style="overflow:auto;" frameborder="no"></iframe>';
          nEditor += '              <div>';
          nEditor += '          </td>';
          nEditor += '      </tr>';
          nEditor += '   </table>';
          nEditor += '</td>';
          nEditor += '<td align="left" width="1%" valign="bottom">';
          nEditor += '   <div style="width: 120px; padding: 0px 0px 10px 0px;"><img id="sent" src="HTRTE/icon/Sent.gif" title="Sent" style="cursor: pointer;"/></div>';
          nEditor += '</td>';
          nEditor += '</tr></table>'; 


      $(ID).innerHTML = nEditor;
      this.addEvent();      
      this.UI = $(this.ID).contentWindow;
      this.editor = this.UI.document;
      with(this){
         if(isIE){
            setTimeout(function(){editor.body.contentEditable = true;}, 300);
         }
         else{            
            setTimeout(function(){editor.designMode = 'on';}, 300);
         }
         
         editor.open();
         editor.write('<html><head></head><body marginwidth="1" marginheight="1" topmargin="1" leftmargin="1" style="border:0px;background-color:#ffffff;font-family:arial;font-size:12px;">' + content + '</body></html>');
         editor.close(); 
         
         Event.observe(editor, 'click',  function() {setIcon();}); 
         Event.observe(editor, 'keyup',  function(event) {if(event.keyCode != 13){setIcon();}});
         
     // Shoutbox add 
      
         Event.observe($('sent'), 'click',  function() {
            sAdd();
            OnFocus();   
         }); 
         Event.observe(editor, 'keydown', function(event) {
            if(event.keyCode == 13 && !event.shiftKey) {
                  sAdd();
                  //OnFocus();
                  try{
                     event.preventDefault();
			         event.stopPropagation();
                  }
                  catch(e){
                     event.returnValue = false; // IE
                  }
              return false;
            }
            return true;	
         });
         
      }
   this.EBold = false;
   this.EItalic = false;
   this.EUnderline = false;
   this.EForecolor = '#000000';
   this.EFontname = 'Arial';
   this.EFontsize = 2;
   sOnload();
   },
   
   toolbar: function(array){
       with(this){
       var ntoolbar = '';
          ntoolbar += '   <table id="toolBar" class="htrte_toolbar" cellspacing="0" cellpadding="0" border="0">';
          ntoolbar += '      <tr>';
          ntoolbar += '   	  <td align="center">';
          ntoolbar += '   	     <img width="6" alt="" src="' + imagePath + 'open.gif"/>';
          ntoolbar += '   	  </td>';          
          
       
          array.each(function(com) {
          var command = ID + com;
             if(com == "|"){
             
          ntoolbar += '   	  <td width="8" align="center">';
          ntoolbar += '   	     <img alt="" src="' + imagePath + 'Separator.gif"/>';
          ntoolbar += '   	  </td>';
          
             }
             else if(com == "fontsize" || com == "fontname"){

                ntoolbar += '   	  <td align="center">';
                ntoolbar += '   	     <img width="3" alt="" src="' + imagePath + 'null.gif"/>';
                ntoolbar += '   	  </td>';
                ntoolbar += '   	  <td>';
                ntoolbar += '   	     <div class="htrte_select_all" id="' + command + '">';
                ntoolbar += '   		    <table cellspacing="0" cellpadding="0" border="0">';
                ntoolbar += '   			   <tr>';
                ntoolbar += '   				  <td><button id="set_' + com + '" style="width: ' + ((com == "fontsize")?'30':'100') + 'px;" class="tbutton">' + ((com == "fontsize")?'Size':'Arial') + '</button></td>';
                ntoolbar += '   				  <td align="center" class="htrte_select" width="14" id="i' + command + '"><img src="' + imagePath + 'Sel.gif"/></td>';
                ntoolbar += '   			   </tr>';
                ntoolbar += '   			</table>';			
                ntoolbar += '   		 </div>';
                ntoolbar += '         </td>';
                ntoolbar += '   	  <td align="center">';
                ntoolbar += '   	     <img width="3" alt="" src="' + imagePath + 'null.gif"/>';
                ntoolbar += '   	  </td>';


             }
             else if(com == "forecolor"){
             
                ntoolbar += '   	  <td align="center">';
                ntoolbar += '   	     <img width="3" alt="" src="' + imagePath + 'null.gif"/>';
                ntoolbar += '   	  </td>';
                ntoolbar += '   	  <td>';
                ntoolbar += '   	     <div class="htrte_select_all" id="' + command + '">';
                ntoolbar += '   	        <table cellspacing="0" cellpadding="0" border="0">';
                ntoolbar += '   	           <tr>';
                ntoolbar += '   	              <td align="center"><img width="21" height="14" alt="" src="' + imagePath + com + '.gif"/><br><img id="changecolor' + command + '" style="background-color: #000000;" width="21" height="4" src="' + imagePath + 'null.gif"/></td>';
                ntoolbar += '   	              <td align="center" class="htrte_select" width="10" id="i' + command + '"><img src="' + imagePath + 'Sel.gif"/></td>';
                ntoolbar += '   	           </tr>';
                ntoolbar += '   	        </table>';
                ntoolbar += '   	     </div>';
                ntoolbar += '   	  </td>';
                ntoolbar += '   	  <td align="center">';
                ntoolbar += '   	     <img width="3" alt="" src="' + imagePath + 'null.gif"/>';
                ntoolbar += '   	  </td>';
             
             }
             else if(com == "smiley"){
             
                ntoolbar += '   	  <td align="center">';
                ntoolbar += '   	     <img width="3" alt="" src="' + imagePath + 'null.gif"/>';
                ntoolbar += '   	  </td>';
                ntoolbar += '   	  <td>';
                ntoolbar += '   	     <div class="htrte_select_all" id="' + command + '">';
                ntoolbar += '   	        <table cellspacing="0" cellpadding="0" border="0">';
                ntoolbar += '   	           <tr>';
                ntoolbar += '   	              <td align="center"><img height="18" alt="" src="' + imagePath + com + '.gif"/></td>';
                ntoolbar += '   	              <td align="center" class="htrte_select" width="10" id="i' + command + '"><img src="' + imagePath + 'Sel.gif"/></td>';
                ntoolbar += '   	           </tr>';
                ntoolbar += '   	        </table>';
                ntoolbar += '   	     </div>';
                ntoolbar += '   	  </td>';
                ntoolbar += '   	  <td align="center">';
                ntoolbar += '   	     <img width="3" alt="" src="' + imagePath + 'null.gif"/>';
                ntoolbar += '   	  </td>';
             
             }
             else{
                ntoolbar += '         <td class="htrte_outIcon" id="' + command + '" >';
                ntoolbar += '               <img src="' + imagePath + com + '.gif">'; 
                ntoolbar += '         </td>';
             }
          });
          
          
          ntoolbar += '   	  <td align="center">';
          ntoolbar += '   	     <img width="6" alt="" src="' + imagePath + 'close.gif"/>';
          ntoolbar += '   	  </td>';          
          ntoolbar += '      </tr>';
          ntoolbar += '   </table>';
          ntoolbar += '   ';
       return ntoolbar;
       }
   },
   
   setIcon: function(){
      this.AIcon = new $A([ 
            ['bold',false],
            ['italic',false],
            ['underline',false]
      ]); 
      with(this){
         if (window.getSelection){ 
            var selected_obj = UI.window.getSelection().focusNode;
         }
         else if (document.getSelection){ 
            var selected_obj = UI.document.getSelection().focusNode;
         }
         else if (document.selection){ 
            var selected_obj = UI.document.selection.createRange().parentElement();
         }
         var current_tag = selected_obj; 
         if (current_tag != null){
            var previous_tagName = selected_obj.tagName;        
         } 
         else{
            var previous_tagName = "HTML";
         }
            var setfontname = false;
            var setfontsize = false;
            var setforecolor = false;
            while(previous_tagName != "HTML"){ 
            
               if(previous_tagName == 'B' || previous_tagName == 'STRONG'){AIcon[0][1] = true;}  
               if(previous_tagName == 'I' || previous_tagName == 'EM'){AIcon[1][1] = true;} 
               if(previous_tagName == 'U'){AIcon[2][1] = true;} 
               
                  Afontname.each(function(fontname) {
                     if(current_tag.face == fontname[0] && setfontname == false){$('set_fontname').innerHTML = fontname[0];EFontname=fontname[0];setfontname = true;};
                  });
                  var loop = 0;
                  Afontsize.each(function(fontsize) {
                     loop++;
                     if(current_tag.size == loop && setfontsize == false){$('set_fontsize').innerHTML = loop;EFontsize=loop;setfontsize = true;};
                  });
                  Aforecolor.each(function(forecolor) {
                     if(current_tag.color == forecolor[0] && setforecolor == false){EForecolor = forecolor[0]; setforecolor = true;};
                  });

               current_tag = current_tag.parentNode; 
               previous_tagName = current_tag.tagName;
            }  
            
            if(AIcon[0][1] == true){$(ID + AIcon[0][0]).className = 'htrte_clickIcon';EBold = true;}else{$(ID + AIcon[0][0]).className = 'htrte_outIcon';EBold = false;}
            if(AIcon[1][1] == true){$(ID + AIcon[1][0]).className = 'htrte_clickIcon';EItalic = true;}else{$(ID + AIcon[1][0]).className = 'htrte_outIcon';EItalic = false;}
            if(AIcon[2][1] == true){$(ID + AIcon[2][0]).className = 'htrte_clickIcon';EUnderline = true;}else{$(ID + AIcon[2][0]).className = 'htrte_outIcon';EUnderline = false;}
          
            
      }
   },
   
   addEvent: function(){
      with(this){
         Acommand.each(function(Tool) {
            Tool.each(function(com) {
               if(com != '|'){
                  if(com == "fontsize" || com == "fontname" || com == "forecolor" || com == "smiley"){
                     var command = ID + com;
                     if(com == "forecolor"){
                        Event.observe($('i' + command), 'click',  function() {openMenu(com,150);});
                        Event.observe($(command), 'click',  function() {addCommand(com,$('changecolor' + command).style.backgroundColor);});
                     }
                     else{
                        Event.observe($(command), 'click',  function() {
                           if(com == "fontsize"){openMenu(com,50);}
                           else if(com == "fontname"){openMenu(com,140);}
                           else if(com == "smiley"){openMenu(com,350);}
                        });
                     }
                     Event.observe($(command), 'mouseout',  function() {$('i' + command).className = 'htrte_select';$(command).className = 'htrte_select_all';});
                     Event.observe($(command), 'mouseover',  function() {
                           $('i' + command).className = 'htrte_select_over';
                           $(command).className = 'htrte_select_all_over';
                     });                                      
                  }
                  else if(com == "bold" || com == "italic" || com == "underline" || com == "strikethrough" || com == "superscript" || com == "subscript"){
                     var command = ID + com;
                     Event.observe($(command), 'click',  function() {addCommand(com);clickIcon(com);}); 
                     Event.observe($(command), 'mouseout',  function() {
                        if($(command).className != 'htrte_clickIcon'){
                           $(command).className = 'htrte_outIcon';
                        }
                     });
                     Event.observe($(command), 'mouseover',  function() {
                        if($(command).className != 'htrte_clickIcon'){
                           $(command).className = 'htrte_overIcon';
                        }
                     });                 
                  }
                  else if(com == "help"){
                     openMenu(com,200);
                  }
                  else{
                     var command = ID + com;
                     Event.observe($(command), 'click',  function() {addCommand(com);}); 
                     Event.observe($(command), 'mouseout',  function() {$(command).className = 'htrte_outIcon';});
                     Event.observe($(command), 'mouseover',  function() {$(command).className = 'htrte_overIcon';});                 
                  }
               }
            });
         });
      }
   },
      
   clickIcon: function(com){
   with(this){
      var command = ID + com;
      if ($(command).className != 'htrte_clickIcon') {
            $(command).className = 'htrte_clickIcon';        
      }
      else{
         $(command).className = 'htrte_outIcon';
      }
   }
   },
   
   addSmiley: function(url,title){
      if(this.isIE == true){
	     img = this.editor.createElement('img');

	     img.setAttribute('src', url);
	     img.setAttribute('title', title);
	     img.setAttribute('border', '0');

	     try{
		    this.OnFocus(); 
		    this.editor.selection.createRange().pasteHTML(img.outerHTML);
	     }catch(exception){
		    alert('Error inserting object in current location.');
		    this.OnFocus(); 
	     }
	     this.OnFocus();
      }
      else
      {
         this.addCommand('insertimage',url);
      }
   },
   
   addCommand: function(command, svalue){
      with(this){ 
         if(isMz){
            editor.execCommand('useCSS',false,svalue);
         }
         OnFocus();  
	     if(!svalue){svalue=null;}
         editor.execCommand(command,false,svalue);       
      }
   },
   
   OnFocus: function(){ 
      with(this){
         if(isOp){
            $(ID).focus();
         }
         else{
            UI.focus();  
         }
      }
   },
   
   clearContent: function(){
   with(this){
      if(isMz){
         editor.body.innerHTML = '';
         editor.execCommand('delete',false,null);
         if(EBold == true){editor.execCommand('bold',false,null);}
         if(EItalic == true){editor.execCommand('italic',false,null);}
         if(EUnderline == true){editor.execCommand('underline',false,null);}
         editor.execCommand('forecolor',false,EForecolor);
         editor.execCommand('fontname',false,EFontname);
         editor.execCommand('fontsize',false,EFontsize);

         
      }
      else{
         editor.body.innerHTML = '';
         if(EBold == true){editor.execCommand('bold',false,null);}
         if(EItalic == true){editor.execCommand('italic',false,null);}
         if(EUnderline == true){editor.execCommand('underline',false,null);}

         editor.execCommand('forecolor',false,EForecolor);
         editor.execCommand('fontname',false,EFontname);
         editor.execCommand('fontsize',false,EFontsize);
         
      }
   }
   },
   
   getContent: function(){
       return this.editor.body.innerHTML;
   },
   
   openMenu: function(com,swidth){
      with(this){
         var command = ID + com;
         $('Pop_' + command).style.width = swidth + 'px';
         $('Pop_' + command).style.visibility = 'visible';
         $('Pop_' + command).style.left = Position.cumulativeOffset($(command))[0] + 'px';
         $('Pop_' + command).style.top = (Position.cumulativeOffset($(command))[1] + $(command).offsetHeight)+'px';         

         var nMenuIcon = new $A($('Pop_' + command).getElementsByClassName('htrte_menu_outIcon'));

         nMenuIcon.each(function(obj) {
            Event.stopObserving(obj, 'click');
            Event.stopObserving(obj, 'mouseover');
            Event.stopObserving(obj, 'mouseout');
            Event.observe(obj, 'click',  function() {
               eval(obj.id);
               closeMenu(com);
            });
            Event.observe(obj, 'mouseover',  function() {
               $(obj).className = 'htrte_menu_overIcon';
            });
            Event.observe(obj, 'mouseout',  function() {
               $(obj).className = 'htrte_menu_outIcon';
            });
         });
         
         Event.observe(editor, 'click',  function() {
            closeMenu(com);
         });
         Event.observe($(ID), 'keypress',  function() {
            closeMenu(com);
         });

      }
   },
   
   closeMenu: function(com){
      with(this){
         var command = ID + com;
         setTimeout(function(){       
            $('Pop_' + command).style.visibility = 'hidden';
         }, 100);
      }
   },
   
   menu: function(array){
      with(this){
      var nMenu = '';
         array.each(function(com) {
            var command = ID + com;
            var loop = 0;
            if(com == "forecolor"){

          nMenu += '<div id="Pop_' + command + '" class="htrte_menu">'; 
          nMenu += '   <table border="0" cellspacing="1" cellpadding="1" align="center" width="100%">'; 
          nMenu += '      <tr/>';
          Aforecolor.each(function(forecolor) {
             if(loop == 8){nMenu += '      </tr><tr>';loop = 0;}
             nMenu += '         <td >';
             nMenu += '             <button title="' + forecolor[1] + '" class="htrte_menu_outIcon" style="width: 15px;height: 15px; background-color: ' + forecolor[1] + ';" id="addCommand(\'' + com + '\',\'' + forecolor[0] + '\');$(\'changecolor' + command + '\').style.backgroundColor = \'' + forecolor[0] + '\';"></button>';
             nMenu += '         </td>';
             loop++;
          });
          nMenu += '      </tr>';
          nMenu += '   </table>';
          nMenu += '</div>';  

            }
            else if(com == "fontsize"){
            
          nMenu += '<div id="Pop_' + command + '" class="htrte_menu">'; 
          nMenu += '   <table border="0" cellspacing="1" cellpadding="1" align="center" width="100%">'; 
          nMenu += '      <tr/>';
          Afontsize.each(function(fontsize) {
             loop++;
             nMenu += '                <tr>';
             nMenu += '                   <td>';
             nMenu += '                      <button title="' + loop + '" class="htrte_menu_outIcon" style="width: 100%;font-size: '+ fontsize +'px;" id="addCommand(\'fontsize\',\'' + loop + '\');">' + loop + '</button>';
             nMenu += '                   </td>';
             nMenu += '                </tr>'; 
          });
          nMenu += '      </tr>';
          nMenu += '   </table>';
          nMenu += '</div>';  
            
            }
            else if(com == "fontname"){
            
          nMenu += '<div id="Pop_' + command + '" class="htrte_menu">'; 
          nMenu += '   <table border="0" cellspacing="1" cellpadding="1" align="center" width="100%">'; 
          nMenu += '      <tr/>';
          Afontname.each(function(fontname) {
             nMenu += '                <tr>';
             nMenu += '                   <td>';
             nMenu += '                      <button title="' + fontname[0] + '" class="htrte_menu_outIcon" style="width: 100%; font-family: ' + fontname[1] + ';" id="addCommand(\'fontname\',\'' + fontname[0] + '\');$(\'set_fontname\').innerHTML = \'' + fontname[0] + '\';">' + fontname[0] + '</button>';
             nMenu += '                   </td>';
             nMenu += '                </tr>'; 
          });             
          nMenu += '      </tr>';
          nMenu += '   </table>';
          nMenu += '</div>';  

            }
            else if(com == "smiley"){ 

          nMenu += '<div id="Pop_' + command + '" class="htrte_menu">'; 
          nMenu += '   <table border="0" cellspacing="1" cellpadding="1" align="center">';  
          loop = 0; 
          Asmileys.each(function(smiley) {
          if(loop == 9){nMenu += '      </tr><tr>';loop = 0;}
          
          nMenu += '         <td align="center">';
          nMenu += '            <img class="htrte_menu_outIcon" src="HTRTE/Smileys/' + smiley[0] + '.gif" border="0" id="addSmiley(\'HTRTE/Smileys/' + smiley[0] + '.gif\',\'' + smiley[2] + '\');" title="' + smiley[2] + '">';
          nMenu += '         </td>';
          
          loop++;
          });
          nMenu += '   </table>';
          nMenu += '</div>';           
            }

         });return nMenu;
      }
      
   }
           
});
