Fixed bug #8232: Creating and editing of fields, forms, etc. in FCE's is impossible...
authorDmitry Dulepov <dmitry.dulepov@gmail.com>
Mon, 18 Aug 2008 15:59:20 +0000 (15:59 +0000)
committerDmitry Dulepov <dmitry.dulepov@gmail.com>
Mon, 18 Aug 2008 15:59:20 +0000 (15:59 +0000)
git-svn-id: https://svn.typo3.org/TYPO3v4/Core/trunk@3995 709f56b5-9817-0410-a4d7-c38de5d9e867

ChangeLog
t3lib/class.t3lib_tceforms.php
typo3/sysext/rtehtmlarea/class.tx_rtehtmlarea_base.php
typo3/sysext/rtehtmlarea/pi2/class.tx_rtehtmlarea_pi2.php

index a6451ef..cac4686 100755 (executable)
--- a/ChangeLog
+++ b/ChangeLog
@@ -6,6 +6,7 @@
        * Fixed bug #9141: Update Wizard uses wrong scheme to write compat_version to localconf.php
        * Fixed bug #9152: Deprecated code into stdgraphic
        * Fixed bug #9183: saveDocNew for all tables except the option is set to 0
+       * Fixed bug #8232: Creating and editing of fields, forms, etc. in FCE's is impossible if there is a section inside
 
 2008-08-16  Stanislas Rolland  <typo3@sjbr.ca>
 
index 1c834de..feb3bec 100755 (executable)
@@ -301,6 +301,7 @@ class t3lib_TCEforms        {
        var $additionalJS_pre = array();                        // Additional JavaScript, printed before the form
        var $additionalJS_post = array();                       // Additional JavaScript printed after the form
        var $additionalJS_submit = array();                     // Additional JavaScript executed on submit; If you set "OK" variable it will raise an error about RTEs not being loaded and offer to block further submission.
+       var $additionalJS_delete = array();                     // Additional JavaScript executed when section element is deleted. This is neceessary, for example, to correctly clean up HTMLArea RTE (bug #8232)
 
        /**
         * Instance of t3lib_tceforms_inline
@@ -980,7 +981,7 @@ class t3lib_TCEforms        {
                                $hookObject->getSingleField_beforeRender($table, $field, $row, $PA);
                        }
                }
-               
+
                switch($PA['fieldConf']['config']['form_type']) {
                        case 'input':
                                $item = $this->getSingleField_typeInput($table,$field,$row,$PA);
@@ -1653,7 +1654,7 @@ class t3lib_TCEforms      {
 
                        // Get values in an array (and make unique, which is fine because there can be no duplicates anyway):
                $itemArray = array_flip($this->extractValuesOnlyFromValueLabelList($PA['itemFormElValue']));
-               
+
                $disabled = '';
                if($this->renderReadonly || $config['readOnly'])  {
                        $disabled = ' disabled="disabled"';
@@ -1674,7 +1675,7 @@ class t3lib_TCEforms      {
                                                                        <td colspan="3">' .
                                                                                '<a href="#" onclick="' . htmlspecialchars(implode('', $setAll).' return false;') . '">' .
                                                                                htmlspecialchars($this->getLL('l_checkAll')) .
-                                                                               '</a>  
+                                                                               '</a>
                                                                                <a href="#" onclick="' . htmlspecialchars(implode('', $unSetAll).' return false;').'">' .
                                                                                htmlspecialchars($this->getLL('l_uncheckAll')) .
                                                                                '</a>
@@ -1712,13 +1713,13 @@ class t3lib_TCEforms    {
                                        $restoreCmd[] = $this->elName($PA['itemFormElName'] . '[' . $c . ']') . '.checked=' . ($sM ? 1 : 0) . ';' .
                                                                '$(\'' . $rowId . '\').removeClassName(\'c-selectedItem\');$(\'' . $rowId . '\').removeClassName(\'c-unselectedItem\');' .
                                                                '$(\'' . $rowId . '\').addClassName(\'c-' . ($sM ? '' : 'un') . 'selectedItem\');';
-                                       
+
                                        $hasHelp = ($p[3] !='');
-                                       
+
                                        $label = t3lib_div::deHSCentities(htmlspecialchars($p[0]));
-                                       $help = $hasHelp ? '<span class="typo3-csh-inline show-right"><span class="header">' . $label . '</span>' . 
+                                       $help = $hasHelp ? '<span class="typo3-csh-inline show-right"><span class="header">' . $label . '</span>' .
                                                '<span class="paragraph">' . $GLOBALS['LANG']->hscAndCharConv(nl2br(trim(htmlspecialchars($p[3]))), false) . '</span></span>' : '';
-                                       
+
                                        if ($hasHelp && $this->edit_showFieldHelp == 'icon') {
                                                $helpIcon  = '<a class="typo3-csh-link" href="#">';
                                                $helpIcon .= '<img' . t3lib_iconWorks::skinImg($this->backPath, 'gfx/helpbubble.gif', 'width="14" height="14"');
@@ -1747,7 +1748,7 @@ class t3lib_TCEforms      {
                                                        <td colspan="3">'.
                                                                '<a href="#" onclick="' . htmlspecialchars(implode('', $setAll).' return false;') . '">' .
                                                                htmlspecialchars($this->getLL('l_checkAll')) .
-                                                               '</a>  
+                                                               '</a>
                                                                <a href="#" onclick="' . htmlspecialchars(implode('', $unSetAll).' return false;') . '">' .
                                                                htmlspecialchars($this->getLL('l_uncheckAll')) .
                                                                '</a>
@@ -1777,7 +1778,7 @@ class t3lib_TCEforms      {
                        // Add revert icon
                if (is_array($restoreCmd)) {
                        $item .= '<a href="#" onclick="' . implode('', $restoreCmd).' return false;' . '">' .
-                               '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/undo.gif','width="13" height="12"') . ' title="' . 
+                               '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/undo.gif','width="13" height="12"') . ' title="' .
                                htmlspecialchars($this->getLL('l_revertSelection')) . '" alt="" />' .'</a>';
                }
                        // Implode rows in table:
@@ -2317,7 +2318,7 @@ class t3lib_TCEforms      {
                        if (!is_array($editData))       {       // Must be XML parsing error...
                                $editData=array();
                        } elseif (!isset($editData['meta']) || !is_array($editData['meta']))    {
-                           $editData['meta'] = array();
+                               $editData['meta'] = array();
                        }
 
                                // Find the data structure if sheets are found:
@@ -2553,6 +2554,10 @@ class t3lib_TCEforms     {
                                                                // Traversing possible types of new content in the section:
                                                        $newElementsLinks = array();
                                                        foreach($value['el'] as $nnKey => $nCfg)        {
+                                                               $additionalJS_post_saved = $this->additionalJS_post;
+                                                               $this->additionalJS_post = array();
+                                                               $additionalJS_submit_saved = $this->additionalJS_submit;
+                                                               $this->additionalJS_submit = array();
                                                                $newElementTemplate = $this->getSingleField_typeFlex_draw(
                                                                        array($nnKey => $nCfg),
                                                                        array(),
@@ -2566,7 +2571,17 @@ class t3lib_TCEforms     {
                                                                );
 
                                                                        // Makes a "Add new" link:
-                                                               $onClickInsert = 'new Insertion.Bottom($("'.$idTagPrefix.'"), unescape("'.rawurlencode($newElementTemplate).'").replace(/'.$idTagPrefix.'-/g,"'.$idTagPrefix.'-idx"+Math.floor(Math.random()*100000+1)+"-")); setActionStatus("'.$idTagPrefix.'"); return false;';      // Maybe there is a better way to do this than store the HTML for the new element in rawurlencoded format - maybe it even breaks with certain charsets? But for now this works...
+                                                               $var = uniqid('idvar');
+                                                               $replace = 'replace(/' . $idTagPrefix . '-/g,"' . $idTagPrefix . '"+' . $var . '+"-")';
+                                                               $onClickInsert = 'var ' . $var . ' = "' . $idTagPrefix . '-idx"+(new Date()).getTime();';
+                                                               // Do not replace $isTagPrefix in setActionStatus() because it needs section id!
+                                                               $onClickInsert .= 'new Insertion.Bottom($("'.$idTagPrefix.'"), unescape("'.rawurlencode($newElementTemplate).'").' . $replace . '); setActionStatus("'.$idTagPrefix.'");';
+                                                               $onClickInsert .= 'eval(unescape("' . rawurlencode(implode(';', $this->additionalJS_post)) . '").' . $replace . ');';
+                                                               $onClickInsert .= 'TBE_EDITOR.addActionChecks("submit", unescape("' . rawurlencode(implode(';', $this->additionalJS_submit)) . '").' . $replace . ');';
+                                                               $onClickInsert .= 'return false;';
+                                                               // Kasper's comment (kept for history): Maybe there is a better way to do this than store the HTML for the new element in rawurlencoded format - maybe it even breaks with certain charsets? But for now this works...
+                                                               $this->additionalJS_post = $additionalJS_post_saved;
+                                                               $this->additionalJS_submit = $additionalJS_submit_saved;
                                                                $newElementsLinks[]= '<a href="#" onclick="'.htmlspecialchars($onClickInsert).'"><img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/new_el.gif','width="11" height="12"').' alt="New" title="New" align="absmiddle" />'.htmlspecialchars(t3lib_div::fixed_lgd_cs($this->sL($nCfg['tx_templavoila']['title']),30)).'</a>';
                                                        }
 
@@ -2583,15 +2598,15 @@ class t3lib_TCEforms    {
 
                                                        <div id="'.$idTagPrefix.'" style="padding-left: 20px;">'.implode('',$tRows).'</div>';
                                                        $output.= $mayRestructureFlexforms ? '<div style="padding: 10px 5px 5px 20px;"><b>Add new:</b> '.implode(' | ',$newElementsLinks).'</div>' : '';
-                                                       // If it's a container:
                                                } else {
+                                                       // It is a container
 
                                                        $toggleIcon_open = '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/pil2down.gif','width="12" height="7"').' hspace="2" alt="Open" title="Open" />';
                                                        $toggleIcon_close = '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/pil2right.gif','width="7" height="12"').' hspace="2" alt="Close" title="Close" />';
 
                                                                // Create on-click actions.
-                                               #       $onClickCopy = 'new Insertion.After($("'.$idTagPrefix.'"), getOuterHTML("'.$idTagPrefix.'").replace(/'.$idTagPrefix.'-/g,"'.$idTagPrefix.'-copy"+Math.floor(Math.random()*100000+1)+"-")); return false;';      // Copied elements doesn't work (well) in Safari while they do in Firefox and MSIE! UPDATE: It turned out that copying doesn't work for any browser, simply because the data from the copied form never gets submitted to the server for some reason! So I decided to simply disable copying for now. If it's requested by customers we can look to enable it again and fix the issue. There is one un-fixable problem though; Copying an element like this will violate integrity if files are attached inside that element because the file reference doesn't get an absolute path prefixed to it which would be required to have TCEmain generate a new copy of the file.
-                                                       $onClickRemove = 'if (confirm("Are you sure?")){$("'.$idTagPrefix.'").hide();setActionStatus("'.$idPrefix.'");} return false;';
+                                                       //$onClickCopy = 'new Insertion.After($("'.$idTagPrefix.'"), getOuterHTML("'.$idTagPrefix.'").replace(/'.$idTagPrefix.'-/g,"'.$idTagPrefix.'-copy"+Math.floor(Math.random()*100000+1)+"-")); return false;';    // Copied elements doesn't work (well) in Safari while they do in Firefox and MSIE! UPDATE: It turned out that copying doesn't work for any browser, simply because the data from the copied form never gets submitted to the server for some reason! So I decided to simply disable copying for now. If it's requested by customers we can look to enable it again and fix the issue. There is one un-fixable problem though; Copying an element like this will violate integrity if files are attached inside that element because the file reference doesn't get an absolute path prefixed to it which would be required to have TCEmain generate a new copy of the file.
+                                                       $onClickRemove = 'if (confirm("Are you sure?")){/*###REMOVE###*/;$("'.$idTagPrefix.'").hide();setActionStatus("'.$idPrefix.'");} return false;';
                                                        $onClickToggle = 'flexFormToggle("'.$idTagPrefix.'"); return false;';
 
                                                        $onMove = 'flexFormSortable("'.$idPrefix.'")';
@@ -2622,6 +2637,7 @@ class t3lib_TCEforms      {
                                                        $actionFieldName = '_ACTION_FLEX_FORM'.$PA['itemFormElName'].$s[0].'][_ACTION]['.$s[1];
 
                                                                // Putting together the container:
+                                                       $this->additionalJS_delete = array();
                                                        $output.= '
                                                                <div id="'.$idTagPrefix.'" class="bgColor2">
                                                                        <input id="'.$idTagPrefix.'-action" type="hidden" name="'.htmlspecialchars($actionFieldName).'" value=""/>
@@ -2641,6 +2657,7 @@ class t3lib_TCEforms      {
                                                                        </div>
                                                                        <input id="'.$idTagPrefix.'-toggleClosed" type="hidden" name="'.htmlspecialchars('data['.$table.']['.$row['uid'].']['.$field.']'.$formPrefix.'[_TOGGLE]').'" value="'.($toggleClosed?1:0).'" />
                                                                </div>';
+                                                       $output = str_replace('/*###REMOVE###*/', t3lib_div::slashJS(htmlspecialchars(implode('', $this->additionalJS_delete))), $output);
                                                                        // NOTICE: We are saving the toggle-state directly in the flexForm XML and "unauthorized" according to the data structure. It means that flexform XML will report unclean and a cleaning operation will remove the recorded togglestates. This is not a fatal problem. Ideally we should save the toggle states in meta-data but it is much harder to do that. And this implementation was easy to make and with no really harmful impact.
                                                }
 
@@ -2663,7 +2680,7 @@ class t3lib_TCEforms      {
                                                                        'label' => $this->sL(trim($value['TCEforms']['label'])),
                                                                        'config' => $value['TCEforms']['config'],
                                                                        'defaultExtras' => $value['TCEforms']['defaultExtras'],
-                                    'onChange' => $value['TCEforms']['onChange']
+                                                                       'onChange' => $value['TCEforms']['onChange']
                                                                );
                                                                if ($PA['_noEditDEF'] && $PA['_lang']==='lDEF') {
                                                                        $fakePA['fieldConf']['config'] = array(
@@ -2673,7 +2690,7 @@ class t3lib_TCEforms      {
                                                                }
 
                                                                if (
-                                    $fakePA['fieldConf']['onChange'] == 'reload' ||
+                                                                       $fakePA['fieldConf']['onChange'] == 'reload' ||
                                                                        ($GLOBALS['TCA'][$table]['ctrl']['type'] && !strcmp($key,$GLOBALS['TCA'][$table]['ctrl']['type'])) ||
                                                                        ($GLOBALS['TCA'][$table]['ctrl']['requestUpdate'] && t3lib_div::inList($GLOBALS['TCA'][$table]['ctrl']['requestUpdate'],$key))) {
                                                                        if ($GLOBALS['BE_USER']->jsConfirmation(1))     {
@@ -5092,29 +5109,29 @@ class t3lib_TCEforms    {
                                        $(id+"-toggleClosed").value = 1;
                                }
 
-                           var previewContent = "";
-                           var children = $(id+"-content").getElementsByTagName("input");
-                           for (var i = 0, length = children.length; i < length; i++) {
+                               var previewContent = "";
+                               var children = $(id+"-content").getElementsByTagName("input");
+                               for (var i = 0, length = children.length; i < length; i++) {
                                        if (children[i].type=="text" && children[i].value)      previewContent+= (previewContent?" / ":"")+children[i].value;
-                           }
+                               }
                                if (previewContent.length>80)   {
                                        previewContent = previewContent.substring(0,67)+"...";
                                }
                                $(id+"-preview").update(previewContent);
                        }
                        function flexFormToggleSubs(id) {       // Toggling sub flexform elements on/off:
-                           var descendants = $(id).immediateDescendants();
+                               var descendants = $(id).immediateDescendants();
                                var isOpen=0;
                                var isClosed=0;
                                        // Traverse and find how many are open or closed:
-                           for (var i = 0, length = descendants.length; i < length; i++) {
+                               for (var i = 0, length = descendants.length; i < length; i++) {
                                        if (descendants[i].id)  {
                                                if (Element.visible(descendants[i].id+"-content"))      {isOpen++;} else {isClosed++;}
                                        }
-                           }
+                               }
 
                                        // Traverse and toggle
-                           for (var i = 0, length = descendants.length; i < length; i++) {
+                               for (var i = 0, length = descendants.length; i < length; i++) {
                                        if (descendants[i].id)  {
                                                if (isOpen!=0 && isClosed!=0)   {
                                                        if (Element.visible(descendants[i].id+"-content"))      {flexFormToggle(descendants[i].id);}
@@ -5122,7 +5139,7 @@ class t3lib_TCEforms      {
                                                        flexFormToggle(descendants[i].id);
                                                }
                                        }
-                           }
+                               }
                        }
                        function flexFormSortable(id)   {       // Create sortables for flexform sections
                                Sortable.create(id, {tag:\'div\',constraint: false, onChange:function(){
@@ -5130,14 +5147,14 @@ class t3lib_TCEforms    {
                                } });
                        }
                        function setActionStatus(id)    {       // Updates the "action"-status for a section. This is used to move and delete elements.
-                           var descendants = $(id).immediateDescendants();
+                               var descendants = $(id).immediateDescendants();
 
                                        // Traverse and find how many are open or closed:
-                           for (var i = 0, length = descendants.length; i < length; i++) {
+                               for (var i = 0, length = descendants.length; i < length; i++) {
                                        if (descendants[i].id)  {
                                                $(descendants[i].id+"-action").value = descendants[i].visible() ? i : "DELETE";
                                        }
-                           }
+                               }
                        }
 
                        TBE_EDITOR.images.req.src = "'.t3lib_iconWorks::skinImg($this->backPath,'gfx/required_h.gif','',1).'";
index 4fd6047..863da97 100644 (file)
@@ -69,7 +69,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
        var $conf_toolbar_hide = array (
                'showhelp',             // Has no content yet
                );
-       
+
                // Always show these toolbar buttons (TYPO3 button name)
        var $conf_toolbar_show = array (
                'undo',
@@ -77,10 +77,10 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                //'showhelp',
                'about',
                );
-       
+
                // The order of the toolbar: the name is the TYPO3-button name
        var $defaultToolbarOrder;
-       
+
                // Conversion array: TYPO3 button names to htmlArea button names
        var $convertToolbarForHtmlAreaArray = array (
                'line'                  => 'InsertHorizontalRule',
@@ -91,11 +91,11 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                'bar'                   => 'separator',
                'linebreak'             => 'linebreak',
                );
-       
+
        var $pluginList;
        var $pluginButton = array();
        var $pluginLabel = array();
-       
+
                // External:
        var $RTEdivStyle;                       // Alternative style for RTE <div> tag.
        public $httpTypo3Path;
@@ -110,12 +110,12 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
 
                // For the editor
        var $client;
-       
-       /**
-        * Reference to parent object, which is an instance of the TCEforms
-        *
-        * @var t3lib_TCEforms
-        */
+
+          /**
+               * Reference to parent object, which is an instance of the TCEforms
+               *
+               * @var t3lib_TCEforms
+               */
        var $TCEform;
        var $elementId;
        var $elementParts;
@@ -138,17 +138,17 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
        protected $pluginEnabledArray = array();                // Array of plugin id's enabled in the current RTE editing area
        protected $pluginEnabledCumulativeArray = array();      // Cumulative array of plugin id's enabled so far in any of the RTE editing areas of the form
        protected $registeredPlugins = array();                 // Array of registered plugins indexd by their plugin Id's
-       
+
        /**
         * Returns true if the RTE is available. Here you check if the browser requirements are met.
         * If there are reasons why the RTE cannot be displayed you simply enter them as text in ->errorLog
         *
         * @return      boolean         TRUE if this RTE object offers an RTE in the current browser environment
         */
-       
+
        function isAvailable()  {
                global $TYPO3_CONF_VARS;
-               
+
                $this->client = $this->clientInfo();
                $this->errorLog = array();
                if (!$this->debugMode)  {       // If debug-mode, let any browser through
@@ -176,7 +176,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                                        } // End of Browser Check
                                } // foreach: Browser Check
                        } else {
-                               // no Browser config for this RTE-Editor, so all Clients are allow                         
+                               // no Browser config for this RTE-Editor, so all Clients are allow
                        }
                        if (!$rteIsAvailable) {
                                $this->errorLog[] = 'rte: Browser not supported. Only msie Version 5 or higher and Mozilla based client 1. and higher.';
@@ -204,22 +204,22 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
         * @param       integer         PID value of record (true parent page id)
         * @return      string          HTML code for RTE!
         */
-       
+
        function drawRTE($parentObject, $table, $field, $row, $PA, $specConf, $thisConfig, $RTEtypeVal, $RTErelPath, $thePidValue) {
                global $BE_USER, $LANG, $TYPO3_DB, $TYPO3_CONF_VARS;
-               
+
                $this->TCEform =& $parentObject;
                $inline =& $this->TCEform->inline;
                $LANG->includeLLFile('EXT:' . $this->ID . '/locallang.xml');
                $this->client = $this->clientInfo();
                $this->typoVersion = t3lib_div::int_from_ver(TYPO3_version);
                $this->userUid = 'BE_' . $BE_USER->user['uid'];
-               
+
                        // Draw form element:
                if ($this->debugMode)   {       // Draws regular text area (debug mode)
                        $item = parent::drawRTE($this->TCEform, $table, $field, $row, $PA, $specConf, $thisConfig, $RTEtypeVal, $RTErelPath, $thePidValue);
                } else {        // Draw real RTE
-               
+
                        /* =======================================
                         * INIT THE EDITOR-SETTINGS
                         * =======================================
@@ -256,14 +256,14 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
 
                                // Special configuration and default extras:
                        $this->specConf = $specConf;
-                       
+
                        if ($this->thisConfig['forceHTTPS']) {
                                $this->httpTypo3Path = preg_replace('/^(http|https)/', 'https', $this->httpTypo3Path);
                                $this->extHttpPath = preg_replace('/^(http|https)/', 'https', $this->extHttpPath);
                                $this->siteURL = preg_replace('/^(http|https)/', 'https', $this->siteURL);
                                $this->hostURL = preg_replace('/^(http|https)/', 'https', $this->hostURL);
                        }
-                       
+
                        /* =======================================
                         * LANGUAGES & CHARACTER SETS
                         * =======================================
@@ -275,7 +275,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                                $this->language='en';
                        }
                        $this->contentTypo3Language = $this->language;
-                       
+
                        $this->contentLanguageUid = ($row['sys_language_uid'] > 0) ? $row['sys_language_uid'] : 0;
                        if (t3lib_extMgm::isLoaded('static_info_tables')) {
                                if ($this->contentLanguageUid) {
@@ -303,11 +303,11 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                                        }
                                }
                        }
-                       
+
                                // Character sets: interface and content
                        $this->charset = $LANG->charSet;
                        $this->OutputCharset = $this->charset;
-                       
+
                        $this->contentCharset = $LANG->csConvObj->charSetArray[$this->contentTypo3Language];
                        $this->contentCharset = $this->contentCharset ? $this->contentCharset : 'iso-8859-1';
                        $this->origContentCharSet = $this->contentCharset;
@@ -317,7 +317,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                         * TOOLBAR CONFIGURATION
                         * =======================================
                         */
-                       
+
                                // htmlArea plugins list
                        $this->pluginEnabledArray = t3lib_div::trimExplode(',', $this->pluginList, 1);
                        $this->enableRegisteredPlugins();
@@ -337,13 +337,13 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
 
                                // Check if some plugins need to be disabled
                        $this->setPlugins();
-                       
+
                                // Merge the list of enabled plugins with the lists from the previous RTE editing areas on the same form
                        $this->pluginEnabledCumulativeArray[$this->TCEform->RTEcounter] = $this->pluginEnabledArray;
                        if ($this->TCEform->RTEcounter > 1 && isset($this->pluginEnabledCumulativeArray[$this->TCEform->RTEcounter-1]) && is_array($this->pluginEnabledCumulativeArray[$this->TCEform->RTEcounter-1])) {
                                $this->pluginEnabledCumulativeArray[$this->TCEform->RTEcounter] = array_unique(array_values(array_merge($this->pluginEnabledArray,$this->pluginEnabledCumulativeArray[$this->TCEform->RTEcounter-1])));
                        }
-                       
+
                        /* =======================================
                         * SET STYLES
                         * =======================================
@@ -393,11 +393,11 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                        $this->editedContentCSS = $skinDir . '/htmlarea-edited-content.css';
                        $this->TCEform->additionalCode_pre['loadCSS'] .= '
                <link rel="alternate stylesheet" type="text/css" href="' . $this->editedContentCSS . '" />';
-                       
+
                                // Main skin
                        $this->TCEform->additionalCode_pre['loadCSS'] .= '
                <link rel="stylesheet" type="text/css" href="' . $this->editorCSS . '" />';
-                       
+
                                // Additional icons from registered plugins
                        foreach ($this->pluginEnabledCumulativeArray[$this->TCEform->RTEcounter] as $pluginId) {
                                if (is_object($this->registeredPlugins[$pluginId])) {
@@ -408,7 +408,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                                        }
                                }
                        }
-                       
+
                                // Loading JavaScript files and code
                        if ($this->TCEform->RTEcounter == 1) {
                                $this->TCEform->additionalCode_pre['loadJSfiles'] = $this->loadJSfiles($this->TCEform->RTEcounter);
@@ -422,7 +422,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
 
                                // Transform value:
                        $value = $this->transformContent('rte',$PA['itemFormElValue'],$table,$field,$row,$specConf,$thisConfig,$RTErelPath,$thePidValue);
-                       
+
                                // Further content transformation by registered plugins
                        foreach ($this->registeredPlugins as $pluginId => $plugin) {
                                if ($this->isPluginEnabled($pluginId) && method_exists($plugin, "transformContent")) {
@@ -446,18 +446,22 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                                $this->TCEform->additionalJS_post[] = $this->setRTEsizeByJS('RTEarea'.$this->TCEform->RTEcounter, $height, $width);
                        }
 
+                       $textAreaId = htmlspecialchars($PA['itemFormElName']);
+
                                // Register RTE in JS:
-                       $this->TCEform->additionalJS_post[] = $this->registerRTEinJS($this->TCEform->RTEcounter, $table, $row['uid'], $field);
+                       $this->TCEform->additionalJS_post[] = $this->registerRTEinJS($this->TCEform->RTEcounter, $table, $row['uid'], $field, $textAreaId);
 
                                // Set the save option for the RTE:
-                       $this->TCEform->additionalJS_submit[] = $this->setSaveRTE($this->TCEform->RTEcounter, $this->TCEform->formName, htmlspecialchars($PA['itemFormElName']));
+                       $this->TCEform->additionalJS_submit[] = $this->setSaveRTE($this->TCEform->RTEcounter, $this->TCEform->formName, $textAreaId);
+                       $this->TCEform->additionalJS_delete[] = $this->setDeleteRTE($this->TCEform->RTEcounter, $this->TCEform->formName, $textAreaId);
 
                                // Draw the textarea
                        $visibility = 'hidden';
+                       $unuqid = uniqid('rte');
                        $item = $this->triggerField($PA['itemFormElName']).'
-                               <div id="pleasewait' . $this->TCEform->RTEcounter . '" class="pleasewait" style="display: none;" >' . $LANG->getLL('Please wait') . '</div>
-                               <div id="editorWrap' . $this->TCEform->RTEcounter . '" class="editorWrap" style="width:' . $editorWrapWidth . '; height:' . $editorWrapHeight . ';">
-                               <textarea id="RTEarea'.$this->TCEform->RTEcounter.'" name="'.htmlspecialchars($PA['itemFormElName']).'" style="'.t3lib_div::deHSCentities(htmlspecialchars($this->RTEdivStyle)).'">'.t3lib_div::formatForTextarea($value).'</textarea>
+                               <div id="pleasewait' . $textAreaId . '" class="pleasewait" style="display: none;" >' . $LANG->getLL('Please wait') . '</div>
+                               <div id="editorWrap' . $textAreaId . '" class="editorWrap" style="width:' . $editorWrapWidth . '; height:' . $editorWrapHeight . ';">
+                               <textarea id="RTEarea' . $textAreaId . '" name="'.htmlspecialchars($PA['itemFormElName']).'" style="'.t3lib_div::deHSCentities(htmlspecialchars($this->RTEdivStyle)).'">'.t3lib_div::formatForTextarea($value).'</textarea>
                                </div>' . ($TYPO3_CONF_VARS['EXTCONF'][$this->ID]['enableDebugMode'] ? '<div id="HTMLAreaLog"></div>' : '') . '
                                ';
                }
@@ -465,7 +469,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                        // Return form item:
                return $item;
        }
-       
+
        /**
         * Add registered plugins to the array of enabled plugins
         *
@@ -507,7 +511,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                }
                $this->pluginEnabledArray = array_diff($this->pluginEnabledArray, $hidePlugins);
        }
-       
+
        /**
         * Set the toolbar config (only in this PHP-Object, not in JS):
         *
@@ -515,7 +519,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
 
        function setToolbar() {
                global $BE_USER;
-               
+
                $this->defaultToolbarOrder = 'bar, blockstylelabel, blockstyle, space, textstylelabel, textstyle, linebreak,
                        bar, formattext, bold,  strong, italic, emphasis, big, small, insertedtext, deletedtext, citation, code, definition, keyboard, monospaced, quotation, sample, variable, bidioverride, strikethrough, subscript, superscript, underline, span,
                        bar, fontstyle, space, fontsize, bar, formatblock, insertparagraphbefore, insertparagraphafter, blockquote,
@@ -523,11 +527,11 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                        bar, orderedlist, unorderedlist, definitionlist, definitionitem, outdent, indent,  bar, lefttoright, righttoleft,
                        bar, textcolor, bgcolor, textindicator,
                        bar, emoticon, insertcharacter, line, link, unlink, image, table,' . (($this->thisConfig['hideTableOperationsInToolbar'] && is_array($this->thisConfig['buttons.']) && is_array($this->thisConfig['buttons.']['toggleborders.']) && $this->thisConfig['buttons.']['toggleborders.']['keepInToolbar']) ? ' toggleborders,': '') . ' user, acronym, bar, findreplace, spellcheck,
-                       bar, chMode, inserttag, removeformat, bar, copy, cut, paste, bar, undo, redo, bar, showhelp, about, linebreak, 
+                       bar, chMode, inserttag, removeformat, bar, copy, cut, paste, bar, undo, redo, bar, showhelp, about, linebreak,
                        ' . ($this->thisConfig['hideTableOperationsInToolbar'] ? '': 'bar, toggleborders,') . ' bar, tableproperties, tablerestyle, bar, rowproperties, rowinsertabove, rowinsertunder, rowdelete, rowsplit, bar,
                        columnproperties, columninsertbefore, columninsertafter, columndelete, columnsplit, bar,
                        cellproperties, cellinsertbefore, cellinsertafter, celldelete, cellsplit, cellmerge';
-               
+
                        // Special toolbar for Mozilla Wamcom on Mac OS 9
                if($this->client['BROWSER'] == 'gecko' && $this->client['VERSION'] == '1.3')  {
                        $this->defaultToolbarOrder = $this->TCEform->docLarge ? 'bar, blockstylelabel, blockstyle, space, textstylelabel, textstyle, linebreak,
@@ -549,7 +553,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                                columnproperties, columninsertbefore, columninsertafter, columndelete, columnsplit, bar,
                                cellproperties, cellinsertbefore, cellinsertafter, celldelete, cellsplit, cellmerge';
                }
-               
+
                        // Additional buttons from registered plugins
                foreach($this->registeredPlugins as $pluginId => $plugin) {
                        if ($this->isPluginEnabled($pluginId)) {
@@ -590,7 +594,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                                $show = array_intersect($show, t3lib_div::trimExplode(',',$RTEkeyList,1));
                        }
                }
-               
+
                        // Hiding buttons of disabled plugins
                $hideButtons = array('space', 'bar', 'linebreak');
                foreach ($this->pluginButton as $pluginId => $buttonList) {
@@ -601,17 +605,17 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                                }
                        }
                }
-               
+
                        // Hiding labels of disabled plugins
                foreach ($this->pluginLabel as $pluginId => $label) {
                        if (!$this->isPluginEnabled($pluginId)) {
                                $hideButtons[] = $label;
                        }
                }
-               
+
                        // Hiding buttons
                $show = array_diff($show, $this->conf_toolbar_hide, t3lib_div::trimExplode(',',$this->thisConfig['hideButtons'],1));
-               
+
                        // Apply toolbar constraints from registered plugins
                foreach ($this->registeredPlugins as $pluginId => $plugin) {
                        if ($this->isPluginEnabled($pluginId) && method_exists($plugin, "applyToolbarConstraints")) {
@@ -624,7 +628,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                foreach ($this->conf_toolbar_show as $buttonId) {
                        if (!in_array($buttonId, $this->toolbarOrderArray)) $this->toolbarOrderArray[] = $buttonId;
                }
-               
+
                        // Getting rid of the buttons for which we have no position
                $show = array_intersect($show, $toolbarOrder);
                $this->toolbar = $show;
@@ -635,7 +639,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
         *
         */
        function setPlugins() {
-               
+
                        // Disabling a plugin that adds buttons if none of its buttons is in the toolbar
                $hidePlugins = array();
                foreach ($this->pluginButton as $pluginId => $buttonList) {
@@ -653,7 +657,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                        }
                }
                $this->pluginEnabledArray = array_diff($this->pluginEnabledArray, $hidePlugins);
-               
+
                        // Hiding labels of disabled plugins
                $hideLabels = array();
                foreach ($this->pluginLabel as $pluginId => $label) {
@@ -662,7 +666,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                        }
                }
                $this->toolbar = array_diff($this->toolbar, $hideLabels);
-               
+
                        // Completing the toolbar converion array for htmlArea
                foreach ($this->registeredPlugins as $pluginId => $plugin) {
                        if ($this->isPluginEnabled($pluginId)) {
@@ -673,7 +677,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
 
        /**
         * Convert the TYPO3 names of buttons into the names for htmlArea RTE
-        * 
+        *
         * @param       string  buttonname (typo3-name)
         * @return      string  buttonname (htmlarea-name)
         */
@@ -705,16 +709,29 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
         */
        function loadJSfiles($RTEcounter) {
                global $TYPO3_CONF_VARS;
-               
+
                $loadJavascriptCode = '
                <script type="text/javascript">
                /*<![CDATA[*/
-                       i=1;
-                       while (document.getElementById("pleasewait" + i)) {
-                               document.getElementById("pleasewait" + i).style.display = "block";
-                               document.getElementById("editorWrap" + i).style.visibility = "hidden";
-                               i++;
-                       };
+                       function rteHtmlAreaGetElementsByClassName(className) {
+                               var allElements = document.getElementsByTagName("*");
+                               var result = new Array();
+
+                               for (var i = 0; i < allElements.length; i++) {
+                                       var c = " " + allElements[i].className + " ";
+                                       if (c.indexOf(" " + className + " ") != -1) {
+                                               result[result.length] = allElements[i];
+                                       }
+                               }
+                               return result;
+                       }
+
+                       wait_elements = rteHtmlAreaGetElementsByClassName("pleasewait");
+                       wrap_elements = rteHtmlAreaGetElementsByClassName("editorWrap");
+                       for (i = 0; i < wait_elements.length; i++) {
+                               wait_elements[i].style.display = "block";
+                               wrap_elements[i].style.visibility = "hidden";
+                       }
                        RTEarea = new Array();
                        RTEarea[0] = new Object();
                        RTEarea[0]["version"] = "' . $TYPO3_CONF_VARS['EXTCONF'][$this->ID]['version'] . '";'
@@ -741,7 +758,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                ';
                return $loadJavascriptCode;
        }
-       
+
        /**
         * Return the inline Javascript code for initializing the RTE
         *
@@ -749,10 +766,10 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
         *
         * @return      string          the inline Javascript code for initializing the RTE
         */
-        
+
        function loadJScode($RTEcounter) {
                global $TYPO3_CONF_VARS;
-               
+
                $loadPluginCode = '';
                foreach ($this->pluginEnabledCumulativeArray[$RTEcounter] as $pluginId) {
                        $extensionKey = is_object($this->registeredPlugins[$pluginId]) ? $this->registeredPlugins[$pluginId]->getExtensionKey() : $this->ID;
@@ -767,10 +784,10 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                /*]]>*/
                ');
        }
-       
+
        /**
         * Return the Javascript code for configuring the RTE
-        * 
+        *
         * @param       integer         $RTEcounter: The index number of the current RTE editing area within the form.
         * @param       string          $table: The table that includes this RTE (optional, necessary for IRRE).
         * @param       string          $uid: The uid of that table that includes this RTE (optional, necessary for IRRE).
@@ -778,88 +795,94 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
         *
         * @return      string          the Javascript code for configuring the RTE
         */
-       function registerRTEinJS($RTEcounter, $table='', $uid='', $field='') {
+       function registerRTEinJS($RTEcounter, $table='', $uid='', $field='', $textAreaId = '') {
                global $TYPO3_CONF_VARS;
-               
+
                $configureRTEInJavascriptString = (!$this->is_FE() ? '' : '
                        ' . '/*<![CDATA[*/') . '
-                       RTEarea['.$RTEcounter.'] = new Object();
-                       RTEarea['.$RTEcounter.'].RTEtsConfigParams = "&RTEtsConfigParams=' . rawurlencode($this->RTEtsConfigParams()) . '";
-                       RTEarea['.$RTEcounter.'].number = '.$RTEcounter.';
-                       RTEarea['.$RTEcounter.'].id = "RTEarea'.$RTEcounter.'";
-                       RTEarea['.$RTEcounter.'].enableWordClean = ' . (trim($this->thisConfig['enableWordClean'])?'true':'false') . ';
-                       RTEarea['.$RTEcounter.']["htmlRemoveComments"] = ' . (trim($this->thisConfig['removeComments'])?'true':'false') . ';
-                       RTEarea['.$RTEcounter.'].disableEnterParagraphs = ' . (trim($this->thisConfig['disableEnterParagraphs'])?'true':'false') . ';
-                       RTEarea['.$RTEcounter.'].disableObjectResizing = ' . (trim($this->thisConfig['disableObjectResizing'])?'true':'false') . ';
-                       RTEarea['.$RTEcounter.']["removeTrailingBR"] = ' . (trim($this->thisConfig['removeTrailingBR'])?'true':'false') . ';
-                       RTEarea['.$RTEcounter.']["useCSS"] = ' . (trim($this->thisConfig['useCSS'])?'true':'false') . ';
-                       RTEarea['.$RTEcounter.']["keepButtonGroupTogether"] = ' . (trim($this->thisConfig['keepButtonGroupTogether'])?'true':'false') . ';
-                       RTEarea['.$RTEcounter.']["disablePCexamples"] = ' . (trim($this->thisConfig['disablePCexamples'])?'true':'false') . ';
-                       RTEarea['.$RTEcounter.']["statusBar"] = ' . (trim($this->thisConfig['showStatusBar'])?'true':'false') . ';
-                       RTEarea['.$RTEcounter.']["showTagFreeClasses"] = ' . (trim($this->thisConfig['showTagFreeClasses'])?'true':'false') . ';
-                       RTEarea['.$RTEcounter.']["useHTTPS"] = ' . ((trim(stristr($this->siteURL, 'https')) || $this->thisConfig['forceHTTPS'])?'true':'false') . ';
-                       RTEarea['.$RTEcounter.']["enableMozillaExtension"] = ' . (($this->client['BROWSER'] == 'gecko' && $TYPO3_CONF_VARS['EXTCONF'][$this->ID]['enableMozillaExtension'])?'true':'false') . ';
-                       RTEarea['.$RTEcounter.']["tceformsNested"] = ' . (is_object($this->TCEform) && method_exists($this->TCEform, 'getDynNestedStack') ? $this->TCEform->getDynNestedStack(true) : '[]') . ';';
+                       editornumber = RTEarea.length;
+                       document.getElementById("pleasewait' . $textAreaId . '").id = "pleasewait" + editornumber;
+                       document.getElementById("editorWrap' . $textAreaId . '").id = "editorWrap" + editornumber;
+                       document.getElementById("RTEarea' . $textAreaId . '").id = "RTEarea" + editornumber;
+                       RTEarea[editornumber] = new Object();
+                       RTEarea[editornumber].RTEtsConfigParams = "&RTEtsConfigParams=' . rawurlencode($this->RTEtsConfigParams()) . '";
+                       RTEarea[editornumber].number = editornumber;
+                       RTEarea[editornumber].deleted = false;
+                       RTEarea[editornumber].textAreaId = "' . $textAreaId . '";
+                       RTEarea[editornumber].id = "RTEarea" + editornumber;
+                       RTEarea[editornumber].enableWordClean = ' . (trim($this->thisConfig['enableWordClean'])?'true':'false') . ';
+                       RTEarea[editornumber]["htmlRemoveComments"] = ' . (trim($this->thisConfig['removeComments'])?'true':'false') . ';
+                       RTEarea[editornumber].disableEnterParagraphs = ' . (trim($this->thisConfig['disableEnterParagraphs'])?'true':'false') . ';
+                       RTEarea[editornumber].disableObjectResizing = ' . (trim($this->thisConfig['disableObjectResizing'])?'true':'false') . ';
+                       RTEarea[editornumber]["removeTrailingBR"] = ' . (trim($this->thisConfig['removeTrailingBR'])?'true':'false') . ';
+                       RTEarea[editornumber]["useCSS"] = ' . (trim($this->thisConfig['useCSS'])?'true':'false') . ';
+                       RTEarea[editornumber]["keepButtonGroupTogether"] = ' . (trim($this->thisConfig['keepButtonGroupTogether'])?'true':'false') . ';
+                       RTEarea[editornumber]["disablePCexamples"] = ' . (trim($this->thisConfig['disablePCexamples'])?'true':'false') . ';
+                       RTEarea[editornumber]["statusBar"] = ' . (trim($this->thisConfig['showStatusBar'])?'true':'false') . ';
+                       RTEarea[editornumber]["showTagFreeClasses"] = ' . (trim($this->thisConfig['showTagFreeClasses'])?'true':'false') . ';
+                       RTEarea[editornumber]["useHTTPS"] = ' . ((trim(stristr($this->siteURL, 'https')) || $this->thisConfig['forceHTTPS'])?'true':'false') . ';
+                       RTEarea[editornumber]["enableMozillaExtension"] = ' . (($this->client['BROWSER'] == 'gecko' && $TYPO3_CONF_VARS['EXTCONF'][$this->ID]['enableMozillaExtension'])?'true':'false') . ';
+                       RTEarea[editornumber]["tceformsNested"] = ' . (is_object($this->TCEform) && method_exists($this->TCEform, 'getDynNestedStack') ? $this->TCEform->getDynNestedStack(true) : '[]') . ';';
 
                        // The following properties apply only to the backend
                if (!$this->is_FE()) {
                        $configureRTEInJavascriptString .= '
-                       RTEarea['.$RTEcounter.'].sys_language_content = "' . $this->contentLanguageUid . '";
-                       RTEarea['.$RTEcounter.'].typo3ContentLanguage = "' . $this->contentTypo3Language . '";
-                       RTEarea['.$RTEcounter.'].typo3ContentCharset = "' . $this->contentCharset . '";
-                       RTEarea['.$RTEcounter.'].userUid = "' . $this->userUid . '";';
+                       RTEarea[editornumber].sys_language_content = "' . $this->contentLanguageUid . '";
+                       RTEarea[editornumber].typo3ContentLanguage = "' . $this->contentTypo3Language . '";
+                       RTEarea[editornumber].typo3ContentCharset = "' . $this->contentCharset . '";
+                       RTEarea[editornumber].userUid = "' . $this->userUid . '";';
                }
-               
+
                        // Setting the plugin flags
                $configureRTEInJavascriptString .= '
-                       RTEarea['.$RTEcounter.'].plugin = new Object();
-                       RTEarea['.$RTEcounter.'].pathToPluginDirectory = new Object();';
+                       RTEarea[editornumber].plugin = new Object();
+                       RTEarea[editornumber].pathToPluginDirectory = new Object();';
                foreach ($this->pluginEnabledArray as $pluginId) {
                        $configureRTEInJavascriptString .= '
-                       RTEarea['.$RTEcounter.'].plugin.'.$pluginId.' = true;';
+                       RTEarea[editornumber].plugin.'.$pluginId.' = true;';
                        if (is_object($this->registeredPlugins[$pluginId])) {
                                $pathToPluginDirectory = $this->registeredPlugins[$pluginId]->getPathToPluginDirectory();
                                if ($pathToPluginDirectory) {
                                        $configureRTEInJavascriptString .= '
-                       RTEarea['.$RTEcounter.'].pathToPluginDirectory.'.$pluginId.' = "' . $pathToPluginDirectory . '";';
+                       RTEarea[editornumber].pathToPluginDirectory.'.$pluginId.' = "' . $pathToPluginDirectory . '";';
                                }
                        }
                }
-               
+
                        // Setting the buttons configuration
                $configureRTEInJavascriptString .= '
-                       RTEarea['.$RTEcounter.'].buttons = new Object();';
+                       RTEarea[editornumber].buttons = new Object();';
                if (is_array($this->thisConfig['buttons.'])) {
                        foreach ($this->thisConfig['buttons.'] as $buttonIndex => $conf) {
                                $button = substr($buttonIndex, 0, -1);
                                if (in_array($button,$this->toolbar)) {
                                        $configureRTEInJavascriptString .= '
-                       RTEarea['.$RTEcounter.'].buttons.'.$button.' = ' . $this->buildNestedJSArray($conf) . ';';
+                       RTEarea[editornumber].buttons.'.$button.' = ' . $this->buildNestedJSArray($conf) . ';';
                                }
                        }
                }
-               
+
                        // Setting the list of tags to be removed if specified in the RTE config
                if (trim($this->thisConfig['removeTags']))  {
                        $configureRTEInJavascriptString .= '
-                       RTEarea['.$RTEcounter.']["htmlRemoveTags"] = /^(' . implode('|', t3lib_div::trimExplode(',', $this->thisConfig['removeTags'], 1)) . ')$/i;';
+                       RTEarea[editornumber]["htmlRemoveTags"] = /^(' . implode('|', t3lib_div::trimExplode(',', $this->thisConfig['removeTags'], 1)) . ')$/i;';
                }
-               
+
                        // Setting the list of tags to be removed with their contents if specified in the RTE config
                if (trim($this->thisConfig['removeTagsAndContents']))  {
                        $configureRTEInJavascriptString .= '
-                       RTEarea['.$RTEcounter.']["htmlRemoveTagsAndContents"] = /^(' . implode('|', t3lib_div::trimExplode(',', $this->thisConfig['removeTagsAndContents'], 1)) . ')$/i;';
+                       RTEarea[editornumber]["htmlRemoveTagsAndContents"] = /^(' . implode('|', t3lib_div::trimExplode(',', $this->thisConfig['removeTagsAndContents'], 1)) . ')$/i;';
                }
-               
+
                        // Process default style configuration
                $configureRTEInJavascriptString .= '
-                       RTEarea['.$RTEcounter.'].defaultPageStyle = "' . $this->hostURL . $this->writeTemporaryFile('', 'defaultPageStyle', 'css', $this->buildStyleSheet()) . '";';
-                       
+                       RTEarea[editornumber].defaultPageStyle = "' . $this->hostURL . $this->writeTemporaryFile('', 'defaultPageStyle', 'css', $this->buildStyleSheet()) . '";';
+
                        // Setting the pageStyle
                $filename = trim($this->thisConfig['contentCSS']) ? trim($this->thisConfig['contentCSS']) : 'EXT:' . $this->ID . '/res/contentcss/default.css';
                $configureRTEInJavascriptString .= '
-                       RTEarea['.$RTEcounter.'].pageStyle = "' . $this->getFullFileName($filename) .'";';
-               
+                       RTEarea[editornumber].pageStyle = "' . $this->getFullFileName($filename) .'";';
+
                        // Process classes configuration
                $classesConfigurationRequired = false;
                foreach ($this->registeredPlugins as $pluginId => $plugin) {
@@ -870,17 +893,17 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                if ($classesConfigurationRequired) {
                        $configureRTEInJavascriptString .= $this->buildJSClassesConfig($RTEcounter);
                }
-               
+
                        // Add Javascript configuration for registered plugins
                foreach ($this->registeredPlugins as $pluginId => $plugin) {
                        if ($this->isPluginEnabled($pluginId)) {
-                               $configureRTEInJavascriptString .= $plugin->buildJavascriptConfiguration($RTEcounter);
+                               $configureRTEInJavascriptString .= $plugin->buildJavascriptConfiguration('editornumber');
                        }
                }
-               
+
                $configureRTEInJavascriptString .= '
-                       RTEarea['.$RTEcounter.'].toolbar = '.$this->getJSToolbarArray().';
-                       HTMLArea.initEditor('.$RTEcounter.');' . (!$this->is_FE() ? '' : '
+                       RTEarea[editornumber].toolbar = '.$this->getJSToolbarArray().';
+                       HTMLArea.initEditor(editornumber);' . (!$this->is_FE() ? '' : '
                        /*]]>*/');
                return $configureRTEInJavascriptString;
        }
@@ -892,21 +915,21 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
         *
         * @return      boolean         true if the plugin can be loaded
         */
-       
-       function isPluginEnabled($pluginId) { 
+
+       function isPluginEnabled($pluginId) {
                return in_array($pluginId, $this->pluginEnabledArray);
        }
-       
+
        /**
         * Build the default content style sheet
         *
         * @return string               Style sheet
         */
        function buildStyleSheet() {
-               
+
                if (!trim($this->thisConfig['ignoreMainStyleOverride'])) {
                        $mainStyle_font = $this->thisConfig['mainStyle_font'] ? $this->thisConfig['mainStyle_font']: 'Verdana,sans-serif';
-                       
+
                        $mainElements = array();
                        $mainElements['P'] = $this->thisConfig['mainStyleOverride_add.']['P'];
                        $elList = explode(',','H1,H2,H3,H4,H5,H6,PRE');
@@ -915,12 +938,12 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                                        $mainElements[$elListName] = $this->thisConfig['mainStyleOverride_add.'][$elListName];
                                }
                        }
-                       
+
                        $addElementCode = '';
                        foreach ($mainElements as $elListName => $elValue) {
                                $addElementCode .= strToLower($elListName) . ' {' . $elValue . '}' . chr(10);
                        }
-                       
+
                        $stylesheet = $this->thisConfig['mainStyleOverride'] ? $this->thisConfig['mainStyleOverride'] : chr(10) .
                                'body.htmlarea-content-body { font-family: ' . $mainStyle_font .
                                        '; font-size: '.($this->thisConfig['mainStyle_size'] ? $this->thisConfig['mainStyle_size'] : '12px') .
@@ -934,7 +957,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                                'ul { ' . $this->thisConfig['mainStyleOverride_add.']['UL'].'}' . chr(10) .
                                'blockquote { ' . $this->thisConfig['mainStyleOverride_add.']['BLOCKQUOTE'].'}' . chr(10) .
                                $addElementCode;
-       
+
                        if (is_array($this->thisConfig['inlineStyle.']))        {
                                $stylesheet .= chr(10) . implode(chr(10), $this->thisConfig['inlineStyle.']) . chr(10);
                        }
@@ -943,7 +966,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                }
                return $stylesheet;
        }
-       
+
        /**
         * Return Javascript configuration of classes
         *
@@ -957,20 +980,20 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                $classesTagConvert = array( 'classesCharacter' => 'span', 'classesParagraph' => 'div', 'classesImage' => 'img', 'classesTable' => 'table', 'classesLinks' => 'a', 'classesTD' => 'td');
                $classesTagArray = t3lib_div::trimExplode(',' , $classesTagList);
                $configureRTEInJavascriptString = '
-                       RTEarea['.$RTEcounter.']["classesTag"] = new Object();';
+                       RTEarea[editornumber]["classesTag"] = new Object();';
                foreach ($classesTagArray as $classesTagName) {
                        $HTMLAreaJSClasses = ($this->thisConfig[$classesTagName])?('"' . $this->cleanList($this->thisConfig[$classesTagName]) . '";'):'null;';
                        $configureRTEInJavascriptString .= '
-                       RTEarea['.$RTEcounter.']["classesTag"]["'. $classesTagConvert[$classesTagName] .'"] = '. $HTMLAreaJSClasses;
+                       RTEarea[editornumber]["classesTag"]["'. $classesTagConvert[$classesTagName] .'"] = '. $HTMLAreaJSClasses;
                }
-               
+
                        // Include JS arrays of configured classes
                $configureRTEInJavascriptString .= '
-                       RTEarea['.$RTEcounter.']["classesUrl"] = "' . $this->hostURL . $this->writeTemporaryFile('', 'classes_'.$LANG->lang, 'js', $this->buildJSClassesArray()) . '";';
-               
+                       RTEarea[editornumber]["classesUrl"] = "' . $this->hostURL . $this->writeTemporaryFile('', 'classes_'.$LANG->lang, 'js', $this->buildJSClassesArray()) . '";';
+
                return $configureRTEInJavascriptString;
        }
-       
+
        /**
         * Return JS arrays of classes labels and noShow flags
         *
@@ -978,13 +1001,13 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
         */
        function buildJSClassesArray() {
                global $TSFE, $LANG, $TYPO3_CONF_VARS;
-               
+
                if ($this->is_FE()) {
                        $RTEProperties = $this->RTEsetup;
                } else {
                        $RTEProperties = $this->RTEsetup['properties'];
                }
-               
+
                $linebreak = $TYPO3_CONF_VARS['EXTCONF'][$this->ID]['enableCompressedScripts'] ? '' : chr(10);
                $index = 0;
                $indexNoShow = 0;
@@ -994,7 +1017,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                $JSClassesNoShowArray = 'HTMLArea.classesNoShow = { ' . $linebreak;
                $JSClassesAlternatingArray = 'HTMLArea.classesAlternating = { ' . $linebreak;
                $JSClassesXORArray = 'HTMLArea.classesXOR = { ' . $linebreak;
-               
+
                        // Scanning the list of classes if specified in the RTE config
                if (is_array($RTEProperties['classes.']))  {
                        foreach ($RTEProperties['classes.'] as $className => $conf) {
@@ -1030,10 +1053,10 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                $JSClassesNoShowArray .= '};' . $linebreak;
                $JSClassesAlternatingArray .= '};' . $linebreak;
                $JSClassesXORArray .= '};' . $linebreak;
-               
+
                return $JSClassesLabelsArray . $JSClassesValuesArray . $JSClassesNoShowArray . $JSClassesAlternatingArray . $JSClassesXORArray;
        }
-       
+
        /**
         * Translate Page TS Config array in JS nested array definition
         *
@@ -1084,7 +1107,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                                                                        }
                                                                        $configureRTEInJavascriptString .= '}';
                                                                } else {
-                                                                       $configureRTEInJavascriptString .= '"'.$property2.'" : '.($conf3?'"'.$conf3.'"':'false');                                                                                               
+                                                                       $configureRTEInJavascriptString .= '"'.$property2.'" : '.($conf3?'"'.$conf3.'"':'false');
                                                                }
                                                                $indexProperty1++;
                                                        }
@@ -1104,7 +1127,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                $configureRTEInJavascriptString .= '}';
                return $configureRTEInJavascriptString;
        }
-       
+
        /**
         * Return a Javascript localization array for htmlArea RTE
         *
@@ -1112,7 +1135,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
         */
        function buildJSMainLangArray() {
                global $TSFE, $LANG, $TYPO3_CONF_VARS;
-               
+
                $linebreak = $TYPO3_CONF_VARS['EXTCONF'][$this->ID]['enableCompressedScripts'] ? '' : chr(10);
                $JSLanguageArray .= 'var HTMLArea_langArray = new Object();' . $linebreak;
                $JSLanguageArray .= 'HTMLArea_langArray = { ' . $linebreak;
@@ -1139,7 +1162,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                $JSLanguageArray .= ' };' . chr(10);
                return $JSLanguageArray;
        }
-       
+
        /**
         * Writes contents in a file in typo3temp/rtehtmlarea directory and returns the file name
         *
@@ -1152,7 +1175,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
         */
        public function writeTemporaryFile($sourceFileName='', $label, $fileExtension='js', $contents='') {
                global $TYPO3_CONF_VARS;
-               
+
                if ($sourceFileName) {
                        $output = '';
                        $source = t3lib_div::getFileAbsFileName($sourceFileName);
@@ -1175,7 +1198,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                }
                return ($this->thisConfig['forceHTTPS']?$this->siteURL:$this->httpTypo3Path) . $relativeFilename;
        }
-       
+
        /**
         * Return a file name containing the main JS language array for HTMLArea
         *
@@ -1183,8 +1206,8 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
         *
         * @return      string          filename
         */
-        
-       function buildJSMainLangFile($RTEcounter) { 
+
+       function buildJSMainLangFile($RTEcounter) {
                $contents = $this->buildJSMainLangArray() . chr(10);
                foreach ($this->pluginEnabledCumulativeArray[$RTEcounter] as $pluginId) {
                        $contents .= $this->buildJSLangArray($pluginId) . chr(10);
@@ -1199,7 +1222,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
         *
         * @return      string          Javascript localization array
         */
-        
+
        function buildJSLangArray($plugin) {
                global $LANG, $TYPO3_CONF_VARS;
 
@@ -1217,7 +1240,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                } else {
                        $LOCAL_LANG[$this->language] = $LOCAL_LANG['default'];
                }
-       
+
                $JSLanguageArray .= 'var ' . $plugin . '_langArray = new Object();' . $linebreak;
                $JSLanguageArray .= $plugin . '_langArray = {' . $linebreak;
                $index = 0;
@@ -1225,7 +1248,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                        $JSLanguageArray .=  (($index++)?',':'') . '"' . $labelKey . '":"' . str_replace('"', '\"', $labelValue) . '"' . $linebreak;
                }
                $JSLanguageArray .= ' };' . chr(10);
-               
+
                return $JSLanguageArray;
        }
 
@@ -1289,10 +1312,10 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                $toolbar = $toolbar . ']]';
                return $toolbar;
        }
-       
+
        public function getLLContent($string) {
                global $LANG;
-               
+
                $BE_lang = $LANG->lang;
                $BE_charSet = $LANG->charSet;
                $LANG->lang = $this->contentTypo3Language;
@@ -1302,10 +1325,10 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                $LANG->charSet = $BE_charSet;
                return $LLString;
        }
-       
+
        public function getPageConfigLabel($string,$JScharCode=1) {
                global $LANG, $TSFE, $TYPO3_CONF_VARS;
-               
+
                if ($this->is_FE()) {
                        if (strcmp(substr($string,0,4),'LLL:') && $TYPO3_CONF_VARS['BE']['forceCharset'])       {
                                        // A pure string coming from Page TSConfig must be in forceCharset, otherwise we just don't know..
@@ -1326,7 +1349,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                }
                return $label;
        }
-       
+
        function feJScharCode($str) {
                global $TSFE;
                        // Convert string to UTF-8:
@@ -1335,7 +1358,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                $nArr = $TSFE->csConvObj->utf8_to_numberarray($str);
                return 'String.fromCharCode('.implode(',',$nArr).')';
        }
-       
+
        public function getFullFileName($filename) {
                if (substr($filename,0,4)=='EXT:')      {       // extension
                        list($extKey,$local) = explode('/',substr($filename,4),2);
@@ -1363,27 +1386,56 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
         */
        function setSaveRTE($RTEcounter, $formName, $textareaId) {
                return '
-               editornumber = '.$RTEcounter.';
-               if (RTEarea[editornumber]) {
-                       document.'.$formName.'["'.$textareaId.'"].value = RTEarea[editornumber]["editor"].getHTML();
+               rteFound = false;
+               for (editornumber = 1; editornumber < RTEarea.length; editornumber++) {
+                       if (RTEarea[editornumber].textAreaId == "' . $textareaId . '") {
+                               if (!RTEarea[editornumber].deleted) {
+                                       document.'.$formName.'["'.$textareaId.'"].value = RTEarea[editornumber]["editor"].getHTML();
+                               }
+                               rteFound = true;
+                               break;
+                       }
                }
-               else {
-                       OK=0;
+               if (!rteFound) {
+                       OK = 0;
+               }
+               ';
+       }
+
+       /**
+        * Return the Javascript code for copying the HTML code from the editor into the hidden input field.
+        * This is for submit function of the form.
+        *
+        * @param       integer         $RTEcounter: The index number of the current RTE editing area within the form.
+        * @param       string          $formName: the name of the form
+        * @param       string          $textareaId: the id of the textarea
+        *
+        * @return      string          Javascript code
+        */
+       function setDeleteRTE($RTEcounter, $formName, $textareaId) {
+               return '
+               for (editornumber = 1; editornumber < RTEarea.length; editornumber++) {
+                       if (RTEarea[editornumber].textAreaId == "' . $textareaId . '") {
+                               if (RTEarea[editornumber]) {
+                                       RTEarea[editornumber].deleted = true;
+                               }
+                       }
+                       break;
                }
                ';
        }
-       
+
        /**
         * Return true if we are in the FE, but not in the FE editing feature of BE.
         *
         * @return boolean
         */
-        
+
        function is_FE() {
                global $TSFE;
                return is_object($TSFE) && is_array($this->LOCAL_LANG) && !strstr($this->elementId,'TSFE_EDIT');
        }
-       
+
        /**
         * Client Browser Information
         *
@@ -1395,9 +1447,9 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
 
        function clientInfo($useragent='')      {
                global $TYPO3_CONF_VARS;
-               
+
                if (!$useragent) $useragent=t3lib_div::getIndpEnv('HTTP_USER_AGENT');
-               
+
                $bInfo=array();
                        // Which browser?
                if (strstr($useragent,'Konqueror'))     {
@@ -1466,7 +1518,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
         ***************************/
        /**
         * @return      [type]          ...
-        * @desc 
+        * @desc
         */
 
        function RTEtsConfigParams()    {
@@ -1486,7 +1538,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                }
                return $str;
        }
-       
+
        function filterStyleEl($elValue,$matchList)     {
                $matchParts = t3lib_div::trimExplode(',',$matchList,1);
                $styleParts = explode(';',$elValue);
@@ -1506,7 +1558,7 @@ class tx_rtehtmlarea_base extends t3lib_rteapi {
                }
                return implode('; ',$nStyle);
        }
-       
+
                // Hook on lorem_ipsum extension to insert text into the RTE in wysiwyg mode
        function loremIpsumInsert($params) {
                return "
index 077f633..35ec538 100644 (file)
@@ -75,16 +75,16 @@ class tx_rtehtmlarea_pi2 extends tx_rtehtmlarea_base {
         */
        function drawRTE($parentObject,$table,$field,$row,$PA,$specConf,$thisConfig,$RTEtypeVal,$RTErelPath,$thePidValue) {
                global $TSFE, $TYPO3_CONF_VARS, $TYPO3_DB;
-               
+
                $this->TCEform =& $parentObject;
                $this->client = $this->clientInfo();
                $this->typoVersion = t3lib_div::int_from_ver(TYPO3_version);
-               
+
                /* =======================================
                 * INIT THE EDITOR-SETTINGS
                 * =======================================
                 */
-                
+
                        // first get the http-path to typo3:
                $this->httpTypo3Path = substr( substr( t3lib_div::getIndpEnv('TYPO3_SITE_URL'), strlen( t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST') ) ), 0, -1 );
                if (strlen($this->httpTypo3Path) == 1) {
@@ -98,39 +98,39 @@ class tx_rtehtmlarea_pi2 extends tx_rtehtmlarea_base {
                $this->siteURL = t3lib_div::getIndpEnv('TYPO3_SITE_URL');
                        // Get the host URL
                $this->hostURL = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST');
-               
+
                        // Element ID + pid
                $this->elementId = $PA['itemFormElName'];
                $this->elementParts[0] = $table;
                $this->elementParts[1] = $row['uid'];
                $this->tscPID = $thePidValue;
                $this->thePid = $thePidValue;
-               
+
                        // Record "type" field value:
                $this->typeVal = $RTEtypeVal; // TCA "type" value for record
-               
+
                        // RTE configuration
                $pageTSConfig = $TSFE->getPagesTSconfig();
                if (is_array($pageTSConfig) && is_array($pageTSConfig['RTE.'])) {
                        $this->RTEsetup = $pageTSConfig['RTE.'];
                }
-               
+
                if (is_array($thisConfig) && !empty($thisConfig)) {
                        $this->thisConfig = $thisConfig;
                } else if (is_array($this->RTEsetup['default.']) && is_array($this->RTEsetup['default.']['FE.'])) {
                        $this->thisConfig = $this->RTEsetup['default.']['FE.'];
                }
-               
+
                        // Special configuration (line) and default extras:
                $this->specConf = $specConf;
-               
+
                if ($this->thisConfig['forceHTTPS']) {
                        $this->httpTypo3Path = preg_replace('/^(http|https)/', 'https', $this->httpTypo3Path);
                        $this->extHttpPath = preg_replace('/^(http|https)/', 'https', $this->extHttpPath);
                        $this->siteURL = preg_replace('/^(http|https)/', 'https', $this->siteURL);
                        $this->hostURL = preg_replace('/^(http|https)/', 'https', $this->hostURL);
                }
-               
+
                /* =======================================
                 * LANGUAGES & CHARACTER SETS
                 * =======================================
@@ -142,7 +142,7 @@ class tx_rtehtmlarea_pi2 extends tx_rtehtmlarea_base {
                if ($this->language == 'default' || !$this->language)   {
                        $this->language = 'en';
                }
-               
+
                $this->contentISOLanguage = $TYPO3_CONF_VARS['EXTCONF']['rtehtmlarea']['defaultDictionary'];
                $this->contentLanguageUid = ($row['sys_language_uid'] > 0) ? $row['sys_language_uid'] : 0;
                if (t3lib_extMgm::isLoaded('static_info_tables')) {
@@ -171,27 +171,27 @@ class tx_rtehtmlarea_pi2 extends tx_rtehtmlarea_base {
                                }
                        }
                }
-               
+
                $this->contentISOLanguage = $this->contentISOLanguage?$this->contentISOLanguage:$this->language;
                $this->contentTypo3Language = $this->contentTypo3Language?$this->contentTypo3Language:$TSFE->lang;
                if ($this->contentTypo3Language == 'default') {
                        $this->contentTypo3Language = 'en';
                }
-               
+
                        // Character set
                $this->charset = $TSFE->renderCharset;
                $this->OutputCharset  = $TSFE->metaCharset ? $TSFE->metaCharset : $TSFE->renderCharset;
-               
+
                        // Set the charset of the content
                $this->contentCharset = $TSFE->csConvObj->charSetArray[$this->contentTypo3Language];
                $this->contentCharset = $this->contentCharset ? $this->contentCharset : 'iso-8859-1';
                $this->contentCharset = trim($TSFE->config['config']['metaCharset']) ? trim($TSFE->config['config']['metaCharset']) : $this->contentCharset;
-               
+
                /* =======================================
                 * TOOLBAR CONFIGURATION
                 * =======================================
                 */
-               
+
                        // htmlArea plugins list
                $this->pluginEnabledArray = t3lib_div::trimExplode(',', $this->pluginList, 1);
                $this->enableRegisteredPlugins();
@@ -202,31 +202,31 @@ class tx_rtehtmlarea_pi2 extends tx_rtehtmlarea_base {
                        $this->thisConfig['disableEnterParagraphs'] = 1;
                }
                $this->pluginEnabledArray = array_diff($this->pluginEnabledArray, $hidePlugins);
-               
+
                        // Toolbar
                $this->settoolbar();
-               
+
                        // Check if some plugins need to be disabled
                $this->setPlugins();
-               
+
                        // Merge the list of enabled plugins with the lists from the previous RTE editing areas on the same form
                $this->pluginEnabledCumulativeArray[$this->TCEform->RTEcounter] = $this->pluginEnabledArray;
                if ($this->TCEform->RTEcounter > 1 && isset($this->pluginEnabledCumulativeArray[$this->TCEform->RTEcounter-1]) && is_array($this->pluginEnabledCumulativeArray[$this->TCEform->RTEcounter-1])) {
                        $this->pluginEnabledCumulativeArray[$this->TCEform->RTEcounter] = array_unique(array_values(array_merge($this->pluginEnabledArray,$this->pluginEnabledCumulativeArray[$this->TCEform->RTEcounter-1])));
                }
-               
+
                /* =======================================
                 * SET STYLES
                 * =======================================
                 */
-                
+
                $RTEWidth = 460+($this->TCEform->docLarge ? 150 : 0);
                $RTEHeight = 380;
                $RTEHeightOverride = intval($this->thisConfig['RTEHeightOverride']);
                $RTEHeight = ($RTEHeightOverride > 0) ? $RTEHeightOverride : $RTEHeight;
                $editorWrapWidth = $RTEWidth . 'px';
                $editorWrapHeight = $RTEHeight . 'px';
-               $this->RTEWrapStyle = $this->RTEWrapStyle ? $this->RTEWrapStyle : ($this->RTEdivStyle ? $this->RTEdivStyle : ('height:' . ($RTEHeight+2) . 'px; width:'. ($RTEWidth+2) . 'px;'));               
+               $this->RTEWrapStyle = $this->RTEWrapStyle ? $this->RTEWrapStyle : ($this->RTEdivStyle ? $this->RTEdivStyle : ('height:' . ($RTEHeight+2) . 'px; width:'. ($RTEWidth+2) . 'px;'));
                $this->RTEdivStyle = $this->RTEdivStyle ? $this->RTEdivStyle : 'position:relative; left:0px; top:0px; height:' . $RTEHeight . 'px; width:'.$RTEWidth.'px; border: 1px solid black;';
                $this->toolbar_level_size = $RTEWidth;
 
@@ -262,11 +262,11 @@ class tx_rtehtmlarea_pi2 extends tx_rtehtmlarea_base {
                $this->editedContentCSS = $skinDir . '/htmlarea-edited-content.css';
                $additionalCode_loadCSS .= '
                <link rel="alternate stylesheet" type="text/css" href="' . $this->editedContentCSS . '" />';
-               
+
                        // Main stylesheet
                $additionalCode_loadCSS .= '
                <link rel="stylesheet" type="text/css" href="' . $this->editorCSS . '" />';
-               
+
                        // Additional icons from registered plugins
                foreach ($this->pluginEnabledCumulativeArray[$this->TCEform->RTEcounter] as $pluginId) {
                        if (is_object($this->registeredPlugins[$pluginId])) {
@@ -277,7 +277,7 @@ class tx_rtehtmlarea_pi2 extends tx_rtehtmlarea_base {
                                }
                        }
                }
-               
+
                        // Loading CSS, JavaScript files and code
                $TSFE->additionalHeaderData['htmlArea'] = $additionalCode_loadCSS;
                $this->TCEform->additionalJS_initial = $this->loadJSfiles($this->TCEform->RTEcounter);
@@ -289,34 +289,35 @@ class tx_rtehtmlarea_pi2 extends tx_rtehtmlarea_base {
                 */
                        // Transform value:
                $value = $this->transformContent('rte',$PA['itemFormElValue'],$table,$field,$row,$specConf,$thisConfig,$RTErelPath,$thePidValue);
-               
+
                        // Further content transformation by registered plugins
                foreach ($this->registeredPlugins as $pluginId => $plugin) {
                        if ($this->isPluginEnabled($pluginId) && method_exists($plugin, "transformContent")) {
                                $value = $plugin->transformContent($value);
                        }
                }
-               
+
                        // Register RTE windows:
                $this->TCEform->RTEwindows[] = $PA['itemFormElName'];
-               
+               $textAreaId = htmlspecialchars($PA['itemFormElName']);
+
                        // Register RTE in JS:
-               $this->TCEform->additionalJS_post[] = $this->registerRTEinJS($this->TCEform->RTEcounter);
-               
+               $this->TCEform->additionalJS_post[] = $this->registerRTEinJS($this->TCEform->RTEcounter, $textAreaId);
+
                        // Set the save option for the RTE:
-               $this->TCEform->additionalJS_submit[] = $this->setSaveRTE($this->TCEform->RTEcounter, $this->TCEform->formName, htmlspecialchars($PA['itemFormElName']));
-               
+               $this->TCEform->additionalJS_submit[] = $this->setSaveRTE($this->TCEform->RTEcounter, $this->TCEform->formName, $textAreaId);
+
                        // draw the textarea
                $visibility = 'hidden';
                $item = $this->triggerField($PA['itemFormElName']).'
-                       <div id="pleasewait' . $this->TCEform->RTEcounter . '" class="pleasewait" style="display: none;" >' . $TSFE->csConvObj->conv($TSFE->getLLL('Please wait',$this->LOCAL_LANG), $this->charset, $TSFE->renderCharset) . '</div>
-                       <div id="editorWrap' . $this->TCEform->RTEcounter . '" class="editorWrap" style="'. htmlspecialchars($this->RTEWrapStyle). '">
-                       <textarea id="RTEarea'.$this->TCEform->RTEcounter.'" name="'.htmlspecialchars($PA['itemFormElName']).'" style="'.htmlspecialchars($this->RTEdivStyle).'">'.t3lib_div::formatForTextarea($value).'</textarea>
+                       <div id="pleasewait' . $textAreaId . '" class="pleasewait" style="display: none;" >' . $TSFE->csConvObj->conv($TSFE->getLLL('Please wait',$this->LOCAL_LANG), $this->charset, $TSFE->renderCharset) . '</div>
+                       <div id="editorWrap' . $$textAreaId . '" class="editorWrap" style="'. htmlspecialchars($this->RTEWrapStyle). '">
+                       <textarea id="RTEarea' . $textAreaId . '" name="'.htmlspecialchars($PA['itemFormElName']).'" style="'.htmlspecialchars($this->RTEdivStyle).'">'.t3lib_div::formatForTextarea($value).'</textarea>
                        </div>' . ($TYPO3_CONF_VARS['EXTCONF'][$this->ID]['enableDebugMode'] ? '<div id="HTMLAreaLog"></div>' : '') . '
                        ';
                return $item;
        }
-       
+
        /**
         * Return the JS-Code for copy the HTML-Code from the editor in the hidden input field.
         * This is for submit function from the form.
@@ -329,18 +330,25 @@ class tx_rtehtmlarea_pi2 extends tx_rtehtmlarea_base {
         */
        function setSaveRTE($RTEcounter, $form, $textarea) {
                return '
-               editornumber = '.$RTEcounter.';
-               if (RTEarea[editornumber]) {
-                       fields = document.getElementsByName(\'' . $textarea . '\');
-                       field = fields.item(0);
-                       if(field && field.tagName.toLowerCase() == \'textarea\') field.value = RTEarea[editornumber][\'editor\'].getHTML();
+               rteFound = false;
+               for (editornumber = 1; editornumber < RTEarea.length; editornumber++) {
+                       if (RTEarea[editornumber].textAreaId == "' . $textarea . '") {
+                               if (!RTEarea[editornumber].deleted) {
+                                       fields = document.getElementsByName(\'' . $textarea . '\');
+                                       field = fields.item(0);
+                                       if(field && field.tagName.toLowerCase() == \'textarea\') field.value = RTEarea[editornumber][\'editor\'].getHTML();
+                               }
+                               rteFound = true;
+                               break;
+                       }
                }
-               else {
-                       OK=0;
+               if (!rteFound) {
+                       OK = 0;
                }
                ';
        }
-       
+
+
 }
 
 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/rtehtmlarea/pi2/class.tx_rtehtmlarea_pi2.php'])       {