


jQuery.extend(
{
  
  markup: function(textarea, settings, extraSettings)
  {
    var PLAINTEXT= 1, RICHTEXT= 0;

    //return this.each(function()
    //{
      var currentEditor= PLAINTEXT;
      var ctrlKey, shiftKey, altKey;
      var menuButtons= new Array();
      var $$, scrollPosition, caretPosition, caretOffset, clicked, hash;
      ctrlKey = shiftKey = altKey;
      var options =
      {
        id:           '',
        target:   null,
        targetAutoRefresh:   true,
        resizeHandle:     true,
        beforeInsert:     '',
        afterInsert:      '',
        onEnter:        {},
        onShiftEnter:     {},
        onCtrlEnter:      {},
        onTab:          {},
        replacement: [/\n{3,}/, '\n\n'],
        menuContainer: null,
        markupSet:      [ { /* set */ } ],
        updateInterval:   null,
        allowedTags: [],
        tagPermission: {},
        keywords:      { /* set */ }
      };
      $.extend(options, settings, extraSettings);
      
        
      abort = false;
      scrollPosition = caretPosition = 0;
      caretOffset = -1;
      
      var result= 
      {
        plaineditor: textarea,
        richeditor: null,
            
        getBBCode: function() { if(currentEditor == RICHTEXT) {result.updateBBCode();} return this.plaineditor.val(); },
        getHTML: function() { return this.richeditor.html(); },
        
        getText: function() { return dom2text(result.richeditor.get(0)); },
        
        getCurrentEditor: function() { return currentEditor; },
        
        updateBBCode: function()
        {
          var bbcode= result.richeditor.bbcode({allowedTags: options.allowedTags});
          //console.log(result.richeditor.html());
          //console.log(bbcode);
          if (options.replacement) bbcode= bbcode.replace(options.replacement[0], options.replacement[1]);
          result.plaineditor.val(bbcode);
        },
        
        updateHTML: function()
        {
          var bbcode= result.plaineditor.val().replace(/(\r\n|\n\r|\r|\n)/, '\n');
          if (options.replacement) bbcode= bbcode.replace(options.replacement[0], options.replacement[1]);
          result.richeditor.html(bbcode2html(bbcode, options.allowedTags));
        },
        
        refreshBBCode: function()
        {
        	var bbcode= result.plaineditor.val().replace(/(\r\n|\n\r|\r|\n)/, '\n');
            if (options.replacement) bbcode= bbcode.replace(options.replacement[0], options.replacement[1]);
            var html = "<div>"+bbcode2html(bbcode, options.allowedTags)+"</div>";
            bbcode=$(html).bbcode({allowedTags: options.allowedTags});
            console.log(bbcode);
            //result.plaineditor.val(bbcode);
        },
        
        stripBBCode: function()
        {
        	var bbcode= result.plaineditor.val().replace(/(\r\n|\n\r|\r|\n)/, '\n');
            if (options.replacement) bbcode= bbcode.replace(options.replacement[0], options.replacement[1]);
            var bbc = $("<body>"+bbcode+"</body>");
            bbc.find("script").remove();
            bbc.find("style").remove();
            //console.log(bbc);
            //console.log($(bbc).text());
           	result.plaineditor.val($(bbc).text());
        },
        
        update: function() { if (currentEditor==PLAINTEXT) {/*result.updateHTML();*/} else {/*result.updateBBCode();*/} },
        
        loadBBCode: function (script, params, onsuccess)
        {
          $.ajax({ type: "POST", url: script, data: params, success: function(bbcode)
          {
            plaineditor.val(bbcode);
            richeditor.html(bbcode2html (bbcode, options.allowedTags));
            if (onsuccess) onsuccess(bbcode); 
          }}); 
        }
      };
      
      result.plaineditor.extend(
      {
        container: textarea,
        doc: document,
        type: "plain-text",
        getBBCode: function() { return textarea.val(); },
        getHTML: function() { return bbcode2html (textarea.val(), options.allowedTags); }
      });
    
    function switchEditor(e)
    {
      if (currentEditor!=e.tabindex)
      {
        if (e.tabindex==RICHTEXT)
        {
        //alert(result.plaineditor.val());
          // synchronize editors
          //if (updateFields)
          {
            result.updateHTML();
          }
        //alert(result.richeditor.html());
          
          // update menu buttons
          for (var i in menuButtons)
          {
            menuButtons[i].setEnabled(menuButtons[i].richAction != undefined || menuButtons[i].independent);
          }
          // finally switch the views
          result.plaineditor.//container.
          hide();
          result.richeditor.container.show();
        }
        else
        {
          // synchronize editors
          //if (updateFields)
          {
            result.updateBBCode();
          }
          
          // update menu buttons
          for (var i in menuButtons)
          {
            menuButtons[i].setEnabled(menuButtons[i].plainAction != undefined || menuButtons[i].independent);
          }
          // finally switch the views
          result.richeditor.container.hide();
          result.plaineditor//.container
          .show();
        }
        //updateFields= false;
        currentEditor= e.tabindex;
      }
    }
  

  function insertNodeAtSelection(win, insertNode)
  {
      // get current selection
      var sel = 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);
          var 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 getOffsetTop(elm) {

  var mOffsetTop = elm.offsetTop;
  var mOffsetParent = elm.offsetParent;

  while(mOffsetParent){
    mOffsetTop += mOffsetParent.offsetTop;
    mOffsetParent = mOffsetParent.offsetParent;
  }
 
  return mOffsetTop;
}

function getOffsetLeft(elm) {

  var mOffsetLeft = elm.offsetLeft;
  var mOffsetParent = elm.offsetParent;

  while(mOffsetParent){
    mOffsetLeft += mOffsetParent.offsetLeft;
    mOffsetParent = mOffsetParent.offsetParent;
  }
 
  return mOffsetLeft;
}
      
      // define markup to insert
      function createMarkup(button)
      {
        var len, j, n, i;
        hash = clicked = button;       

        if (currentEditor==RICHTEXT)
        {
          result.richeditor.container.get(0).contentWindow.focus();
          if (button.richAction.command == "createtable")
          {
            if (
            (rows = 2//parseInt(prompt("Bitten geben Sie Anzahl der Zeilen ein:"))
            ) > 0 && 
            (cols = 2//parseInt(prompt("Bitten geben Sie Anzahl der Spalten ein:"))
            ) > 0)
            {
              table = result.richeditor.container.get(0).contentWindow.document.createElement("table");
              table.setAttribute("width", "100%");
              table.setAttribute("height", 25*rows);
              tbody = result.richeditor.container.get(0).contentWindow.document.createElement("tbody");
              colgroup =result.richeditor.container.get(0).contentWindow.document.createElement("colgroup");
              for (var j=0; j < cols; j++)
              {
                col =result.richeditor.container.get(0).contentWindow.document.createElement("col");
                col.setAttribute("width", (100.0/cols)+"%");
                colgroup.appendChild(col);
              }
              table.appendChild(colgroup);
              for (var i=0; i < rows; i++)
              {
                tr =result.richeditor.container.get(0).contentWindow.document.createElement("tr");
                for (var j=0; j < cols; j++)
                {
                  td =result.richeditor.container.get(0).contentWindow.document.createElement("td");
                  tr.appendChild(td);
                }
                tbody.appendChild(tr);
              }
              table.appendChild(tbody);      
              insertNodeAtSelection(result.richeditor.container.get(0).contentWindow, table);
            }
          }
          else
          {   
            try
            {
              result.richeditor.doc.execCommand(button.richAction.command, false, promptDynamicValues(button.richAction.value));
            }
            catch(e)
            {//console.log(e)
            }
          }
          result.richeditor.container.get(0).contentWindow.focus();
        }
        else
        {
        grabSelection();
        $.extend(hash, {  line:"", 
                  selection:(selection||''), 
                  caretPosition:caretPosition,
                  ctrlKey:ctrlKey, 
                  shiftKey:shiftKey, 
                  altKey:altKey
                });
                
        // callbacks before insertion
        prepare(options.beforeInsert);
        prepare(clicked.beforeInsert);
        if (ctrlKey === true && shiftKey === true)
        {
          prepare(clicked.beforeMultiInsert);
        }
        $.extend(hash, { line:1 });
        
        if (ctrlKey === true && shiftKey === true)
        {
          lines = selection.split(/\r?\n/);
          for (j = 0, n = lines.length, i = 0; i < n; i++)
          {
            if ($.trim(lines[i]) !== '')
            {
              $.extend(hash, { line:++j, selection:lines[i] } );
              lines[i] = build(lines[i]).block;
            }
            else
            {
              lines[i] = "";
            }
          }
          string = { block:lines.join('\n')};
          start = caretPosition;
          len = string.block.length + (($.browser.opera) ? n : 0);
        }
        else if (ctrlKey === true)
        {
          string = build(selection);
          start = caretPosition + string.openWith.length;
          len = string.block.length - string.openWith.length - string.closeWith.length;
          len -= fixIeBug(string.block);
        }
        else if (shiftKey === true)
        {
          string = build(selection);
          start = caretPosition;
          len = string.block.length;
          len -= fixIeBug(string.block);
        }
        else
        {
          string = build(selection);
          start = caretPosition + string.block.length ;
          len = 0;
          start -= fixIeBug(string.block);
        }
        if ((selection === '' && string.replaceWith === ''))
        {
          caretOffset += fixOperaBug(string.block);
          
          start = caretPosition + string.openWith.length;
          len = string.block.length - string.openWith.length - string.closeWith.length;
          
          var selectedText= result.plaineditor.val();
          caretOffset = selectedText.substring(caretPosition,  selectedText.length).length;
          caretOffset -= fixOperaBug(selectedText.substring(0, caretPosition));
        }
        $.extend(hash, { caretPosition:caretPosition, scrollPosition:scrollPosition } );

        if (string.block !== selection && abort === false)
        {
          insert(string.block);
          updateSelection(start, len);
        }
        else
        {
          caretOffset = -1;
        }
        grabSelection();

        $.extend(hash, { line:'', selection:selection });

        // callbacks after insertion
        if (ctrlKey === true && shiftKey === true)
        {
          prepare(clicked.afterMultiInsert);
        }
        prepare(clicked.afterInsert);
        prepare(options.afterInsert);
                                                  
        // reinit keyevent
        shiftKey = altKey = ctrlKey = abort = false;
        }
      }
      // add markup
      function insert(block)
      { 
        if (result.plaineditor.doc.selection)
        {
          var newSelection = result.plaineditor.doc.selection.createRange();
          newSelection.text = block;
        }
        else
        {
          var selectedText= result.plaineditor.val();
          result.plaineditor.val(selectedText.substring(0, caretPosition) + block + selectedText.substring(caretPosition + selection.length, selectedText.length));
        }
      }
      

      // markup! markups
      function promptDynamicValues(string)
      {
        if (string)
        {
          string = string.toString();
          string = string.replace(/\(\!\(([\s\S]*?)\)\!\)/g,
            function(x, a)
            {
              var b = a.split('|!|');
              return  altKey === true?
                ((b[1] !== undefined) ? b[1] : b[0]):
                ((b[1] === undefined) ? "" : b[0]);
            });
          // [![prompt]!], [![prompt:!:value]!]
          string = string.replace(/\[\!\[([\s\S]*?)\]\!\]/g,
            function(x, a)
            {
              var b = a.split(':!:');
              if (abort === true)
                return false;
              value = prompt(b[0], (b[1]) ? b[1] : '');
              if (value === null)
                abort = true;
              return value;
            });
          return string;
        }
        return "";
      }

      // prepare action
      function prepare(action)
      {
        if ($.isFunction(action)) action = action(hash);
        return promptDynamicValues(action);
      }

      // build block to insert
      function build(string)
      {
        openWith  = prepare(clicked.plainAction.openWith);
        placeHolder = prepare(clicked.plainAction.placeHolder);
        replaceWith = prepare(clicked.plainAction.replaceWith);
        closeWith   = prepare(clicked.plainAction.closeWith);
        if (replaceWith !== "")
          block = openWith + replaceWith + closeWith;
        else if (selection === '' && placeHolder !== '')
          block = openWith + placeHolder + closeWith;
        else
          block = openWith + (string||selection) + closeWith;
        return {  block:block, 
              openWith:openWith, 
              replaceWith:replaceWith, 
              placeHolder:placeHolder,
              closeWith:closeWith
          };
      }

      // Substract linefeed in Opera
      function fixOperaBug(string)
      {
        return $.browser.opera? string.length - string.replace(/\n*/g, '').length: 0;
      }
      // Substract linefeed in IE
      function fixIeBug(string)
      {
        return $.browser.msie? string.length - string.replace(/\r*/g, '').length: 0;
      }

      // set a selection
      function updateSelection(start, len)
      {
        if (result.plaineditor.get(0).createTextRange)
        {
          // quick fix to make it work on Opera 9.5
          if ($.browser.opera && $.browser.version >= 9.5 && len == 0)
          {
            return false;
          }
          range = result.plaineditor.get(0).createTextRange();
          range.collapse(true);
          range.moveStart('character', start); 
          range.moveEnd('character', len); 
          range.select();
        }
        else if (result.plaineditor.get(0).setSelectionRange )
        {
          result.plaineditor.get(0).setSelectionRange(start, start + len);
        }
        result.plaineditor.get(0).scrollTop = scrollPosition;
        result.plaineditor.get(0).focus();
      }
      function getRangeObject(selObj,doc)
      {
        if (selObj.getRangeAt)
        {
          return selObj.getRangeAt(0);
        }
        else
        { // Old Safari!
          var range = doc.createRange();
          range.setStart(selObj.anchorNode,selObj.anchorOffset);
          range.setEnd(selObj.focusNode,selObj.focusOffset);
          return range;
        }
      }
      // get the selection
      function grabSelection()
      {
        //editors[current].result.get(0).focus();
        scrollPosition = result.plaineditor.get(0).scrollTop;
        if (result.plaineditor.doc.selection)
        {
          selection = result.plaineditor.doc.selection.createRange().text;
          if ($.browser.msie)
          { // ie
            var range = result.plaineditor.doc.selection.createRange(), rangeCopy = range.duplicate();
            rangeCopy.moveToElementText(result.plaineditor.get(0));
            caretPosition = -1;
            while(rangeCopy.inRange(range))
            { // fix most of the ie bugs with linefeeds...
              rangeCopy.moveStart('character');
              caretPosition ++;
            }
          }
          else
          { // opera
            caretPosition = result.plaineditor.get(0).selectionStart;
          }
        }
        else
        { // gecko
          var selectedText= null;
          var selectionEnd= null;
          
          if (currentEditor==PLAINTEXT)
          {
            caretPosition = result.plaineditor.get(0).selectionStart;
            selectedText= result.plaineditor.val();
            selectionEnd= result.plaineditor.get(0).selectionEnd;
          selection = selectedText.substring(caretPosition, selectionEnd);
          }
        } 
        return selection;
      }

      // open preview window
      function preview()
      {
        if (!options.targetAutoRefresh)
        {
          refreshPreview(); 
        }
      }

      // refresh Preview window
      function refreshPreview()
      {
        if (options.target)
          options.target.html (bbcode2html(result.plaineditor.val(), options.allowedTags));
      }
      
            var defaultButtonStructure= {                          
              enabled: true,
              setEnabled: function (state) { this.enabled= state; if (state) $(this).removeClass("disabled"); else $(this).addClass("disabled"); },
              isEnabled: function () { return this.enabled; }
            };           
      
         // recursively build header with dropMenus from markupset
      function dropMenus(markupSet)
      {
        var menu = $('<menu></menu>'), i = 0;
        $('li:hover > menu', menu).css('display', 'block');
        $(markupSet).each(function()
        {
          var item = this, title, li, j;

          title = ' title="'+((item.key) ? (item.tooltip||'')+' [Ctrl+'+item.key+']' : (item.tooltip||''))+'"';
          key   = (item.key) ? ' accesskey="'+item.key+'"' : '';
          style= item.style? ' style="'+item.style+'"': '';
          id= item.id? ' id="'+item.id+'"': '';


          
          if (item.type=="separator")
          {
            li = $('<li class="separator">'+(item.separator||'')+'</li>').appendTo(menu);
          }
          else if (item.type=="button")
          {
          if (item.tag)
          {
          if (item.tag instanceof Array)options.allowedTags= options.allowedTags.concat(item.tag);
          else options.allowedTags.push(item.tag);
            options.tagPermission[item.tag]= true;
          }
            i++; 
            li = $('<li'+(this.className? ' class="'+this.className+'"': '')+'><a href=""'+id+key+title+style+'>'+(this.icon? '<img src="'+this.icon+'" />':this.text||this.tooltip||'')+'</a></li>');
                
            li.bind("contextmenu", function()
            { // prevent contextmenu on mac and allow ctrl+click
              return false;
            }).click(function()
            {
              if (item.call) eval(item.call)(result);
              if (!item.independent) createMarkup(item);
              return false;
            }).hover(function()
            {
              $('> menu', this).show();
              $(document).one('click', function(){ $('menu menu', main_component).hide(); }); // close dropmenu if click outside
            }, function()
            {
              $('> menu', this).hide();
            }).appendTo(menu);
            if (item.dropMenu)
            {
              $(li).addClass('dropmenu').append(dropMenus(item.dropMenu));
            }
            $.extend(li, defaultButtonStructure, item);
            menuButtons.push(li);
          }
          else if (item.type=="label")
          {
            var forid= item.forID? ' for="'+item.forID+'"': '';
            var label= $('<label'+id+forid+key+title+style+'>'+item.text+'</label>');
            li = $('<li'+(item.className? ' class="'+item.className+'"': '')+'></li>');
            label.appendTo (li);
            li.appendTo(menu);
          }
          else if (item.type=="combobox")
          {
            var combobox= $(item.editable?'<input type=\"text\"'+id+key+title+style+'>': '<select '+id+key+title+style+'>');
            if (item.queryScript)
            {
              for (var j in item.queryParams)
              {
                if (options.keywords[j])
                  item.queryParams[j]= options.keywords[j];
              }
              combobox.load(item.queryScript, item.queryParams, item.querySuccess);
            }
            if (item.change)
              combobox.change (function () { item.change(result, $(this).val()); });
            li = $('<li'+(item.className? ' class="'+item.className+'"': '')+'></li>');
            combobox.appendTo (li);
            li.appendTo(menu);
          }
        }); 
        return menu;
      }
      
      
      
    if (options.menuContainer)
    {      
      options.menuContainer.addClass("markup");      
    
      function tryEnableDesignMode(iframeDoc, doc, initCallback)
      {
        try
        {
          with (iframeDoc) { open('text/html', 'append'); charset= "iso-8859-1"; write(doc); close(); }
        }
        catch(error)
        {     
        }
        if (document.contentEditable)
        {
          iframeDoc.designMode = "On";  
          setTimeout(initCallback, 250);
          return true;
        }
        else if (document.designMode != null)
        {
          try
          {
            iframeDoc.designMode = "on";
            setTimeout(initCallback, 250);
            return true;
          }
          catch (error)
          {      
          }
        }
        setTimeout(function() {tryEnableDesignMode(iframeDoc,doc,initCallback)}, 250);
        return false;
      }
      var currentTab= null;
      var tabMenus= $(options.markupSet);
      var main_component = $('<div class="main_component"></div>');  
      if (tabMenus.size()==1)
      {
        main_component.append(dropMenus(tabMenus.get(0).menu));
      }
      else
      {
        // add the header before the textarea    
        var tabBar = $('<menu class="tabmenu"></menu>');
        main_component.append(tabBar);
        tabMenus.each(function()
      {
        var tabMenu= this;
        var title= ' title="'+((this.key) ? (this.tooltip||'')+' [Ctrl+'+this.key+']' : (this.tooltip||''))+'"';
        var key= (this.key) ? ' accesskey="'+this.key+'"' : '';
        var style= this.style? ' style="'+this.style+'"': '';
        var id= this.id? ' id="'+this.id+'"': '';
        var tab= $('<li'+(this.className? ' class="'+this.className+'"': '')+'><a href=""'+id+key+title+style+'>'+(this.icon? '<img src="'+this.icon+'" />':this.text||this.tooltip||'')+'</a></li>');
        tab.data('component', dropMenus(this.menu));
        tab.addClass('tab').click(function()
        {
          
          if (tab != currentTab)
          {
            currentTab.data('component').hide();
            currentTab.removeClass('selected');
            currentTab= tab;
            currentTab.addClass('selected');
            currentTab.data('component').show();
          }
          if (tabMenu.menu.click)
            menu.click(this);
          return false;
        });        
        tabBar.append(tab);
        main_component.append(tab.data('component'));
        
        if (!currentTab)
        {
          currentTab= tab;
          currentTab.addClass('selected');
        }
        else
          tab.data('component').hide();
      });
      }
      options.menuContainer.prepend(main_component);
    }
      
      
      if(document.designMode || document.contentEditable)
      {
      
      var rte=
      {
          container: $('<iframe class="rte_iframe" scrolling="auto"></iframe>'),
          doc: null,
          type: 'rich-text',
          getBBCode: function() { return html2bbcode ($(this).html()); },
          getHTML: function() { return $(this).html(); }
      };
      
        // need to be created this way
        var content= result.plaineditor.val();
        // Mozilla need this to display caret
        if($.trim(content)=='')
          content= '<br>';
        var doc= '<html><head><meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"/><link href="layout/css.css" rel="stylesheet" type="text/css" /><link href="layout/markup.css" rel="stylesheet" type="text/css" /></head><body class="editor markup_view">'+bbcode2html(content, options.allowedTags)+'</body></html>';//
        
        result.plaineditor.after(rte.container);
        
        rte.doc= rte.container.get(0).contentWindow.document;
        
        tryEnableDesignMode(rte.doc,doc,function ()
        {
          rte.container.css({width: result.plaineditor.css("width"), height: result.plaineditor.css("height")});
          result.richeditor= $(rte.doc).find("body");
          /*
          result.richeditor.focus(function()
        		  {
          	console.log("FOCUS");
  	        $(this).css("background-color", "yellow");
  		  }).blur(function()
        		  {
          	console.log("BLUR");
  	        $(this).css("background-color", "white");
  		  }).mouseup(function()
        		  {
            	console.log("MOUSEUP");
    		  }).change(function()
            		  {
    	          	console.log("CHANGE");
    	  		  });
    	  		  */
          $.extend(result.richeditor, rte);
          // IE
          if (jQuery.browser.msie)
            result.richeditor.bind('paste',function (e) { //alert('Paste 1:\n'+$(rte).html()); 
            setTimeout(function()
                {
                console.log("before");
                console.log($(result.richeditor).html());
                  var bbcode= $(result.richeditor).bbcode({allowedTags: options.allowedTags});
                  if (options.replacement) bbcode= bbcode.replace(options.replacement[0], options.replacement[1]);
                console.log(" ");
                console.log(bbcode);
                console.log(" ");
                  result.richeditor.html(bbcode2html(bbcode, options.allowedTags));
                console.log("after");
                console.log($(result.richeditor).html());
                console.log(" ");
                }, 5); });
          // Firefox
          else
            $(rte.doc).keyup(function(e)
            {
              if (
              (e.ctrlKey && e.keyCode == 86)//e.DOM_VK_V
               || 
               (e.shiftKey && e.keyCode == 45)//e.DOM_VK_INSERT
              )
              {
                setTimeout(function()
                {
                console.log("before");
                console.log($(result.richeditor).html());
                  var bbcode= $(result.richeditor).bbcode({allowedTags: options.allowedTags});
                  if (options.replacement) bbcode= bbcode.replace(options.replacement[0], options.replacement[1]);
                console.log(" ");
                console.log(bbcode);
                console.log(" ");
                  result.richeditor.html(bbcode2html(bbcode, options.allowedTags));
                console.log("after");
                console.log($(result.richeditor).html());
                console.log(" ");
                }, 5);
              }
              return true;
            });
            
            
        
        var editorSwitcher = $('<menu></menu>');
        var richModeBtn= $('<li><a><img src=\"gfx/markup/page_white_word.png\" style=\"vertical-align: middle;\"> Designer-Ansicht</a></li>');
        var plainModeBtn= $('<li><a><img src=\"gfx/markup/page_white_text.png\" style=\"vertical-align: middle;\"> Quelltext-Ansicht</a></li>')
        richModeBtn.click(function(){ if (currentEditor!=RICHTEXT) { switchEditor ({source: $(this), tabindex: RICHTEXT}); plainModeBtn.removeClass('selected'); richModeBtn.addClass('selected'); } return false; }).appendTo(editorSwitcher);
        plainModeBtn.click(function(){ if (currentEditor!=PLAINTEXT) { switchEditor ({source: $(this), tabindex: PLAINTEXT}); richModeBtn.removeClass('selected'); plainModeBtn.addClass('selected'); } return false; }).appendTo(editorSwitcher);

        // add the header before the textarea
        var editorSwitcherPanel = $('<div class="tabs"></div>');
        editorSwitcher.appendTo(editorSwitcherPanel);
        //rte.container.after(editorSwitcherPanel);
        main_component.append(editorSwitcherPanel);
        rte.container.hide();
        richModeBtn.click();
        
          if (options.updateInterval) setInterval(result.update,options.updateInterval);
        });
      }
    //});
    
    return result;
  }
});

