var jsEditor = new Array();

function HTML_Editor(editor_id, initial_text)
{
  this.editorid = editor_id;
  this.initialized = false;
  this.controlbar = fetch_object(this.editorid + '_toolbar');
  this.textobj = fetch_object(this.editorid + '_textarea');
  this.buttons = new Array();

  this.init = function()
  {
    //alert(this.editorid);
    if(this.initialized)
    {
      return;
    }
    this.set_editor_functions();
    this.init_controls();
    this.initialized = true;
  };

  /**
  * Init Editor Functions
  */
  this.set_editor_functions = function()
  {
    this.textobj.onfocus = HTML_Editor_Events.prototype.editwin_onfocus;
    this.textobj.onblur = HTML_Editor_Events.prototype.editwin_onblur;
  };

  /**
  * Set Context
  */
  this.set_context = function()
  {
  };

  /**
  * Get Selected Text
  */
  this.get_selection = function()
  {
    if (typeof(this.textobj.selectionStart) != 'undefined')
    {
      return this.textobj.value.substr(this.textobj.selectionStart, this.textobj.selectionEnd - this.textobj.selectionStart);
    }
    else if (document.selection && document.selection.createRange)
    {
      return document.selection.createRange().text;
    }
    else if (window.getSelection)
    {
      return window.getSelection() + '';
    }
    else
    {
      return false;
    }
  };

  this.verify_prompt = function(str)
  {
    switch(str)
    {
      case 'http://':
      case 'null':
      case 'undefined':
      case 'false':
      case '':
      case null:
      case false:
        return false;

      default:
        return str;
    }
  };

    /**
    * Paste HTML
    */
    this.insert_text = function(text, movestart, moveend)
    {
      this.check_focus();

      if (typeof(this.textobj.selectionStart) != 'undefined')
      {
        var opn = this.textobj.selectionStart + 0;

        this.textobj.value = this.textobj.value.substr(0, this.textobj.selectionStart) + text + this.textobj.value.substr(this.textobj.selectionEnd);

        if (movestart === false)
        {
          // do nothing
        }
        else if (typeof movestart != 'undefined')
        {
          this.textobj.selectionStart = opn + movestart;
          this.textobj.selectionEnd = opn + text.length - moveend;
        }
        else
        {
          this.textobj.selectionStart = opn;
          this.textobj.selectionEnd = opn + text.length;
        }
      }
      else if (document.selection && document.selection.createRange)
      {
        var sel = document.selection.createRange();
        sel.text = text.replace(/\r?\n/g, '\r\n');

        if (movestart === false)
        {
          // do nothing
        }
        else if (typeof movestart != 'undefined')
        {
          sel.moveStart('character', -text.length +movestart);
          sel.moveEnd('character', -moveend);
        }
        else
        {
          sel.moveStart('character', -text.length);
        }
        sel.select();
      }
      else
      {
        // failed - just stuff it at the end of the message
        this.textobj.value += text;
      }
    };

  this.init_controls = function()
  {
    var controls = new Array();

    if (this.controlbar == null)
    {
      return;
    }

    var buttons = fetch_tags(this.controlbar, 'img');
    for (var i = 0; i < buttons.length; i++)
    {
      if (buttons[i].id != 'separator')
      {
        controls[controls.length] = buttons[i].id;
      }
      if (buttons[i].id.indexOf('_unlink')>0 && !is_regexp)
      {
        buttons[i].style.display = 'none';
      }
    }
    for (var i = 0; i < controls.length; i++)
    {
      var control = fetch_object(controls[i]);
      this.init_command_button(control);
    }
    //set_unselectable(this.controlbar);
  };

  this.init_command_button = function(obj)
  {
    obj.cmd = obj.id.substr(obj.id.indexOf('_cmd_') + 5);
    obj.editorid = this.editorid;
    obj.state = false;
    obj.mode = 'normal';
    istyle = 'pi_button_' + obj.mode;
    obj.className = istyle;
    obj.onclick = obj.onmousedown = obj.onmouseover = obj.onmouseout = HTML_Editor_Events.prototype.command_button_onmouseevent;
  };

  this.button_context = function(obj, state, controltype)
  {
    if (typeof controltype == 'undefined')
    {
      controltype = 'button';
    }
    switch (obj.state)
    {
      case true: // selected button
      {
        switch (state)
        {
          case 'mouseover':
          case 'mousedown':
          case 'mouseup':
          {
            this.set_control_style(obj, controltype, 'down');
            break;
          }
          case 'mouseout':
          {
            this.set_control_style(obj, 'button', 'selected');
            break;
          }
        }
        break;
      }
      default: // not selected
      {
        switch (state)
        {
          case 'mouseover':
          case 'mouseup':
          {
            this.set_control_style(obj, controltype, 'hover');
            break;
          }
          case 'mousedown':
          {
            this.set_control_style(obj, controltype, 'down');
            break;
          }
          case 'mouseout':
          {
            this.set_control_style(obj, controltype, 'normal');
            break;
          }
        }
        break;
      }
    }
  };

  this.set_control_style = function(obj, controltype, mode)
  {
    if (obj.mode != mode)
    {
      obj.mode = mode;
      // construct the name of the appropriate array key from the istyles array
      istyle = 'pi_' + controltype + '_' + obj.mode;
      obj.className = istyle;
      obj.style.cursor = pointer_cursor;
    }
  };

  this.apply_format = function(cmd)
	{
		var cmd_upper = cmd.toUpperCase();
    selection = this.get_selection();
    if(selection === false)
      {
        selection = '';
      }
      else
      {
        selection = new String(selection);
      }

		switch(cmd)
		{
			case 'bold':
			case 'italic':
			case 'underline':
			case 'strikeout':
			  var opentag = cmd_upper.substr(0, 1);
			  break;
			case 'createlink':
			  var url = prompt('Bitte gib die URL ein.', 'http://');
				if(this.verify_prompt(url))
				  {
						var selection = prompt('Bitte gib den dazugehörigen Linktext ein.', selection);
						if(this.verify_prompt(selection))
							{
								var opentag = 'URL';
								var endtag = 'URL';
								if(selection==url)
								  {
										selection = url;
									}
									else
									{
								    opentag += '=' + url;
									}
							}
					}
			  break;
			case 'email':
			  var mail = prompt('Bitte gib die E-Mail-Adresse ein.', selection);
				if(this.verify_prompt(mail))
				  {
						var selection = prompt('Bitte gib den dazugehörigen Linktext ein.', selection);
						if(this.verify_prompt(selection))
							{
								var opentag = 'MAIL';
								var endtag = 'MAIL';
								if(selection==mail)
								  {
										selection = mail;
									}
									else
									{
								    opentag += '=' + mail;
									}
							}
					}
			  break;
			case 'unlink':
			  var removeable_tags = new Array('url','mail');
				for (var i = 0; i < removeable_tags.length; i++)
				{
					var regex1 = new RegExp('^\\[' + removeable_tags[i] + '\\](.+)\\[\\/' + removeable_tags[i] + '\\]$', 'gi');
					var regex2 = new RegExp('^\\[' + removeable_tags[i] + '=(.+)\\](.+)\\[\\/' + removeable_tags[i] + '\\]$', 'gi');
					if(regex1.test(selection))
					  {
					    var unlinked = selection.replace(regex1, '$1');
							break;
						}
						else if(regex2.test(selection))
					  {
					    var unlinked = selection.replace(regex2, '$2 ($1)');
							break;
						}
				}
			  break;
			case 'insertimage':
			  var img = prompt('Bitte gib die URL des Bildes ein.', 'http://');
				if(this.verify_prompt(img))
				  {
						var selection = prompt('Bitte gib den dazugehörigen Bildtitel ein.', selection);
						if(this.verify_prompt(selection))
							{
								var opentag = 'IMG';
								var endtag = 'IMG';
								if(selection==img)
								  {
										selection = img;
									}
									else
									{
								    opentag += '=' + img;
									}
							}
					}
			  break;
		}
		if(!endtag || endtag=='undefined')
		  {
		    var endtag = opentag;
			}
		if(opentag && opentag!='undefined')
		  {
		    this.insert_text('[' + opentag + ']' + selection + '[/' + endtag + ']', opentag.length + 2, endtag.length + 3);
				return true;
			}
			else if(unlinked.length>0)
		  {
		    this.insert_text(unlinked);
				return true;
			}
			else
			{
				return false;
			}
	}

  this.format = function(e, cmd)
  {
    e = do_an_e(e);
    this.check_focus();
    if (this[cmd])
    {
      var ret = this[cmd](e);
    }
    else
    {
      try
      {
				var ret = this.apply_format(cmd);
      }
      catch(e)
      {
        this.handle_error(cmd, e);
        var ret = false;
      }
    }
    this.check_focus();
    return ret;
  };

  this.check_focus = function()
  {
    if (!this.textobj.hasfocus)
    {
      this.textobj.focus();
      if (is_opera)
      {
        // see http://www.vbulletin.com/forum/bugs35.php?do=view&bugid=687
        this.textobj.focus();
      }
    }
  };

  this.handle_error = function(cmd, e)
  {
  };

  //initialisieren
  this.init();
}

// =============================================================================
// Editor event handler functions

/**
* Class containing editor event handlers
*/
function HTML_Editor_Events()
{
}

/**
* Handles a mouse event on a command button
*/
HTML_Editor_Events.prototype.command_button_onmouseevent = function(e)
{
  e = do_an_e(e);
  if (e.type == 'click')
  {
    jsEditor[this.editorid].format(e, this.cmd);
  }
  jsEditor[this.editorid].button_context(this, e.type);
};

/**
* Sets editwin.hasfocus = true on focus
*/
HTML_Editor_Events.prototype.editwin_onfocus = function(e)
{
  this.hasfocus = true;
};

/**
* Sets editwin.hasfocus = false on blur
*/
HTML_Editor_Events.prototype.editwin_onblur = function(e)
{
  this.hasfocus = false;
};

/*var txtfeld;
function storeCaret(textEl)
{
  txtfeld = textEl;
  if(txtfeld.createTextRange)
      txtfeld.caretPos = document.selection.createRange().duplicate();
}
function setHTML(text)
{
  if(txtfeld)
    {
      if(txtfeld.createTextRange && txtfeld.caretPos)
        {
          var caretPos = txtfeld.caretPos;
          caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
          txtfeld.focus();
        }
        else
        {
          txtfeld.value  += text;
          txtfeld.focus();
        }
    }
    else var aw = alert('Bitte wählen Sie erst ein Eingabefeld aus!');
}
function setURL()
{
  var url = prompt('Bitte geben Sie den Link ein!');
  if(url)
    {
      var linktext = prompt('Bitte geben Sie den Linktext ein!\nSoll der Link gleichzeitig der Linktext sein, ignorieren Sie die Eingabe und klicken "OK".');
      if(linktext)
          setHTML('[url=' + url + ']' + linktext + '[/url]');
        else
          setHTML('[url]' + url + '[/url]');
    }
}
function setMail()
{
  var url = prompt('Bitte geben Sie die eMailadresse ein!');
  if(url)
    {
      var linktext = prompt('Bitte geben Sie den Linktext ein!\nSoll die eMailadresse gleichzeitig der Linktext sein, ignorieren Sie die Eingabe und klicken "OK".');
      if(linktext)
          setHTML('[mail=' + url + ']' + linktext + '[/mail]');
        else
          setHTML('[mail]' + url + '[/mail]');
    }
}
function setAcro()
{
  var acro = prompt('Bitte geben Sie das Akronym ein!');
  if(acro)
    {
      var acrotext = prompt('Bitte geben Sie die Erläuterung ein!');
      if(acrotext)
          setHTML('[acronym=' + acrotext + ']' + acro + '[/acronym]');
    }
}*/
