This commit was manufactured by cvs2svn to create tag
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_tceforms.php
index b2ae2e0..a2852f0 100755 (executable)
@@ -1,22 +1,22 @@
 <?php
 /***************************************************************
 *  Copyright notice
-*  
-*  (c) 1999-2003 Kasper Skårhøj (kasper@typo3.com)
+*
+*  (c) 1999-2004 Kasper Skaarhoj (kasper@typo3.com)
 *  All rights reserved
 *
-*  This script is part of the TYPO3 project. The TYPO3 project is 
+*  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
-* 
+*
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
-*  A copy is found in the textfile GPL.txt and important notices to the license 
+*  A copy is found in the textfile GPL.txt and important notices to the license
 *  from the author is found in LICENSE.txt distributed with these scripts.
 *
-* 
+*
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/
-/** 
+/**
  * Contains TYPO3 Core Form generator - AKA "TCEforms"
  *
- * Revised for TYPO3 3.6 August/2003 by Kasper Skårhøj
+ * $Id$
+ * Revised for TYPO3 3.6 August/2003 by Kasper Skaarhoj
  * XHTML compliant
+ *
+ * @author     Kasper Skaarhoj <kasper@typo3.com>
  */
 /**
  * [CLASS/FUNCTION INDEX of SCRIPT]
  *
  *
  *
- *  193: class t3lib_TCEforms  
- *  286:     function t3lib_TCEforms() 
- *  323:     function initDefaultBEmode()      
+ *  175: class t3lib_TCEforms
+ *  274:     function t3lib_TCEforms()
+ *  306:     function initDefaultBEmode()
  *
  *              SECTION: Rendering the forms, fields etc
- *  366:     function getSoloField($table,$row,$theFieldToReturn)      
- *  405:     function getMainFields($table,$row,$depth=0)      
- *  532:     function getListedFields($table,$row,$list)       
- *  574:     function getPaletteFields($table,$row,$palette,$header='',$itemList='',$collapsedHeader='')       
- *  650:     function getSingleField($table,$field,$row,$altName='',$palette=0,$extra='',$pal=0)       
- *  777:     function getSingleField_SW($table,$field,$row,&$PA)       
+ *  351:     function getSoloField($table,$row,$theFieldToReturn)
+ *  390:     function getMainFields($table,$row,$depth=0)
+ *  517:     function getListedFields($table,$row,$list)
+ *  558:     function getPaletteFields($table,$row,$palette,$header='',$itemList='',$collapsedHeader='')
+ *  634:     function getSingleField($table,$field,$row,$altName='',$palette=0,$extra='',$pal=0)
+ *  762:     function getSingleField_SW($table,$field,$row,&$PA)
  *
  *              SECTION: Rendering of each TCEform field type
- *  848:     function getSingleField_typeInput($table,$field,$row,&$PA)        
- *  900:     function getSingleField_typeText($table,$field,$row,&$PA) 
- *  969:     function getSingleField_typeCheck($table,$field,$row,&$PA)        
- * 1028:     function getSingleField_typeRadio($table,$field,$row,&$PA)        
- * 1058:     function getSingleField_typeSelect($table,$field,$row,&$PA)       
- * 1217:     function getSingleField_typeGroup($table,$field,$row,&$PA)        
- * 1359:     function getSingleField_typeNone($table,$field,$row,&$PA) 
- * 1413:     function getSingleField_typeFlex($table,$field,$row,&$PA) 
- * 1514:     function getSingleField_typeFlex_langMenu($languages,$elName,$selectedLanguage,$multi=1)  
- * 1533:     function getSingleField_typeFlex_sheetMenu($sArr,$elName,$sheetKey)       
- * 1563:     function getSingleField_typeFlex_draw($dataStruct,$editData,$cmdData,$table,$field,$row,&$PA,$formPrefix='',$level=0,$tRows=array())      
- * 1712:     function getSingleField_typeUnknown($table,$field,$row,&$PA)      
- * 1727:     function getSingleField_typeUser($table,$field,$row,&$PA) 
+ *  833:     function getSingleField_typeInput($table,$field,$row,&$PA)
+ *  885:     function getSingleField_typeText($table,$field,$row,&$PA)
+ *  984:     function getSingleField_typeCheck($table,$field,$row,&$PA)
+ * 1043:     function getSingleField_typeRadio($table,$field,$row,&$PA)
+ * 1073:     function getSingleField_typeSelect($table,$field,$row,&$PA)
+ * 1235:     function getSingleField_typeGroup($table,$field,$row,&$PA)
+ * 1389:     function getSingleField_typeNone($table,$field,$row,&$PA)
+ * 1405:     function getSingleField_typeNone_render($config,$itemValue)
+ * 1462:     function getSingleField_typeFlex($table,$field,$row,&$PA)
+ * 1563:     function getSingleField_typeFlex_langMenu($languages,$elName,$selectedLanguage,$multi=1)
+ * 1582:     function getSingleField_typeFlex_sheetMenu($sArr,$elName,$sheetKey)
+ * 1612:     function getSingleField_typeFlex_draw($dataStruct,$editData,$cmdData,$table,$field,$row,&$PA,$formPrefix='',$level=0,$tRows=array())
+ * 1764:     function getSingleField_typeUnknown($table,$field,$row,&$PA)
+ * 1779:     function getSingleField_typeUser($table,$field,$row,&$PA)
  *
  *              SECTION: "Configuration" fetching/processing functions
- * 1759:     function getRTypeNum($table,$row) 
- * 1785:     function rearrange($fields)       
- * 1811:     function getExcludeElements($table,$row,$typeNum) 
- * 1859:     function getFieldsToAdd($table,$row,$typeNum)     
- * 1884:     function mergeFieldsWithAddedFields($fields,$fieldsToAdd) 
- * 1916:     function setTSconfig($table,$row,$field='')       
- * 1938:     function getSpecConfForField($table,$row,$field)  
- * 1958:     function getSpecConfFromString($extraString)    
+ * 1813:     function getRTypeNum($table,$row)
+ * 1839:     function rearrange($fields)
+ * 1865:     function getExcludeElements($table,$row,$typeNum)
+ * 1913:     function getFieldsToAdd($table,$row,$typeNum)
+ * 1938:     function mergeFieldsWithAddedFields($fields,$fieldsToAdd)
+ * 1970:     function setTSconfig($table,$row,$field='')
+ * 1992:     function getSpecConfForField($table,$row,$field)
+ * 2013:     function getSpecConfFromString($extraString, $defaultExtras)
  *
  *              SECTION: Form element helper functions
- * 1990:     function dbFileIcons($fName,$mode,$allowed,$itemArray,$selector='',$params=array(),$onFocus='')   
- * 2099:     function renderWizards($itemKinds,$wizConf,$table,$row,$field,&$PA,$itemName,$specConf,$RTE=0)    
- * 2262:     function getIcon($icon)   
- * 2293:     function wrapOpenPalette($header,$table,$row,$palette,$retFunc=0) 
- * 2317:     function checkBoxParams($itemName,$thisValue,$c,$iCount,$addFunc='')      
- * 2331:     function elName($itemName)        
- * 2342:     function noTitle($str,$wrapParts=array()) 
- * 2351:     function blur()   
- * 2364:     function getSingleHiddenField($table,$field,$row) 
- * 2386:     function formWidth($size=48,$textarea=0) 
- * 2408:     function formWidthText($size=48,$wrap='') 
- * 2423:     function formElStyle($type)       
- * 2441:     function insertDefStyle($type)    
+ * 2045:     function dbFileIcons($fName,$mode,$allowed,$itemArray,$selector='',$params=array(),$onFocus='')
+ * 2177:     function getClipboardElements($allowed,$mode)
+ * 2226:     function getClickMenu($str,$table,$uid='')
+ * 2247:     function renderWizards($itemKinds,$wizConf,$table,$row,$field,&$PA,$itemName,$specConf,$RTE=0)
+ * 2417:     function getIcon($icon)
+ * 2448:     function wrapOpenPalette($header,$table,$row,$palette,$retFunc=0)
+ * 2472:     function checkBoxParams($itemName,$thisValue,$c,$iCount,$addFunc='')
+ * 2486:     function elName($itemName)
+ * 2497:     function noTitle($str,$wrapParts=array())
+ * 2506:     function blur()
+ * 2515:     function thisReturnUrl()
+ * 2528:     function getSingleHiddenField($table,$field,$row)
+ * 2550:     function formWidth($size=48,$textarea=0)
+ * 2572:     function formWidthText($size=48,$wrap='')
+ * 2587:     function formElStyle($type)
+ * 2605:     function insertDefStyle($type)
  *
  *              SECTION: Item-array manipulation functions (check/select/radio)
- * 2472:     function initItemArray($fieldValue)       
- * 2490:     function addItems($items,$iArray) 
- * 2512:     function procItems($items,$iArray,$config,$table,$row,$field)     
- * 2536:     function addSelectOptionsToItemArray($items,$fieldValue,$TSconfig,$field) 
- * 2614:     function addSelectOptionsToItemArray_makeModuleData($value)       
- * 2636:     function foreignTable($items,$fieldValue,$TSconfig,$field,$pFFlag=0)      
+ * 2636:     function initItemArray($fieldValue)
+ * 2654:     function addItems($items,$iArray)
+ * 2676:     function procItems($items,$iArray,$config,$table,$row,$field)
+ * 2700:     function addSelectOptionsToItemArray($items,$fieldValue,$TSconfig,$field)
+ * 2778:     function addSelectOptionsToItemArray_makeModuleData($value)
+ * 2800:     function foreignTable($items,$fieldValue,$TSconfig,$field,$pFFlag=0)
  *
  *              SECTION: Template functions
- * 2714:     function setFancyDesign() 
- * 2741:     function setNewBEDesign() 
- * 2795:     function intoTemplate($inArr,$altTemplate='')     
- * 2815:     function wrapLabels($str) 
- * 2829:     function wrapTotal($c,$rec,$table)        
- * 2842:     function replaceTableWrap($arr,$rec,$table)       
- * 2864:     function wrapBorder(&$out_array,&$out_pointer)    
- * 2885:     function rplColorScheme($inTemplate)      
- * 2898:     function getDivider()     
- * 2908:     function printPalette($palArr)    
- * 2950:     function helpTextIcon($table,$field,$force=0)     
- * 2966:     function helpText($table,$field)  
- * 2988:     function setColorScheme($scheme)  
- * 3002:     function resetSchemes()   
- * 3013:     function storeSchemes()   
- * 3024:     function restoreSchemes() 
+ * 2877:     function setFancyDesign()
+ * 2904:     function setNewBEDesign()
+ * 2958:     function intoTemplate($inArr,$altTemplate='')
+ * 2982:     function addUserTemplateMarkers($marker,$table,$field,$row,&$PA)
+ * 2993:     function wrapLabels($str)
+ * 3006:     function wrapTotal($c,$rec,$table)
+ * 3019:     function replaceTableWrap($arr,$rec,$table)
+ * 3041:     function wrapBorder(&$out_array,&$out_pointer)
+ * 3062:     function rplColorScheme($inTemplate)
+ * 3075:     function getDivider()
+ * 3085:     function printPalette($palArr)
+ * 3127:     function helpTextIcon($table,$field,$force=0)
+ * 3143:     function helpText($table,$field)
+ * 3165:     function setColorScheme($scheme)
+ * 3179:     function resetSchemes()
+ * 3190:     function storeSchemes()
+ * 3201:     function restoreSchemes()
  *
  *              SECTION: JavaScript related functions
- * 3054:     function JStop($formname='forms[0]')      
- * 3087:     function JSbottom($formname='forms[0]')   
- * 3151:     function TBE_EDITOR_loginRefreshed()      
- * 3157:     function TBE_EDITOR_checkLoginTimeout()   
- * 3165:     function TBE_EDITOR_setHiddenContent(RTEcontent,theField) 
- * 3170:     function TBE_EDITOR_fieldChanged_fName(fName,el)  
- * 3182:     function TBE_EDITOR_fieldChanged(table,uid,field,el)      
- * 3220:     function TBE_EDITOR_setOriginalFormFieldValue(theField)   
- * 3227:     function TBE_EDITOR_isFormChanged(noAlert)        
- * 3234:     function TBE_EDITOR_checkAndDoSubmit(sendAlert)   
- * 3240:     function TBE_EDITOR_checkSubmit(sendAlert)        
- * 3264:     function TBE_EDITOR_checkRange(el,lower,upper)    
- * 3272:     function TBE_EDITOR_initRequired()        
- * 3277:     function TBE_EDITOR_setImage(name,imgName)        
- * 3281:     function TBE_EDITOR_submitForm()  
- * 3286:     function typoSetup        ()      
- * 3293:     function typo3FormFieldSet(theField, evallist, is_in, checkbox, checkboxValue)    
- * 3307:     function typo3FormFieldGet(theField, evallist, is_in, checkbox, checkboxValue, checkbox_off, checkSetValue)       
- * 3323:     function TBE_EDITOR_split(theStr1, delim, index) 
- * 3337:     function TBE_EDITOR_palUrl(inData,fieldList,fieldNum,table,uid,isOnFocus) 
- * 3354:     function TBE_EDITOR_curSelected(theField) 
- * 3368:     function TBE_EDITOR_rawurlencode(str,maxlen)      
- * 3379:     function TBE_EDITOR_str_replace(match,replace,string)     
- * 3414:     function dbFileCon($formObj='document.forms[0]')  
- * 3423:     function setFormValueOpenBrowser (mode,params) 
- * 3436:     function setFormValueFromBrowseWin(fName,value,label)     
- * 3462:     function setHiddenFromList(fObjSel,fObjHid)       
- * 3470:     function setFormValueManipulate(fName,type)       
- * 3510:     function setFormValue_getFObj(fName)      
- * 3532:     function printNeededJSFunctions() 
- * 3551:     function printNeededJSFunctions_top()     
+ * 3230:     function JStop()
+ * 3281:     function JSbottom($formname='forms[0]')
+ * 3592:     function dbFileCon($formObj='document.forms[0]')
+ * 3700:     function printNeededJSFunctions()
+ * 3727:     function printNeededJSFunctions_top()
  *
  *              SECTION: Various helper functions
- * 3599:     function getDefaultRecord($table,$pid=0)  
- * 3636:     function getRecordPath($table,$rec)       
- * 3649:     function readPerms()      
- * 3663:     function sL($str) 
- * 3676:     function getLL($str)      
- * 3694:     function isPalettesCollapsed($table,$palette)     
- * 3709:     function isDisplayCondition($displayCond,$row)    
- * 3760:     function getTSCpid($table,$uid,$pid)      
- * 3774:     function doLoadTableDescr($table) 
- * 3786:     function getAvailableLanguages($onlyIsoCoded=1,$setDefault=1)     
+ * 3775:     function getDefaultRecord($table,$pid=0)
+ * 3814:     function getRecordPath($table,$rec)
+ * 3827:     function readPerms()
+ * 3841:     function sL($str)
+ * 3854:     function getLL($str)
+ * 3872:     function isPalettesCollapsed($table,$palette)
+ * 3887:     function isDisplayCondition($displayCond,$row)
+ * 3940:     function getTSCpid($table,$uid,$pid)
+ * 3954:     function doLoadTableDescr($table)
+ * 3966:     function getAvailableLanguages($onlyIsoCoded=1,$setDefault=1)
  *
  *
- * 3829: class t3lib_TCEforms_FE extends t3lib_TCEforms 
- * 3837:     function wrapLabels($str) 
- * 3847:     function printPalette($palArr)    
+ * 4008: class t3lib_TCEforms_FE extends t3lib_TCEforms
+ * 4016:     function wrapLabels($str)
+ * 4026:     function printPalette($palArr)
  *
- * TOTAL FUNCTIONS: 107
+ * TOTAL FUNCTIONS: 86
  * (This index is automatically created/updated by the extension "extdeveval")
  *
  */
 
+
 
 
 
 
 /**
  * 'TCEforms' - Class for creating the backend editing forms.
- * 
- * @author     Kasper Skårhøj <kasper@typo3.com>
+ *
+ * @author     Kasper Skaarhoj <kasper@typo3.com>
  * @coauthor   Rene Fritz <r.fritz@colorcube.de>
  * @package TYPO3
  * @subpackage t3lib
 class t3lib_TCEforms   {
 
                // variables not commented yet.... (do so...)
-       var $helpTextFontTag='<font color="#333333">';
-       var $RTEpath = 'ext/rte/';
-       var $tceFormsEditor=1;
-       var $palFieldArr=array();
-       var $disableWizards=0;
-       var $RTEdivStyle='';
-       var $isPalettedoc=0;
-       var $paletteMargin=1;
+       var $helpTextFontTag = '<font color="#333333">';
+       var $palFieldArr = array();
+       var $disableWizards = 0;
+       var $isPalettedoc = 0;
+       var $paletteMargin = 1;
        var $defStyle = ''; // 'font-family:Verdana;font-size:10px;';
-       var $cachedTSconfig=array();
-       var $cachedTSconfig_fieldLevel=array();
-       var $transformedRow=array();
-       var $extJSCODE='';
-       var $RTEwindows=array();
+       var $cachedTSconfig = array();
+       var $cachedTSconfig_fieldLevel = array();
+       var $transformedRow = array();
+       var $extJSCODE = '';
        var $printNeededJS = array();
        var $hiddenFieldAccum=array();
        var $TBE_EDITOR_fieldChanged_func='';
@@ -218,27 +196,30 @@ class t3lib_TCEforms      {
 
                // EXTERNAL, static
        var $backPath='';                                       // Set this to the 'backPath' pointing back to the typo3 admin directory from the script where this form is displayed.
-       var $doSaveFieldName='';                        // Can be set to point to a field name in the form which will be set to '1' when the form is submitted.
+       var $returnUrl='';                                      // Alternative return URL path (default is t3lib_div::linkThisScript())
+       var $doSaveFieldName='';                        // Can be set to point to a field name in the form which will be set to '1' when the form is submitted with a *save* button. This way the recipient script can determine that the form was submitted for save and not "close" for example.
        var $palettesCollapsed=0;                       // Can be set true/false to whether palettes (secondary options) are in the topframe or in form. True means they are NOT IN-form. So a collapsed palette is one, which is shown in the top frame, not in the page.
-       var $disableRTE=0;                                      // If set, the RTE is disabled.
+       var $disableRTE=0;                                      // If set, the RTE is disabled (from form display, eg. by checkbox in the bottom of the page!)
        var $globalShowHelp=1;                          // If false, then all CSH will be disabled, regardless of settings in $this->edit_showFieldHelp
        var $fieldOrder='';                                     // Overrule the field order set in TCA[types][showitem], eg for tt_content this value, 'bodytext,image', would make first the 'bodytext' field, then the 'image' field (if set for display)... and then the rest in the old order.
        var $doPrintPalette=1;                          // If set to false, palettes will NEVER be rendered.
+       var $clipObj=FALSE;                                     // Set to initialized clipboard object; Then the element browser will offer a link to paste in records from clipboard.
+       var $enableClickMenu=FALSE;                     // Enable click menu on reference icons.
 
        var $form_rowsToStylewidth = 9.58;      // Form field width compensation: Factor from NN4 form field widths to style-aware browsers (like NN6+ and MSIE, with the $CLIENT[FORMSTYLE] value set)
        var $form_largeComp = 1.33;                     // Form field width compensation: Compensation for large documents, doc-tab (editing)
        var $charsPerRow=40;                            // The number of chars expected per row when the height of a text area field is automatically calculated based on the number of characters found in the field content.
        var $maxTextareaWidth=48;                       // The maximum abstract value for textareas
        var $maxInputWidth=48;                          // The maximum abstract value for input fields
+       var $defaultMultipleSelectorStyle='width:250px;';       // Default style for the selector boxes used for multiple items in "select" and "group" types.
+
 
-       
                // INTERNAL, static
        var $prependFormFieldNames = 'data';            // The string to prepend formfield names with.
        var $prependFormFieldNames_file = 'data_files';         // The string to prepend FILE form field names with.
-       var $formName = 'editform';                                     // The name attribute of the form. 
-       var $RTEbgColor= '#F6F2E6';                                     // The background color passed to the RTE
+       var $formName = 'editform';                                     // The name attribute of the form.
+
 
-               
 
                // INTERNAL, dynamic
        var $perms_clause='';                                           // Set by readPerms()  (caching)
@@ -248,7 +229,8 @@ class t3lib_TCEforms        {
        var $clientInfo=array();                                        // Loaded with info about the browser when class is instantiated.
        var $RTEenabled=0;                                                      // True, if RTE is possible for the current user (based on result from BE_USER->isRTE())
        var $RTEenabled_notReasons='';                          // If $this->RTEenabled was false, you can find the reasons listed in this array which is filled with reasons why the RTE could not be loaded)
-               
+       var $RTEcounter = 0;                                            // Counter that is incremented before an RTE is created. Can be used for unique ids etc.
+
        var $colorScheme;                                                       // Contains current color scheme
        var $defColorScheme;                                            // Contains the default color scheme
        var $fieldStyle;                                                        // Contains field style values
@@ -262,7 +244,7 @@ class t3lib_TCEforms        {
        var $sectionWrap='';                                            // Wrapping template code for a section
        var $palFieldTemplateHeader='';                         // Template for palette headers
        var $palFieldTemplate='';                                       // Template for palettes
-       
+
                // INTERNAL, working memory
        var $excludeElements='';                                        // Set to the fields NOT to display, if any.
        var $palettesRendered=array();                          // During rendering of forms this will keep track of which palettes has already been rendered (so they are not rendered twice by mistake)
@@ -272,7 +254,11 @@ class t3lib_TCEforms       {
        var $renderDepth=0;                                                     // Keeps track of the rendering depth of nested records.
        var $savedSchemes=array();                                      // Color scheme buffer.
 
-
+               // Internal, registers for user defined functions etc.
+       var $additionalCode_pre = array();                      // Additional HTML code, printed before the form.
+       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.
 
 
 
@@ -282,27 +268,22 @@ class t3lib_TCEforms      {
 
        /**
         * Constructor function, setting internal variables, loading the styles used.
-        * 
-        * @return      void            
+        *
+        * @return      void
         */
        function t3lib_TCEforms()       {
                global $CLIENT;
-               
-               $this->clientInfo=t3lib_div::clientInfo();
+
+               $this->clientInfo = t3lib_div::clientInfo();
+
                $this->RTEenabled = $GLOBALS['BE_USER']->isRTE();
                if (!$this->RTEenabled) {
-                       $this->RTEenabled_notReasons=
-                               (!t3lib_extMgm::isLoaded('rte') ? "- 'rte' extension is not loaded\n":'').
-                               ($CLIENT['BROWSER']!='msie' ? "- Browser is not MSIE\n":'').
-                               ($CLIENT['SYSTEM']!='win' ? "- Client system is not Windows\n":'').
-                               ($CLIENT['VERSION']<5 ? "- Browser version below 5\n":'').
-                               (!$GLOBALS['BE_USER']->uc['edit_RTE'] ? "- RTE is not enabled for user!\n":'').
-                               (!$GLOBALS['TYPO3_CONF_VARS']['BE']['RTEenabled'] ? '- RTE is not enabled in $TYPO3_CONF_VARS["BE"]["RTEenabled"]'.chr(10):'');
-                       $this->commentMessages[]='RTE NOT ENABLED IN SYSTEM due to:'.chr(10).$this->RTEenabled_notReasons;
-               }
-               
+                       $this->RTEenabled_notReasons = implode(chr(10),$GLOBALS['BE_USER']->RTE_errors);
+                       $this->commentMessages[] = 'RTE NOT ENABLED IN SYSTEM due to:'.chr(10).$this->RTEenabled_notReasons;
+               }
+
                        // Default color scheme
-               $this->defColorScheme=array(
+               $this->defColorScheme = array(
                        $GLOBALS['SOBE']->doc->bgColor, // Background for the field AND palette
                        t3lib_div::modifyHTMLColorAll($GLOBALS['SOBE']->doc->bgColor,-20),      // Background for the field header
                        t3lib_div::modifyHTMLColorAll($GLOBALS['SOBE']->doc->bgColor,-10),      // Background for the palette field header
@@ -312,21 +293,20 @@ class t3lib_TCEforms      {
 
                        // Override / Setting defaults from TBE_STYLES array
                $this->resetSchemes();
-               
+
                        // Setting the current colorScheme to default.
-               $this->defColorScheme=$this->colorScheme;
+               $this->defColorScheme = $this->colorScheme;
        }
-       
+
        /**
         * Initialize various internal variables.
-        * 
-        * @return      void            
+        *
+        * @return      void
         */
        function initDefaultBEmode()    {
                global $BE_USER;
                $this->prependFormFieldNames = 'data';
                $this->formName = 'editform';
-               $this->RTEbgColor = $GLOBALS['SOBE']->doc->bgColor;
                $this->setNewBEDesign();
                $this->docLarge = $BE_USER->uc['edit_wideDocument'] ? 1 : 0;
                $this->edit_showFieldHelp = $BE_USER->uc['edit_showFieldHelp'];
@@ -358,10 +338,10 @@ class t3lib_TCEforms      {
         *******************************************************/
 
        /**
-        * Will return the TCEform element for just a single field from a record. 
+        * Will return the TCEform element for just a single field from a record.
         * The field must be listed in the currently displayed fields (as found in [types][showitem]) for the record.
         * This also means that the $table/$row supplied must be complete so the list of fields to show can be found correctly
-        * 
+        *
         * @param       string          The table name
         * @param       array           The record from the table for which to render a field.
         * @param       string          The field name to return the TCEform element for.
@@ -370,7 +350,7 @@ class t3lib_TCEforms        {
         */
        function getSoloField($table,$row,$theFieldToReturn)    {
                global $TCA;
-               
+
                if ($TCA[$table])       {
                        t3lib_div::loadTCA($table);
                        $typeNum = $this->getRTypeNum($table,$row);
@@ -383,7 +363,7 @@ class t3lib_TCEforms        {
                                        reset($fields);
                                        while(list(,$fieldInfo)=each($fields))  {
                                                $parts = explode(';',$fieldInfo);
-                                               
+
                                                $theField = trim($parts[0]);
                                                if (!in_array($theField,$excludeElements) && !strcmp($theField,$theFieldToReturn))      {
                                                        if ($TCA[$table]['columns'][$theField]) {
@@ -400,10 +380,10 @@ class t3lib_TCEforms      {
        /**
         * Based on the $table and $row of content, this displays the complete TCEform for the record.
         * The input-$row is required to be preprocessed if necessary by eg. the t3lib_transferdata class. For instance the RTE content should be transformed through this class first.
-        * 
+        *
         * @param       string          The table name
         * @param       array           The record from the table for which to render a field.
-        * @param       [type]          $depth: ...
+        * @param       integer         Depth level
         * @return      string          HTML output
         * @see getSoloField()
         */
@@ -412,7 +392,7 @@ class t3lib_TCEforms        {
 
                $this->renderDepth=$depth;
 
-                       // Init vars:           
+                       // Init vars:
                $out_array=array();
                $out_pointer=0;
                $this->palettesRendered=array();
@@ -422,7 +402,7 @@ class t3lib_TCEforms        {
 
                                // Load the full TCA for the table.
                        t3lib_div::loadTCA($table);
-                               
+
                                // Load the description content for the table.
                        if ($this->edit_showFieldHelp || $this->doLoadTableDescr($table))       {
                                $GLOBALS['LANG']->loadSingleTableDescription($table);
@@ -450,7 +430,7 @@ class t3lib_TCEforms        {
                                        while(list(,$fieldInfo)=each($fields))  {
                                                        // Exploding subparts of the field configuration:
                                                $parts = explode(';',$fieldInfo);
-                                               
+
                                                        // Getting the style information out:
                                                $color_style_parts = t3lib_div::trimExplode('-',$parts[4]);
                                                if (strcmp($color_style_parts[0],''))   {
@@ -465,7 +445,7 @@ class t3lib_TCEforms        {
                                                        $this->borderStyle = $GLOBALS['TBE_STYLES']['borderschemes'][intval($color_style_parts[2])];
                                                        if (!isset($this->borderStyle)) $this->borderStyle = $GLOBALS['TBE_STYLES']['borderschemes'][0];
                                                }
-                                               
+
                                                        // Render the field:
                                                $theField = $parts[0];
                                                if (!in_array($theField,$excludeElements))      {
@@ -478,7 +458,7 @@ class t3lib_TCEforms        {
                                                                }
                                                                $sField = $this->getSingleField($table,$theField,$row,$parts[1],0,$parts[3],$parts[2]);
                                                                if ($sField)    $sField.=$sFieldPal;
-                                                               
+
                                                                $out_array[$out_pointer].= $sField;
                                                        } elseif($theField=='--div--')  {
                                                                $out_array[$out_pointer].=$this->getDivider();
@@ -498,7 +478,7 @@ class t3lib_TCEforms        {
                                }
                        }
                }
-               
+
                        // Wrapping a border around it all:
                $this->wrapBorder($out_array,$out_pointer);
 
@@ -525,10 +505,10 @@ class t3lib_TCEforms      {
        }
 
        /**
-        * Will return the TCEform elements for a pre-defined list of fields. 
+        * Will return the TCEform elements for a pre-defined list of fields.
         * Notice that this will STILL use the configuration found in the list [types][showitem] for those fields which are found there. So ideally the list of fields given as argument to this function should also be in the current [types][showitem] list of the record.
         * Used for displaying forms for the frontend edit icons for instance.
-        * 
+        *
         * @param       string          The table name
         * @param       array           The record array.
         * @param       string          Commalist of fields from the table. These will be shown in the specified order in a form.
@@ -544,16 +524,15 @@ class t3lib_TCEforms      {
 
                $out='';
                $types_fieldConfig=t3lib_BEfunc::getTCAtypes($table,$row,1);
-               
+
                $editFieldList=array_unique(t3lib_div::trimExplode(',',$list,1));
-               reset($editFieldList);
-               while(list(,$theFieldC)=each($editFieldList))   {
+               foreach($editFieldList as $theFieldC)   {
                        list($theField,$palFields) = split('\[|\]',$theFieldC);
                        $theField = trim($theField);
                        $palFields = trim($palFields);
                        if ($TCA[$table]['columns'][$theField]) {
                                $parts = t3lib_div::trimExplode(';',$types_fieldConfig[$theField]['origString']);
-                               $sField= $this->getSingleField($table,$theField,$row,$parts[1],0,$parts[3],$parts[2]);
+                               $sField= $this->getSingleField($table,$theField,$row,$parts[1],0,$parts[3],0);  // Don't sent palette pointer - there are no options anyways for a field-list.
                                $out.= $sField;
                        } elseif($theField=='--div--')  {
                                $out.=$this->getDivider();
@@ -567,7 +546,7 @@ class t3lib_TCEforms        {
 
        /**
         * Creates a palette (collection of secondary options).
-        * 
+        *
         * @param       string          The table name
         * @param       array           The row array
         * @param       string          The palette number/pointer
@@ -579,7 +558,7 @@ class t3lib_TCEforms        {
        function getPaletteFields($table,$row,$palette,$header='',$itemList='',$collapsedHeader='')     {
                global $TCA;
                if (!$this->doPrintPalette)     return '';
-               
+
                $out='';
                $palParts=array();
                t3lib_div::loadTCA($table);
@@ -588,7 +567,7 @@ class t3lib_TCEforms        {
                if (!is_array($this->excludeElements))  {
                        $this->excludeElements = $this->getExcludeElements($table,$row,$this->getRTypeNum($table,$row));
                }
-                       
+
                        // Render the palette TCEform elements.
                if ($TCA[$table] && (is_array($TCA[$table]['palettes'][$palette]) || $itemList))        {
                        $itemList = $itemList?$itemList:$TCA[$table]['palettes'][$palette]['showitem'];
@@ -604,7 +583,7 @@ class t3lib_TCEforms        {
                                                if ($this->isPalettesCollapsed($table,$palette))        {
                                                        $this->hiddenFieldListArr[] = $theField;
                                                }
-                                               
+
                                                $part=$this->getSingleField($table,$theField,$row,$parts[1],1,'',$parts[2]);
                                                if (is_array($part))    {
                                                        $palParts[]=$part;
@@ -631,7 +610,7 @@ class t3lib_TCEforms        {
                        // If a palette is collapsed (not shown in form, but in top frame instead) AND a collapse header string is given, then make that string a link to activate the palette.
                if ($this->isPalettesCollapsed($table,$palette) && $collapsedHeader)    {
                        $pC=    $this->intoTemplate(array(
-                                                       'PALETTE' => $this->wrapOpenPalette('<img src="'.$this->backPath.'gfx/options.gif" width="18" height="16" border="0" title="'.htmlspecialchars($this->getLL('l_moreOptions')).'" align="top" alt="" /><strong>'.$collapsedHeader.'</strong>',$table,$row,$palette),
+                                                       'PALETTE' => $this->wrapOpenPalette('<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/options.gif','width="18" height="16"').' border="0" title="'.htmlspecialchars($this->getLL('l_moreOptions')).'" align="top" alt="" /><strong>'.$collapsedHeader.'</strong>',$table,$row,$palette),
                                                ),
                                                $this->palFieldTemplate
                                        );
@@ -639,10 +618,10 @@ class t3lib_TCEforms      {
                }
                return $out;
        }
-       
+
        /**
         * Returns the form HTML code for a database table field.
-        * 
+        *
         * @param       string          The table name
         * @param       string          The field name
         * @param       array           The record to edit from the database table.
@@ -655,56 +634,55 @@ class t3lib_TCEforms      {
        function getSingleField($table,$field,$row,$altName='',$palette=0,$extra='',$pal=0)     {
                global $TCA,$BE_USER;
 
-               $out='';
-               $PA=array();
-               $PA['altName']=$altName;
+               $out = '';
+               $PA = array();
+               $PA['altName'] = $altName;
                $PA['palette'] = $palette;
                $PA['extra'] = $extra;
                $PA['pal'] = $pal;
-        
+
                        // Make sure to load full $TCA array for the table:
                t3lib_div::loadTCA($table);
 
                        // Get the TCA configuration for the current field:
                $PA['fieldConf'] = $TCA[$table]['columns'][$field];
 
-               
                        // Now, check if this field is configured and editable (according to excludefields + other configuration)
                if (    is_array($PA['fieldConf']) &&
-                               (!$PA['fieldConf']['exclude'] || $BE_USER->check('non_exclude_fields',$table.':'.$field)) && 
+                               (!$PA['fieldConf']['exclude'] || $BE_USER->check('non_exclude_fields',$table.':'.$field)) &&
                                $PA['fieldConf']['config']['type']!='passthrough' &&
-                               ($this->RTEenabled || !$PA['fieldConf']['config']['showIfRTE']) && 
+                               ($this->RTEenabled || !$PA['fieldConf']['config']['showIfRTE']) &&
                                (!$PA['fieldConf']['displayCond'] || $this->isDisplayCondition($PA['fieldConf']['displayCond'],$row))
                        )       {
 
-                               // Fetching the TSconfig for the current table/field. This includes the $row which means that 
+                               // Fetching the TSconfig for the current table/field. This includes the $row which means that
                        $PA['fieldTSConfig'] = $this->setTSconfig($table,$row,$field);
 
                                // If the field is NOT disabled from TSconfig (which it could have been) then render it
                        if (!$PA['fieldTSConfig']['disabled'])  {
-                                       
+
                                        // Init variables:
                                $PA['itemFormElName']=$this->prependFormFieldNames.'['.$table.']['.$row['uid'].']['.$field.']';         // Form field name
                                $PA['itemFormElName_file']=$this->prependFormFieldNames_file.'['.$table.']['.$row['uid'].']['.$field.']';       // Form field name, in case of file uploads
                                $PA['itemFormElValue']=$row[$field];            // The value to show in the form field.
-                               
+
                                        // Create a JavaScript code line which will ask the user to save/update the form due to changing the element. This is used for eg. "type" fields and others configured with "requestUpdate"
                                if (
                                                (($TCA[$table]['ctrl']['type'] && !strcmp($field,$TCA[$table]['ctrl']['type'])) ||
                                                ($TCA[$table]['ctrl']['requestUpdate'] && t3lib_div::inList($TCA[$table]['ctrl']['requestUpdate'],$field)))
                                                && !$BE_USER->uc['noOnChangeAlertInTypeFields'])        {
-                                       $alertMsgOnChange="if (confirm(".$GLOBALS['LANG']->JScharCode($this->getLL('m_onChangeAlert')).") && TBE_EDITOR_checkSubmit(-1)){TBE_EDITOR_submitForm()};";
+                                       $alertMsgOnChange = 'if (confirm('.$GLOBALS['LANG']->JScharCode($this->getLL('m_onChangeAlert')).') && TBE_EDITOR_checkSubmit(-1)){ TBE_EDITOR_submitForm() };';
                                } else {$alertMsgOnChange='';}
-                               
+
                                        // Render as a hidden field?
                                if (in_array($field,$this->hiddenFieldListArr)) {
                                        $this->hiddenFieldAccum[]='<input type="hidden" name="'.$PA['itemFormElName'].'" value="'.htmlspecialchars($PA['itemFormElValue']).'" />';
                                } else {        // Render as a normal field:
-                               
+
                                                // If the field is NOT a palette field, then we might create an icon which links to a palette for the field, if one exists.
                                        if (!$PA['palette'])    {
                                                if ($PA['pal'] && $this->isPalettesCollapsed($table,$PA['pal']))        {
-                                                       list($thePalIcon,$palJSfunc) = $this->wrapOpenPalette('<img src="'.$this->backPath.'gfx/options.gif" width="18" height="16" border="0" title="'.htmlspecialchars($this->getLL('l_moreOptions')).'" alt="" />',$table,$row,$PA['pal'],1);
+                                                       list($thePalIcon,$palJSfunc) = $this->wrapOpenPalette('<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/options.gif','width="18" height="16"').' border="0" title="'.htmlspecialchars($this->getLL('l_moreOptions')).'" alt="" />',$table,$row,$PA['pal'],1);
                                                } else {
                                                        $thePalIcon = '';
                                                        $palJSfunc = '';
@@ -712,7 +690,7 @@ class t3lib_TCEforms        {
                                        }
                                                // onFocus attribute to add to the field:
                                        $PA['onFocus'] = ($palJSfunc && !$BE_USER->uc['dontShowPalettesOnFocusInAB']) ? ' onfocus="'.htmlspecialchars($palJSfunc).'"' : '';
-                                       
+
                                                // Find item
                                        $item='';
                                        $PA['label'] = $PA['altName'] ? $PA['altName'] : $PA['fieldConf']['label'];
@@ -721,7 +699,7 @@ class t3lib_TCEforms        {
                                        $PA['fieldChangeFunc']=array();
                                        $PA['fieldChangeFunc']['TBE_EDITOR_fieldChanged'] = "TBE_EDITOR_fieldChanged('".$table."','".$row['uid']."','".$field."','".$PA['itemFormElName']."');";
                                        $PA['fieldChangeFunc']['alert']=$alertMsgOnChange;
-                                       
+
                                                // Based on the type of the item, call a render function:
                                        $item = $this->getSingleField_SW($table,$field,$row,$PA);
 
@@ -729,7 +707,7 @@ class t3lib_TCEforms        {
                                        $PA['label'] = t3lib_div::deHSCentities(htmlspecialchars($PA['label']));
                                        if (t3lib_div::testInt($row['uid']) && $PA['fieldTSConfig']['linkTitleToSelf']) {
                                                $lTTS_url = $this->backPath.'alt_doc.php?edit['.$table.']['.$row['uid'].']=edit&columnsOnly='.$field.
-                                                                       ($PA['fieldTSConfig']['linkTitleToSelf.']['returnUrl']?'&returnUrl='.rawurlencode(t3lib_div::linkThisScript()):'');
+                                                                       ($PA['fieldTSConfig']['linkTitleToSelf.']['returnUrl']?'&returnUrl='.rawurlencode($this->thisReturnUrl()):'');
                                                $PA['label'] = '<a href="'.htmlspecialchars($lTTS_url).'">'.$PA['label'].'</a>';
                                        }
 
@@ -772,7 +750,7 @@ class t3lib_TCEforms        {
 
        /**
         * Rendering a single item for the form
-        * 
+        *
         * @param       string          Table name of record
         * @param       string          Fieldname to render
         * @param       array           The record
@@ -814,7 +792,7 @@ class t3lib_TCEforms        {
                                $item = $this->getSingleField_typeUnknown($table,$field,$row,$PA);
                        break;
                }
-               
+
                return $item;
        }
 
@@ -837,15 +815,15 @@ class t3lib_TCEforms      {
 
 
        /**********************************************************
-        * 
+        *
         * Rendering of each TCEform field type
-        * 
+        *
         ************************************************************/
 
        /**
         * Generation of TCEform elements of the type "input"
         * This will render a single-line input form field, possibly with various control/validation features
-        * 
+        *
         * @param       string          The table name of the record
         * @param       string          The field name which this element is supposed to edit
         * @param       array           The record data array where the value(s) for the field can be found
@@ -858,7 +836,7 @@ class t3lib_TCEforms        {
 
                $config = $PA['fieldConf']['config'];
 #              $specConf = $this->getSpecConfForField($table,$row,$field);
-               $specConf = $this->getSpecConfFromString($PA['extra']);
+               $specConf = $this->getSpecConfFromString($PA['extra'], $PA['fieldConf']['defaultExtras']);
                $size = t3lib_div::intInRange($config['size']?$config['size']:30,5,$this->maxInputWidth);
                $evalList = t3lib_div::trimExplode(',',$config['eval'],1);
 
@@ -871,7 +849,7 @@ class t3lib_TCEforms        {
                                // Setting default "click-checkbox" values for eval types "date" and "datetime":
                        $nextMidNight = mktime(0,0,0)+1*3600*24;
                        $checkSetValue = in_array('date',$evalList) ? $nextMidNight : '';
-                       $checkSetValue = in_array('datetime',$evalList) ? $nextMidNight+12*3600 : $checkSetValue;
+                       $checkSetValue = in_array('datetime',$evalList) ? time() : $checkSetValue;
 
                        $cOnClick = 'typo3FormFieldGet('.$paramsList.',1,\''.$checkSetValue.'\');'.implode('',$PA['fieldChangeFunc']);
                        $item.='<input type="checkbox" name="'.$PA['itemFormElName'].'_cb" onclick="'.htmlspecialchars($cOnClick).'" />';
@@ -883,11 +861,11 @@ class t3lib_TCEforms      {
                $item.='<input type="text" name="'.$PA['itemFormElName'].'_hr" value=""'.$this->formWidth($size).' maxlength="'.$mLgd.'" onchange="'.htmlspecialchars($iOnChange).'"'.$PA['onFocus'].' />';     // This is the EDITABLE form field.
                $item.='<input type="hidden" name="'.$PA['itemFormElName'].'" value="'.htmlspecialchars($PA['itemFormElValue']).'" />';                 // This is the ACTUAL form field - values from the EDITABLE field must be transferred to this field which is the one that is written to the database.
                $this->extJSCODE.='typo3FormFieldSet('.$paramsList.');';
-                       
+
                        // Creating an alternative item without the JavaScript handlers.
-               $altItem='<input type="hidden" name="'.$PA['itemFormElName'].'_hr" value="" />';
-               $altItem.='<input type="hidden" name="'.$PA['itemFormElName'].'" value="'.htmlspecialchars($PA['itemFormElValue']).'" />';
-                       
+               $altItem = '<input type="hidden" name="'.$PA['itemFormElName'].'_hr" value="" />';
+               $altItem.= '<input type="hidden" name="'.$PA['itemFormElName'].'" value="'.htmlspecialchars($PA['itemFormElValue']).'" />';
+
                        // Wrap a wizard around the item?
                $item= $this->renderWizards(array($item,$altItem),$config['wizards'],$table,$row,$field,$PA,$PA['itemFormElName'].'_hr',$specConf);
 
@@ -897,7 +875,7 @@ class t3lib_TCEforms        {
        /**
         * Generation of TCEform elements of the type "text"
         * This will render a <textarea> OR RTE area form field, possibly with various control/validation features
-        * 
+        *
         * @param       string          The table name of the record
         * @param       string          The field name which this element is supposed to edit
         * @param       array           The record data array where the value(s) for the field can be found
@@ -905,68 +883,98 @@ class t3lib_TCEforms      {
         * @return      string          The HTML code for the TCEform field
         */
        function getSingleField_typeText($table,$field,$row,&$PA)       {
+
+                       // Init config:
                $config = $PA['fieldConf']['config'];
-               $cols = t3lib_div::intInRange($config['cols']?$config['cols']:30,5,$this->maxTextareaWidth);
-               $origRows = $rows = t3lib_div::intInRange($config['rows']?$config['rows']:5,1,20);
-               if (strlen($PA['itemFormElValue'])>$this->charsPerRow*2)        {
+
+                       // Setting columns number:
+               $cols = t3lib_div::intInRange($config['cols'] ? $config['cols'] : 30, 5, $this->maxTextareaWidth);
+
+                       // Setting number of rows:
+               $origRows = $rows = t3lib_div::intInRange($config['rows'] ? $config['rows'] : 5, 1, 20);
+               if (strlen($PA['itemFormElValue']) > $this->charsPerRow*2)      {
                        $cols = $this->maxTextareaWidth;
-                       $rows = t3lib_div::intInRange(round(strlen($PA['itemFormElValue'])/$this->charsPerRow),count(explode(chr(10),$PA['itemFormElValue'])),20);
-                       if ($rows<$origRows)    $rows=$origRows;
+                       $rows = t3lib_div::intInRange(round(strlen($PA['itemFormElValue'])/$this->charsPerRow), count(explode(chr(10),$PA['itemFormElValue'])), 20);
+                       if ($rows<$origRows)    $rows = $origRows;
                }
-               $RTEwasLoaded=0;
-               $RTEwouldHaveBeenLoaded=0;
 
-               $specConf = $this->getSpecConfFromString($PA['extra']);
-               if ($this->RTEenabled) {        // If RTE is generally enabled (TYPO3_CONF_VARS and user settings)
-                       $RTEWidth = 460+($this->docLarge ? 150 : 0);
-                       $p=t3lib_BEfunc::getSpecConfParametersFromArray($specConf['rte_transform']['parameters']);
-                       if (isset($specConf['richtext']) && (!$p['flag'] || !$row[$p['flag']])) {       // If the field is configured for RTE and if any flag-field is not set to disable it.
+                       // Init RTE vars:
+               $RTEwasLoaded = 0;                              // Set true, if the RTE is loaded; If not a normal textarea is shown.
+               $RTEwouldHaveBeenLoaded = 0;    // Set true, if the RTE would have been loaded if it wasn't for the disable-RTE flag in the bottom of the page...
+
+                       // "Extra" configuration; Returns configuration for the field based on settings found in the "types" fieldlist. Traditionally, this is where RTE configuration has been found.
+               $specConf = $this->getSpecConfFromString($PA['extra'], $PA['fieldConf']['defaultExtras']);
 
-                               list($tscPID,$thePidValue)=$this->getTSCpid($table,$row['uid'],$row['pid']);
+                       // Setting up the altItem form field, which is a hidden field containing the value
+               $altItem = '<input type="hidden" name="'.htmlspecialchars($PA['itemFormElName']).'" value="'.htmlspecialchars($PA['itemFormElValue']).'" />';
 
-                               if ($thePidValue>=0)    {       // If the pid-value is not negative (that is, a pid could NOT be fetched)
+                       // If RTE is generally enabled (TYPO3_CONF_VARS and user settings)
+               if ($this->RTEenabled) {
+                       $p = t3lib_BEfunc::getSpecConfParametersFromArray($specConf['rte_transform']['parameters']);
+                       if (isset($specConf['richtext']) && (!$p['flag'] || !$row[$p['flag']])) {       // If the field is configured for RTE and if any flag-field is not set to disable it.
+                               list($tscPID,$thePidValue) = $this->getTSCpid($table,$row['uid'],$row['pid']);
+
+                                       // If the pid-value is not negative (that is, a pid could NOT be fetched)
+                               if ($thePidValue >= 0)  {
                                        $RTEsetup = $GLOBALS['BE_USER']->getTSConfig('RTE',t3lib_BEfunc::getPagesTSconfig($tscPID));
                                        $RTEtypeVal = t3lib_BEfunc::getTCAtypeValue($table,$row);
                                        $thisConfig = t3lib_BEfunc::RTEsetup($RTEsetup['properties'],$table,$field,$RTEtypeVal);
+
                                        if (!$thisConfig['disabled'])   {
                                                if (!$this->disableRTE) {
-                                                       $RTEdivStyle = $this->RTEdivStyle ? $this->RTEdivStyle : 'position:relative; left:0px; top:0px; height:380; width:'.$RTEWidth.';border:solid 0px;';
-                                                       $rteURL = $this->backPath.$this->RTEpath.'rte.php?elementId='.$PA['itemFormElName'].'&pid='.$row['pid'].'&typeVal='.rawurlencode($RTEtypeVal).'&bgColor='.rawurlencode($this->colorScheme[0]).'&sC='.rawurlencode($PA['extra']).($this->tceFormsEditor?'&TCEformsEdit=1':'').'&formName='.rawurlencode($this->formName);
-                                                       $item.='<input type="hidden" name="'.$PA['itemFormElName'].'" value="'.htmlspecialchars($PA['itemFormElValue']).'" />';
-                                                       $item.='<div id="cdiv'.count($this->RTEwindows).'" style="'.htmlspecialchars($RTEdivStyle).'">';
-                                                       $item.='<iframe src="'.htmlspecialchars($rteURL).'" id="'.$PA['itemFormElName'].'_RTE" style="visibility: visible; position: absolute; left: 0px; top: 0px; height:100%; width:100%"></iframe>';
-                                                       $item.='</div>';
-
-                                                       $altItem='<input type="hidden" name="'.$PA['itemFormElName'].'" value="'.htmlspecialchars($PA['itemFormElValue']).'" />';
-                                                       $item=$this->renderWizards(array($item,$altItem),$config['wizards'],$table,$row,$field,$PA,$PA['itemFormElName'],$specConf,1);
-                                                       $this->RTEwindows[]=$PA['itemFormElName'];
-                                                       $RTEwasLoaded=1;
+                                                       $this->RTEcounter++;
+
+                                                               // Find alternative relative path for RTE images/links:
+                                                       $eFile = t3lib_parsehtml_proc::evalWriteFile($specConf['static_write'], $row);
+                                                       $RTErelPath = is_array($eFile) ? dirname($eFile['relEditFile']) : '';
+
+                                                               // Get RTE object, draw form and set flag:
+                                                       $RTEobj = &t3lib_BEfunc::RTEgetObj();
+                                                       $item = $RTEobj->drawRTE($this,$table,$field,$row,$PA,$specConf,$thisConfig,$RTEtypeVal,$RTErelPath,$thePidValue);
+
+                                                               // Wizard:
+                                                       $item = $this->renderWizards(array($item,$altItem),$config['wizards'],$table,$row,$field,$PA,$PA['itemFormElName'],$specConf,1);
+
+                                                       $RTEwasLoaded = 1;
                                                } else {
-                                                       $RTEwouldHaveBeenLoaded=1;
-                                                       $this->commentMessages[]=$PA['itemFormElName'].': RTE is disabled by the on-page RTE-flag (probably you can enable it by the check-box in the bottom of this page!)';
+                                                       $RTEwouldHaveBeenLoaded = 1;
+                                                       $this->commentMessages[] = $PA['itemFormElName'].': RTE is disabled by the on-page RTE-flag (probably you can enable it by the check-box in the bottom of this page!)';
                                                }
-                                       } else $this->commentMessages[]=$PA['itemFormElName'].': RTE is disabled by the Page TSconfig, "RTE"-key (eg. by RTE.default.disabled=0 or such)';
-                               } else $this->commentMessages[]=$PA['itemFormElName'].': PID value could NOT be fetched. Rare error, normally with new records.';
+                                       } else $this->commentMessages[] = $PA['itemFormElName'].': RTE is disabled by the Page TSconfig, "RTE"-key (eg. by RTE.default.disabled=0 or such)';
+                               } else $this->commentMessages[] = $PA['itemFormElName'].': PID value could NOT be fetched. Rare error, normally with new records.';
+                       } else {
+                               if (!isset($specConf['richtext']))      $this->commentMessages[] = $PA['itemFormElName'].': RTE was not configured for this field in TCA-types';
+                               if (!(!$p['flag'] || !$row[$p['flag']]))         $this->commentMessages[] = $PA['itemFormElName'].': Field-flag ('.$PA['flag'].') has been set to disable RTE!';
+                       }
+               }
+
+                       // Display ordinary field if RTE was not loaded.
+               if (!$RTEwasLoaded) {
+                       if ($specConf['rte_only'])      {       // Show message, if no RTE (field can only be edited with RTE!)
+                               $item = '<p><em>'.htmlspecialchars($this->getLL('l_noRTEfound')).'</em></p>';
                        } else {
-                               if (!isset($specConf['richtext']))      $this->commentMessages[]=$PA['itemFormElName'].': RTE was not configured for this field in TCA-types';
-                               if (!(!$p['flag'] || !$row[$p['flag']]))         $this->commentMessages[]=$PA['itemFormElName'].': Field-flag ('.$PA['flag'].') has been set to disable RTE!';
+                               if ($specConf['nowrap'])        {
+                                       $wrap = 'off';
+                               } else {
+                                       $wrap = ($config['wrap'] ? $config['wrap'] : 'virtual');
+                               }
+                               $iOnChange = implode('',$PA['fieldChangeFunc']);
+                               $item.= '
+                                                       <textarea name="'.$PA['itemFormElName'].'"'.$this->formWidthText($cols,$wrap).' rows="'.$rows.'" wrap="'.$wrap.'" onchange="'.htmlspecialchars($iOnChange).'"'.$PA['onFocus'].'>'.
+                                                       t3lib_div::formatForTextarea($PA['itemFormElValue']).
+                                                       '</textarea>';
+                               $item = $this->renderWizards(array($item,$altItem),$config['wizards'],$table,$row,$field,$PA,$PA['itemFormElName'],$specConf,$RTEwouldHaveBeenLoaded);
                        }
                }
-               if (!$RTEwasLoaded) {   // Display ordinary field if RTE was not loaded.
-                       if (strstr($PA['extra'],'nowrap'))      $wrap='off'; else $wrap=($config['wrap']?$config['wrap']:'virtual');
-                       $iOnChange = implode('',$PA['fieldChangeFunc']);
-                       $item.='<textarea name="'.$PA['itemFormElName'].'"'.$this->formWidthText($cols,$wrap).' rows="'.$rows.'" wrap="'.$wrap.'" onchange="'.htmlspecialchars($iOnChange).'"'.$PA['onFocus'].'>'.t3lib_div::formatForTextarea($PA['itemFormElValue']).'</textarea>';
-                       $altItem='<input type="hidden" name="'.$PA['itemFormElName'].'" value="'.htmlspecialchars($PA['itemFormElValue']).'" />';
-                       $item=$this->renderWizards(array($item,$altItem),$config['wizards'],$table,$row,$field,$PA,$PA['itemFormElName'],$specConf,$RTEwouldHaveBeenLoaded);
-               }       
 
+                       // Return field HTML:
                return $item;
        }
 
        /**
         * Generation of TCEform elements of the type "check"
         * This will render a check-box OR an array of checkboxes
-        * 
+        *
         * @param       string          The table name of the record
         * @param       string          The field name which this element is supposed to edit
         * @param       array           The record data array where the value(s) for the field can be found
@@ -990,7 +998,7 @@ class t3lib_TCEforms        {
                        $item.= '<table border="0" cellspacing="0" cellpadding="0">';
                        for ($c=0;$c<count($selItems);$c++) {
                                $p = $selItems[$c];
-                               if(!($c%$cols)) {$item.='<tr>';}
+                               if(!($c%$cols)) { $item.='<tr>'; }
                                $cBP = $this->checkBoxParams($PA['itemFormElName'],$thisValue,$c,count($selItems),implode('',$PA['fieldChangeFunc']));
                                $cBName = $PA['itemFormElName'].'_'.$c;
                                $item.= '<td nowrap="nowrap">'.
@@ -1004,7 +1012,7 @@ class t3lib_TCEforms      {
                                for ($c=0;$c<$rest;$c++) {
                                        $item.= '<td></td>';
                                }
-                               if ($c>0)       {$item.= '</tr>';}
+                               if ($c>0)       { $item.= '</tr>'; }
                        }
                        $item.= '</table>';
                } else {
@@ -1017,7 +1025,7 @@ class t3lib_TCEforms      {
                                                htmlspecialchars($p[0]);
                        }
                }
-               $item.='<input type="hidden" name="'.$PA['itemFormElName'].'" value="'.htmlspecialchars($thisValue).'" />';     
+               $item.= '<input type="hidden" name="'.$PA['itemFormElName'].'" value="'.htmlspecialchars($thisValue).'" />';
 
                return $item;
        }
@@ -1025,7 +1033,7 @@ class t3lib_TCEforms      {
        /**
         * Generation of TCEform elements of the type "radio"
         * This will render a series of radio buttons.
-        * 
+        *
         * @param       string          The table name of the record
         * @param       string          The field name which this element is supposed to edit
         * @param       array           The record data array where the value(s) for the field can be found
@@ -1044,7 +1052,7 @@ class t3lib_TCEforms      {
                        $p = $selItems[$c];
                        $rOnClick = implode('',$PA['fieldChangeFunc']);
                        $rChecked = (!strcmp($p[1],$PA['itemFormElValue'])?' checked="checked"':'');
-                       $item.= '<input type="radio"'.$this->insertDefStyle('radio').' name="'.$PA['itemFormElName'].'" value="'.htmlspecialchars($p[1]).'" onclick="'.$rOnClick.'"'.$rChecked.$PA['onFocus'].' />'.
+                       $item.= '<input type="radio"'.$this->insertDefStyle('radio').' name="'.$PA['itemFormElName'].'" value="'.htmlspecialchars($p[1]).'" onclick="'.htmlspecialchars($rOnClick).'"'.$rChecked.$PA['onFocus'].' />'.
                                        htmlspecialchars($p[0]).
                                        '<br />';
                }
@@ -1055,7 +1063,7 @@ class t3lib_TCEforms      {
        /**
         * Generation of TCEform elements of the type "select"
         * This will render a selector box element, or possibly a special construction with two selector boxes. That depends on configuration.
-        * 
+        *
         * @param       string          The table name of the record
         * @param       string          The field name which this element is supposed to edit
         * @param       array           The record data array where the value(s) for the field can be found
@@ -1072,25 +1080,24 @@ class t3lib_TCEforms    {
                $selItems = $this->addItems($selItems,$PA['fieldTSConfig']['addItems.']);
                if ($config['itemsProcFunc']) $selItems = $this->procItems($selItems,$PA['fieldTSConfig']['itemsProcFunc.'],$config,$table,$row,$field);
 
-                       // Possibly remove some items:          
+                       // Possibly remove some items:
                $removeItems=t3lib_div::trimExplode(',',$PA['fieldTSConfig']['removeItems'],1);
-               reset($selItems);
-               while(list($tk,$p)=each($selItems))     {
+               foreach($selItems as $tk => $p) {
                        if (in_array($p[1],$removeItems))       {
                                unset($selItems[$tk]);
                        } else if (isset($PA['fieldTSConfig']['altLabels.'][$p[1]])) {
                                $selItems[$tk][0]=$this->sL($PA['fieldTSConfig']['altLabels.'][$p[1]]);
                        }
                }
-               
+
                        // Creating the label for the "No Matching Value" entry.
                $nMV_label = isset($PA['fieldTSConfig']['noMatchingValue_label']) ? $this->sL($PA['fieldTSConfig']['noMatchingValue_label']) : '[ '.sprintf($this->getLL('l_noMatchingValue'),$PA['itemFormElValue']).' ]';
-               
+
                        // Prepare some values:
                $maxitems = intval($config['maxitems']);
                $minitems = intval($config['minitems']);
                $size = intval($config['size']);
-               
+
                        // If a SINGLE selector box...
                if ($maxitems<=1)       {
                        $c=0;
@@ -1099,7 +1106,7 @@ class t3lib_TCEforms      {
                        $opt=array();
                        $selicons=array();
                        $onlySelectedIconShown=0;
-                       
+
                        if ($config['suppress_icons']=='IF_VALUE_FALSE')        {
                                $suppressIcons = !$PA['itemFormElValue'] ? 1 : 0;
                        } elseif ($config['suppress_icons']=='ONLY_SELECTED')   {
@@ -1108,7 +1115,7 @@ class t3lib_TCEforms      {
                        } elseif ($config['suppress_icons'])    {
                                $suppressIcons = 1;
                        } else $suppressIcons = 0;
-                       
+
                                // Traverse the Array of selector box items:
                        foreach($selItems as $p)        {
                                $sM = (!strcmp($PA['itemFormElValue'],$p[1])?' selected="selected"':'');
@@ -1134,7 +1141,7 @@ class t3lib_TCEforms      {
                        }
                        $sOnChange = 'if (this.options[this.selectedIndex].value==\'--div--\') {this.selectedIndex='.$sI.';} '.implode('',$PA['fieldChangeFunc']);
                        $item.= '<input type="hidden" name="'.$PA['itemFormElName'].'_selIconVal" value="'.htmlspecialchars($sI).'" />';        // MUST be inserted before the selector - else is the value of the hiddenfield here mysteriously submitted...
-                       $item.= '<select name="'.$PA['itemFormElName'].'"'.$this->insertDefStyle('select').($size?' size="'.$size.'"':'').' onchange="'.$sOnChange.'"'.$PA['onFocus'].'>';
+                       $item.= '<select name="'.$PA['itemFormElName'].'"'.$this->insertDefStyle('select').($size?' size="'.$size.'"':'').' onchange="'.htmlspecialchars($sOnChange).'"'.$PA['onFocus'].'>';
                        $item.= implode('',$opt);
                        $item.= '</select>';
 
@@ -1164,35 +1171,41 @@ class t3lib_TCEforms    {
                        $maxitems = t3lib_div::intInRange($config['maxitems'],0);
                        if (!$maxitems) $maxitems=100000;
                        $minitems = t3lib_div::intInRange($config['minitems'],0);
-                       
+
                                // Register the required number of elements:
                        $this->requiredElements[$PA['itemFormElName']] = array($minitems,$maxitems,'imgName'=>$table.'_'.$row['uid'].'_'.$field);
 
                        $sOnChange = 'setFormValueFromBrowseWin(\''.$PA['itemFormElName'].'\',this.options[this.selectedIndex].value,this.options[this.selectedIndex].text); '.implode('',$PA['fieldChangeFunc']);
 
-                               // Put together the select form with selected elements:
-                       $thumbnails='<select style="width:200 px;" name="'.$PA['itemFormElName'].'_sel"'.$this->insertDefStyle('select').($size?' size="'.$size.'"':'').' onchange="'.htmlspecialchars($sOnChange).'"'.$PA['onFocus'].'>';
-                       foreach($selItems as $p)        {
-                               $thumbnails.= '<option value="'.htmlspecialchars($p[1]).'">'.htmlspecialchars($p[0]).'</option>';
-                       }
-                       $thumbnails.= '</select>';
-
                                // Perform modification of the selected items array:
                        $itemArray = t3lib_div::trimExplode(',',$PA['itemFormElValue'],1);
                        foreach($itemArray as $tk => $tv) {
-                               $tvP=explode('|',$tv,2);
+                               $tvP = explode('|',$tv,2);
                                if (in_array($tvP[0],$removeItems) && !$PA['fieldTSConfig']['disableNoMatchingValueElement'])   {
-                                       $tvP[1]=rawurlencode($nMV_label);
+                                       $tvP[1] = rawurlencode($nMV_label);
                                } elseif (isset($PA['fieldTSConfig']['altLabels.'][$tvP[0]])) {
-                                       $tvP[1]=rawurlencode($this->sL($PA['fieldTSConfig']['altLabels.'][$tvP[0]]));
+                                       $tvP[1] = rawurlencode($this->sL($PA['fieldTSConfig']['altLabels.'][$tvP[0]]));
+                               } else {
+                                       $tvP[1] = rawurlencode($this->sL(rawurldecode($tvP[1])));
                                }
                                $itemArray[$tk]=implode('|',$tvP);
                        }
-                       
+
+                               // Put together the select form with selected elements:
+                       $selector_itemListStyle = isset($config['itemListStyle']) ? ' style="'.htmlspecialchars($config['itemListStyle']).'"' : ' style="'.$this->defaultMultipleSelectorStyle.'"';
+                       $size = $config['autoSizeMax'] ? t3lib_div::intInRange(count($itemArray)+1,t3lib_div::intInRange($size,1),$config['autoSizeMax']) : $size;
+                       $thumbnails = '<select name="'.$PA['itemFormElName'].'_sel"'.$this->insertDefStyle('select').($size?' size="'.$size.'"':'').' onchange="'.htmlspecialchars($sOnChange).'"'.$PA['onFocus'].$selector_itemListStyle.'>';
+                       foreach($selItems as $p)        {
+                               $thumbnails.= '<option value="'.htmlspecialchars($p[1]).'">'.htmlspecialchars($p[0]).'</option>';
+                       }
+                       $thumbnails.= '</select>';
+
                        $params=array(
                                'size' => $size,
                                'autoSizeMax' => t3lib_div::intInRange($config['autoSizeMax'],0),
+                               'style' => isset($config['selectedListStyle']) ? ' style="'.htmlspecialchars($config['selectedListStyle']).'"' : ' style="'.$this->defaultMultipleSelectorStyle.'"',
                                'dontShowMoveIcons' => ($maxitems<=1),
+                               'maxitems' => $maxitems,
                                'info' => '',
                                'headers' => array(
                                        'selector' => $this->getLL('l_selected').':<br />',
@@ -1205,8 +1218,8 @@ class t3lib_TCEforms      {
                }
 
                        // Wizards:
-               $altItem='<input type="hidden" name="'.$PA['itemFormElName'].'" value="'.htmlspecialchars($PA['itemFormElValue']).'" />';
-               $item = $this->renderWizards(array($item,$altItem),$config['wizards'],$table,$row,$field,$PA,$PA['itemFormElName'],$specConf);  
+               $altItem = '<input type="hidden" name="'.$PA['itemFormElName'].'" value="'.htmlspecialchars($PA['itemFormElValue']).'" />';
+               $item = $this->renderWizards(array($item,$altItem),$config['wizards'],$table,$row,$field,$PA,$PA['itemFormElName'],$specConf);
 
                return $item;
        }
@@ -1214,7 +1227,7 @@ class t3lib_TCEforms      {
        /**
         * Generation of TCEform elements of the type "group"
         * This will render a selectorbox into which elements from either the file system or database can be inserted. Relations.
-        * 
+        *
         * @param       string          The table name of the record
         * @param       string          The field name which this element is supposed to edit
         * @param       array           The record data array where the value(s) for the field can be found
@@ -1236,119 +1249,131 @@ class t3lib_TCEforms  {
                $item.= '<input type="hidden" name="'.$PA['itemFormElName'].'_mul" value="'.($config['multiple']?1:0).'" />';
                $this->requiredElements[$PA['itemFormElName']] = array($minitems,$maxitems,'imgName'=>$table.'_'.$row['uid'].'_'.$field);
                $info='';
-               
-                       // If the element is of the internal type "file":
-               if ($config['internal_type']=='file')   {
-
-                               // Creating string showing allowed types:
-                       $tempFT = t3lib_div::trimExplode(',',$allowed,1);
-                       reset($tempFT);
-                       if (!count($tempFT))    {$info.='*';}
-                       while(list(,$ext)=each($tempFT))        {
-                               if ($ext)       {
-                                       $info.=strtoupper($ext).' ';
-                               }
-                       }
-                               // Creating string, showing disallowed types:
-                       $tempFT_dis = t3lib_div::trimExplode(',',$disallowed,1);
-                       reset($tempFT_dis);
-                       if (count($tempFT_dis)) {$info.='<br />';}
-                       while(list(,$ext)=each($tempFT_dis))    {
-                               if ($ext)       {
-                                       $info.='-'.strtoupper($ext).' ';
+
+                       // Acting according to either "file" or "db" type:
+               switch((string)$config['internal_type'])        {
+                       case 'file':    // If the element is of the internal type "file":
+
+                                       // Creating string showing allowed types:
+                               $tempFT = t3lib_div::trimExplode(',',$allowed,1);
+                               if (!count($tempFT))    {$info.='*';}
+                               foreach($tempFT as $ext)        {
+                                       if ($ext)       {
+                                               $info.=strtoupper($ext).' ';
+                                       }
                                }
-                       }
-                               
-                               // Making the array of file items:
-                       $itemArray=t3lib_div::trimExplode(',',$PA['itemFormElValue'],1);
-
-                               // Showing thumbnails:
-                       $thumbsnail='';
-                       if ($show_thumbs)       {
-                               reset($itemArray);
-                               $imgs=array();
-                               while(list(,$imgRead)=each($itemArray)) {
-                                       $imgP = explode('|',$imgRead);
-
-                                       $rowCopy=array();
-                                       $rowCopy[$field] = $imgP[0];
-                                       $imgs[]= '<nobr>'.t3lib_BEfunc::thumbCode($rowCopy,$table,$field,$this->backPath,'thumbs.php',$config['uploadfolder'],0,' align="middle"').$imgP[0].'</nobr>';
+                                       // Creating string, showing disallowed types:
+                               $tempFT_dis = t3lib_div::trimExplode(',',$disallowed,1);
+                               if (count($tempFT_dis)) {$info.='<br />';}
+                               foreach($tempFT_dis as $ext)    {
+                                       if ($ext)       {
+                                               $info.='-'.strtoupper($ext).' ';
+                                       }
                                }
-                               $thumbsnail = implode('<br />',$imgs);
-                       }
 
-                               // Creating the element:
-                       $params=array(
-                               'size' => $size,
-                               'dontShowMoveIcons' => ($maxitems<=1),
-                               'autoSizeMax' => t3lib_div::intInRange($config['autoSizeMax'],0),
-                               'info' => $info,
-                               'thumbnails' => $thumbsnail
-                       );
-                       $item.= $this->dbFileIcons($PA['itemFormElName'],'file',implode(',',$tempFT),$itemArray,'',$params,$PA['onFocus']);
+                                       // Making the array of file items:
+                               $itemArray = t3lib_div::trimExplode(',',$PA['itemFormElValue'],1);
 
-                               // Adding the upload field:
-                       if ($this->edit_docModuleUpload)        $item.='<input type="file" name="'.$PA['itemFormElName_file'].'"'.$this->formWidth().' />';
-               }
-               
-                       // If the element is of the internal type "db":
-               if ($config['internal_type']=='db')     {
+                                       // Showing thumbnails:
+                               $thumbsnail = '';
+                               if ($show_thumbs)       {
+                                       $imgs = array();
+                                       foreach($itemArray as $imgRead) {
+                                               $imgP = explode('|',$imgRead);
 
-                               // Creating string showing allowed types:
-                       $tempFT = t3lib_div::trimExplode(',',$allowed,1);
-                       if (!strcmp(trim($tempFT[0]),'*'))      {
-                               $info.='<nobr>&nbsp;&nbsp;&nbsp;&nbsp;'.
-                                               htmlspecialchars($this->getLL('l_allTables')).
-                                               '</nobr><br />';
-                       } else {
-                               while(list(,$theT)=each($tempFT))       {
-                                       if ($theT)      {
-                                               $info.='<nobr>&nbsp;&nbsp;&nbsp;&nbsp;'.
-                                                               '<img src="'.$this->backPath.t3lib_iconWorks::getIcon($theT).'" width="18" height="16" align="top" alt="" /> '.
-                                                               htmlspecialchars($this->sL($GLOBALS['TCA'][$theT]['ctrl']['title'])).
-                                                               '</nobr><br />';
+                                               $rowCopy = array();
+                                               $rowCopy[$field] = $imgP[0];
+
+                                                       // Icon + clickmenu:
+                                               $absFilePath = t3lib_div::getFileAbsFileName($config['uploadfolder'].'/'.$imgP[0]);
+
+                                               $fI = pathinfo($imgP[0]);
+                                               $fileIcon = t3lib_BEfunc::getFileIcon(strtolower($fI['extension']));
+                                               $fileIcon = '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/fileicons/'.$fileIcon,'width="18" height="16"').' class="absmiddle" title="'.htmlspecialchars($fI['basename'].($absFilePath ? ' ('.t3lib_div::formatSize(filesize($absFilePath)).'bytes)' : ' - FILE NOT FOUND!')).'" alt="" />';
+
+                                               $imgs[] = '<span class="nobr">'.t3lib_BEfunc::thumbCode($rowCopy,$table,$field,$this->backPath,'thumbs.php',$config['uploadfolder'],0,' align="middle"').
+                                                                       ($absFilePath ? $this->getClickMenu($fileIcon, $absFilePath) : $fileIcon).
+                                                                       $imgP[0].
+                                                                       '</span>';
                                        }
+                                       $thumbsnail = implode('<br />',$imgs);
                                }
-                       }
 
-                       $perms_clause = $GLOBALS['BE_USER']->getPagePermsClause(1);
-                       $itemArray=array();
-                       $imgs=array();
+                                       // Creating the element:
+                               $params = array(
+                                       'size' => $size,
+                                       'dontShowMoveIcons' => ($maxitems<=1),
+                                       'autoSizeMax' => t3lib_div::intInRange($config['autoSizeMax'],0),
+                                       'maxitems' => $maxitems,
+                                       'style' => isset($config['selectedListStyle']) ? ' style="'.htmlspecialchars($config['selectedListStyle']).'"' : ' style="'.$this->defaultMultipleSelectorStyle.'"',
+                                       'info' => $info,
+                                       'thumbnails' => $thumbsnail
+                               );
+                               $item.= $this->dbFileIcons($PA['itemFormElName'],'file',implode(',',$tempFT),$itemArray,'',$params,$PA['onFocus']);
+
+                                       // Adding the upload field:
+                               if ($this->edit_docModuleUpload)        $item.='<input type="file" name="'.$PA['itemFormElName_file'].'"'.$this->formWidth().' size="60" />';
+                       break;
+                       case 'db':      // If the element is of the internal type "db":
+
+                                       // Creating string showing allowed types:
+                               $tempFT = t3lib_div::trimExplode(',',$allowed,1);
+                               if (!strcmp(trim($tempFT[0]),'*'))      {
+                                       $info.='<span class="nobr">&nbsp;&nbsp;&nbsp;&nbsp;'.
+                                                       htmlspecialchars($this->getLL('l_allTables')).
+                                                       '</span><br />';
+                               } else {
+                                       while(list(,$theT)=each($tempFT))       {
+                                               if ($theT)      {
+                                                       $info.='<span class="nobr">&nbsp;&nbsp;&nbsp;&nbsp;'.
+                                                                       t3lib_iconWorks::getIconImage($theT,array(),$this->backPath,'align="top"').
+                                                                       htmlspecialchars($this->sL($GLOBALS['TCA'][$theT]['ctrl']['title'])).
+                                                                       '</span><br />';
+                                               }
+                                       }
+                               }
 
-                               // Thumbnails:                  
-                       $temp_itemArray = t3lib_div::trimExplode(',',$PA['itemFormElValue'],1);
-                       foreach($temp_itemArray as $dbRead)     {
-                               $recordParts = explode('|',$dbRead);
-                               list($this_table,$this_uid) = t3lib_BEfunc::splitTable_Uid($recordParts[0]);
-                               $itemArray[] = array('table'=>$this_table, 'id'=>$this_uid);
+                               $perms_clause = $GLOBALS['BE_USER']->getPagePermsClause(1);
+                               $itemArray = array();
+                               $imgs = array();
+
+                                       // Thumbnails:
+                               $temp_itemArray = t3lib_div::trimExplode(',',$PA['itemFormElValue'],1);
+                               foreach($temp_itemArray as $dbRead)     {
+                                       $recordParts = explode('|',$dbRead);
+                                       list($this_table,$this_uid) = t3lib_BEfunc::splitTable_Uid($recordParts[0]);
+                                       $itemArray[] = array('table'=>$this_table, 'id'=>$this_uid);
+                                       if ($show_thumbs)       {
+                                               $rr = t3lib_BEfunc::getRecord($this_table,$this_uid);
+                                               $imgs[] = '<span class="nobr">'.
+                                                               $this->getClickMenu(t3lib_iconWorks::getIconImage($this_table,$rr,$this->backPath,'align="top" title="'.htmlspecialchars(t3lib_BEfunc::getRecordPath($rr['pid'],$perms_clause,15)).'"'),$this_table, $this_uid).
+                                                               '&nbsp;'.
+                                                               $this->noTitle($rr[$GLOBALS['TCA'][$this_table]['ctrl']['label']],array('<em>','</em>')).
+                                                               '</span>';
+                                       }
+                               }
+                               $thumbsnail='';
                                if ($show_thumbs)       {
-                                       $rr = t3lib_BEfunc::getRecord($this_table,$this_uid);
-                                       $imgs[]='<nobr>'.
-                                                       t3lib_iconWorks::getIconImage($this_table,$rr,$this->backPath,'align="top" title="'.htmlspecialchars(t3lib_BEfunc::getRecordPath($rr['pid'],$perms_clause,15)).'"').
-                                                       '&nbsp;'.
-                                                       $this->noTitle($rr[$GLOBALS['TCA'][$this_table]['ctrl']['label']],array('<em>','</em>')).
-                                                       '</nobr>';
+                                       $thumbsnail = implode('<br />',$imgs);
                                }
-                       }
-                       $thumbsnail='';
-                       if ($show_thumbs)       {
-                               $thumbsnail = implode('<br />',$imgs);
-                       }
 
-                               // Creating the element:
-                       $params=array(
-                               'size' => $size,
-                               'dontShowMoveIcons' => ($maxitems<=1),
-                               'autoSizeMax' => t3lib_div::intInRange($config['autoSizeMax'],0),
-                               'info' => $info,
-                               'thumbnails' => $thumbsnail
-                       );
-                       $item.= $this->dbFileIcons($PA['itemFormElName'],'db',implode(',',$tempFT),$itemArray,'',$params,$PA['onFocus']);
+                                       // Creating the element:
+                               $params = array(
+                                       'size' => $size,
+                                       'dontShowMoveIcons' => ($maxitems<=1),
+                                       'autoSizeMax' => t3lib_div::intInRange($config['autoSizeMax'],0),
+                                       'maxitems' => $maxitems,
+                                       'style' => isset($config['selectedListStyle']) ? ' style="'.htmlspecialchars($config['selectedListStyle']).'"' : ' style="'.$this->defaultMultipleSelectorStyle.'"',
+                                       'info' => $info,
+                                       'thumbnails' => $thumbsnail
+                               );
+                               $item.= $this->dbFileIcons($PA['itemFormElName'],'db',implode(',',$tempFT),$itemArray,'',$params,$PA['onFocus']);
+                       break;
                }
 
                        // Wizards:
-               $altItem='<input type="hidden" name="'.$PA['itemFormElName'].'" value="'.htmlspecialchars($PA['itemFormElValue']).'" />';
-               $item = $this->renderWizards(array($item,$altItem),$config['wizards'],$table,$row,$field,$PA,$PA['itemFormElName'],$specConf);  
+               $altItem = '<input type="hidden" name="'.$PA['itemFormElName'].'" value="'.htmlspecialchars($PA['itemFormElValue']).'" />';
+               $item = $this->renderWizards(array($item,$altItem),$config['wizards'],$table,$row,$field,$PA,$PA['itemFormElName'],$specConf);
 
                return $item;
        }
@@ -1356,7 +1381,7 @@ class t3lib_TCEforms      {
        /**
         * Generation of TCEform elements of the type "none"
         * This will render a non-editable display of the content of the field.
-        * 
+        *
         * @param       string          The table name of the record
         * @param       string          The field name which this element is supposed to edit
         * @param       array           The record data array where the value(s) for the field can be found
@@ -1367,16 +1392,29 @@ class t3lib_TCEforms    {
                        // Init:
                $config = $PA['fieldConf']['config'];
                $itemValue = $PA['itemFormElValue'];
-               
+
+               return $this->getSingleField_typeNone_render($config,$itemValue);
+       }
+
+       /**
+        * HTML rendering of a value which is not editable.
+        *
+        * @param       array           Configuration for the display
+        * @param       string          The value to display
+        * @return      string          The HTML code for the display
+        * @see getSingleField_typeNone();
+        */
+       function getSingleField_typeNone_render($config,$itemValue)     {
+
                $divStyle = 'border:solid 1px '.t3lib_div::modifyHTMLColorAll($this->colorScheme[0],-30).';'.$this->defStyle.$this->formElStyle('text').' background-color: '.$this->colorScheme[0].'; overflow:auto;padding-left:1px;color:#555;';
                if ($config['rows']>1) {
                        if(!$config['pass_content']) {
-                               $itemValue=nl2br(htmlspecialchars($itemValue));
+                               $itemValue = nl2br(htmlspecialchars($itemValue));
                        }
                                // like textarea
-                       $cols = t3lib_div::intInRange($config['cols']?$config['cols']:30,5,$this->maxTextareaWidth);
+                       $cols = t3lib_div::intInRange($config['cols'] ? $config['cols'] : 30, 5, $this->maxTextareaWidth);
                        if (!$config['fixedRows']) {
-                               $origRows = $rows = t3lib_div::intInRange($config['rows']?$config['rows']:5,1,20);
+                               $origRows = $rows = t3lib_div::intInRange($config['rows'] ? $config['rows'] : 5, 1, 20);
                                if (strlen($itemValue)>$this->charsPerRow*2)    {
                                        $cols = $this->maxTextareaWidth;
                                        $rows = t3lib_div::intInRange(round(strlen($itemValue)/$this->charsPerRow),count(explode(chr(10),$itemValue)),20);
@@ -1391,10 +1429,13 @@ class t3lib_TCEforms    {
                                // hardcoded: 12 is the height of the font
                        $height=$rows*12;
                                // is colorScheme[0] the right value?
-                       $item='<div style="'.htmlspecialchars($divStyle.'height:'.$height.'px;width:'.$width.'px;').'">'.$itemValue.'</div>';
+                       $item='
+                               <div style="'.htmlspecialchars($divStyle.'height:'.$height.'px;width:'.$width.'px;').'">'.
+                               $itemValue.
+                               '</div>';
                } else {
                        if(!$config['pass_content']) {
-                               $itemValue=htmlspecialchars($itemValue);
+                               $itemValue = htmlspecialchars($itemValue);
                        }
 
                        // how to handle cropping for too long lines?
@@ -1402,15 +1443,18 @@ class t3lib_TCEforms    {
                        $cols = $config['cols']?$config['cols']:($config['size']?$config['size']:$this->maxInputWidth);
                        if ($this->docLarge)    $cols = round($cols*$this->form_largeComp);
                        $width = ceil($cols*$this->form_rowsToStylewidth);
-                       $item='<div style="'.htmlspecialchars($divStyle.'width:'.$width.'px;').'"><nobr>'.(strcmp($itemValue,'')?$itemValue:"&nbsp;").'<nobr></div>';
+                       $item = '
+                               <div style="'.htmlspecialchars($divStyle.'width:'.$width.'px;').'">'.   // Had to remove "nobreak" since Mozilla crashed...!
+                               (strcmp($itemValue,'') ? $itemValue : '&nbsp;').
+                               '</div>';
                }
 
                return $item;
        }
-       
+
        /**
         * Handler for Flex Forms
-        * 
+        *
         * @param       string          The table name of the record
         * @param       string          The field name which this element is supposed to edit
         * @param       array           The record data array where the value(s) for the field can be found
@@ -1440,7 +1484,7 @@ class t3lib_TCEforms      {
 #debug(array($editData,$xmlData));
                                $editData=array();
                        }
-                               
+
                                // Find the data structure if sheets are found:
                        $sheet = $editData['meta']['currentSheetId'] ? $editData['meta']['currentSheetId'] : 'sDEF';    // Sheet to display
                        $item.= '<input type="hidden" name="'.$PA['itemFormElName'].'[meta][currentSheetId]" value="'.$sheet.'">';
@@ -1450,22 +1494,22 @@ class t3lib_TCEforms    {
                                $item.=$this->getSingleField_typeFlex_sheetMenu($dataStructArray['sheets'], $PA['itemFormElName'].'[meta][currentSheetId]', $sheet).'<br />';
                        }
 #debug($editData);
-               
+
                                // Create language menu:
                        $langChildren = $dataStructArray['meta']['langChildren'] ? 1 : 0;
                        $langDisabled = $dataStructArray['meta']['langDisable'] ? 1 : 0;
 
                        $languages = $this->getAvailableLanguages();
-                       
+
                        if (!is_array($editData['meta']['currentLangId']) || !count($editData['meta']['currentLangId']))        {
                                $editData['meta']['currentLangId']=array('DEF');
                        }
                        $editData['meta']['currentLangId'] = array_unique($editData['meta']['currentLangId']);
-                       
+
                        if (!$langDisabled && count($languages) > 1)    {
                                $item.=$this->getSingleField_typeFlex_langMenu($languages, $PA['itemFormElName'].'[meta][currentLangId]', $editData['meta']['currentLangId']).'<br />';
                        }
-                       
+
                        if ($langChildren || $langDisabled)     {
                                $rotateLang = array('DEF');
                        } else {
@@ -1479,13 +1523,13 @@ class t3lib_TCEforms    {
        #                       foreach($dataStructArray['sheets'] as $sheet => $_blabla)       {
                                        list ($dataStruct, $sheet) = t3lib_div::resolveSheetDefInDS($dataStructArray,$sheet);
                #debug(array($dataStruct, $sheet));
-                                       
+
                                                // Render sheet:
                                        if (is_array($dataStruct['ROOT']) && is_array($dataStruct['ROOT']['el']))               {
-                                               $cmdData = t3lib_div::GPvar('flexFormsCmdData',1);
+                                               $cmdData = t3lib_div::_GP('flexFormsCmdData');
                                                $lang = 'l'.$lKey;      // Default language, other options are "lUK" or whatever country code (independant of system!!!)
                                                $PA['_valLang'] = $langChildren && !$langDisabled ? $editData['meta']['currentLangId'] : 'DEF'; // Default language, other options are "lUK" or whatever country code (independant of system!!!)
-                                               
+
                                                        // Render flexform:
                                                $tRows = $this->getSingleField_typeFlex_draw(
                                                                        $dataStruct['ROOT']['el'],
@@ -1497,8 +1541,8 @@ class t3lib_TCEforms      {
                                                                        $PA,
                                                                        '[data]['.$sheet.']['.$lang.']'
                                                                );
-                                               $item.= '<table border="1" cellpadding="2" cellspacing="0">'.implode('',$tRows).'</table>';
-                                               
+                                               $item.= '<table border="0" cellpadding="1" cellspacing="1">'.implode('',$tRows).'</table>';
+
                        #                       $item = '<div style=" position:absolute;">'.$item.'</div>';
                                                //visibility:hidden;
                                        } else $item.='Data Structure ERROR: No ROOT element found for sheet "'.$sheet.'".';
@@ -1508,10 +1552,10 @@ class t3lib_TCEforms    {
 
                return $item;
        }
-       
+
        /**
         * Creates the language menu for FlexForms:
-        * 
+        *
         * @param       [type]          $languages: ...
         * @param       [type]          $elName: ...
         * @param       [type]          $selectedLanguage: ...
@@ -1528,33 +1572,33 @@ class t3lib_TCEforms    {
 
                return $output;
        }
-       
+
        /**
         * Creates the menu for selection of the sheets:
-        * 
+        *
         * @param       array           Sheet array for which to render the menu
         * @param       string          Form element name of the field containing the sheet pointer
         * @param       string          Current sheet key
         * @return      string          HTML for menu
         */
        function getSingleField_typeFlex_sheetMenu($sArr,$elName,$sheetKey)     {
-       
+
                $tCells=array();
                $pct = round(100/count($sArr));
                foreach($sArr as $sKey => $sheetCfg)    {
-                       $onClick="if (confirm(".$GLOBALS['LANG']->JScharCode($this->getLL('m_onChangeAlert')).") && TBE_EDITOR_checkSubmit(-1)){".$this->elName($elName).".value='".$sKey."'; TBE_EDITOR_submitForm()};";
+                       $onClick = 'if (confirm('.$GLOBALS['LANG']->JScharCode($this->getLL('m_onChangeAlert')).') && TBE_EDITOR_checkSubmit(-1)){'.$this->elName($elName).".value='".$sKey."'; TBE_EDITOR_submitForm()};";
 
                        $tCells[]='<td width="'.$pct.'%" style="'.($sKey==$sheetKey ? 'background-color: #9999cc; font-weight: bold;' : 'background-color: #aaaaaa;').' cursor: hand;" onclick="'.htmlspecialchars($onClick).'" align="center">'.
                                        ($sheetCfg['ROOT']['TCEforms']['sheetTitle'] ? $this->sL($sheetCfg['ROOT']['TCEforms']['sheetTitle']) : $sKey).
                                        '</td>';
                }
-               
+
                return '<table border="0" cellpadding="0" cellspacing="2" style="padding: 1px 15px 0px 15px; border: 1px solid black;"><tr>'.implode('',$tCells).'</tr></table>';
        }
-       
+
        /**
         * [Describe function...]
-        * 
+        *
         * @param       [type]          $dataStruct: ...
         * @param       [type]          $editData: ...
         * @param       [type]          $cmdData: ...
@@ -1568,7 +1612,7 @@ class t3lib_TCEforms      {
         * @return      [type]          ...
         */
        function getSingleField_typeFlex_draw($dataStruct,$editData,$cmdData,$table,$field,$row,&$PA,$formPrefix='',$level=0,$tRows=array())    {
-       
+
                        // Data Structure array must be ... and array of course...
                if (is_array($dataStruct))      {
                        foreach($dataStruct as $key => $value)  {
@@ -1578,8 +1622,7 @@ class t3lib_TCEforms      {
                                                // Making the row:
                                                // ********************
                                        $rowCells=array();
-                                       $bgColor = $this->doc->bgColor4;
-                                               
+
                                                // Icon:
                                        $rowCells['title'] = '<img src="clear.gif" width="'.($level*16).'" height="1" alt="" /><strong>'.htmlspecialchars(t3lib_div::fixed_lgd($this->sL($value['tx_templavoila']['title']),30)).'</strong>';;
 
@@ -1596,11 +1639,11 @@ class t3lib_TCEforms    {
                                                        }
 
                                                                // Put row together
-                                                       $tRows[]='<tr bgcolor="'.$bgColor.'">
+                                                       $tRows[]='<tr class="bgColor2">
                                                                <td nowrap="nowrap" valign="top">'.$rowCells['title'].'</td>
                                                                <td>'.$rowCells['formEl'].'</td>
                                                        </tr>';
-                                                       
+
                                                        $cc=0;
                                                        if (is_array($editData[$key]['el']))    {
                                                                foreach($editData[$key]['el'] as $k3 => $v3)    {
@@ -1624,8 +1667,8 @@ class t3lib_TCEforms      {
                                                                        }
                                                                }
                                                        }
-                                                       
-                                                       
+
+
 
                                                                // New form?
                                                        if ($cmdData[$key]['value'])    {
@@ -1647,9 +1690,9 @@ class t3lib_TCEforms      {
                                                        }
                                                } else {
                                                                // Put row together
-                                                       $tRows[]='<tr bgcolor="'.$bgColor.'">
+                                                       $tRows[]='<tr class="bgColor2">
                                                                <td nowrap="nowrap" valign="top">'.
-                                                               '<input name="_DELETE_FLEX_FORM'.$PA['itemFormElName'].$formPrefix.'" type="checkbox" value="1" /><img src="'.$this->backPath.'gfx/garbage.gif" border="0">'.
+                                                               '<input name="_DELETE_FLEX_FORM'.$PA['itemFormElName'].$formPrefix.'" type="checkbox" value="1" /><img src="'.$this->backPath.'gfx/garbage.gif" border="0" alt="" />'.
                                                                $rowCells['title'].'</td>
                                                                <td>'.$rowCells['formEl'].'</td>
                                                        </tr>';
@@ -1675,30 +1718,32 @@ class t3lib_TCEforms    {
                                                } else {
                                                        $rotateLang = array($PA['_valLang']);
                                                }
-                                               
+
                                                foreach($rotateLang as $vDEFkey)        {
                                                        $vDEFkey = 'v'.$vDEFkey;
 
                                                        $fakePA=array();
                                                        $fakePA['fieldConf']=array(
-                                                               'label' => $this->sL($value['TCEforms']['label']), 
-                                                               'config' => $value['TCEforms']['config']
+                                                               'label' => $this->sL($value['TCEforms']['label']),
+                                                               'config' => $value['TCEforms']['config'],
+                                                               'defaultExtras' => $value['TCEforms']['defaultExtras'],
+                                                               'displayCond' => $value['TCEforms']['displayCond'],     // Haven't tested this...
                                                        );
                                                        $fakePA['fieldChangeFunc']=$PA['fieldChangeFunc'];
                                                        $fakePA['onFocus']=$PA['onFocus'];
                                                        $fakePA['label']==$PA['label'];
-                                                       
+
                                                        $fakePA['itemFormElName']=$PA['itemFormElName'].$formPrefix.'['.$key.']['.$vDEFkey.']';
                                                        $fakePA['itemFormElName_file']=$PA['itemFormElName_file'].$formPrefix.'['.$key.']['.$vDEFkey.']';
                                                        $fakePA['itemFormElValue']=$editData[$key][$vDEFkey];
-       
+
                                                        $rowCells['formEl']= $this->getSingleField_SW($table,$field,$row,$fakePA);
                                                        $rowCells['title']= htmlspecialchars($fakePA['fieldConf']['label']);
-                                                       
+
                                                                // Put row together
-                                                       $tRows[]='<tr bgcolor="'.$bgColor.'">
-                                                               <td nowrap="nowrap" valign="top">'.$rowCells['title'].($vDEFkey=='vDEF' ? '' : ' ('.$vDEFkey.')').'</td>
-                                                               <td>'.$rowCells['formEl'].'</td>
+                                                       $tRows[]='<tr>
+                                                               <td nowrap="nowrap" valign="top" class="bgColor5">'.$rowCells['title'].($vDEFkey=='vDEF' ? '' : ' ('.$vDEFkey.')').'</td>
+                                                               <td class="bgColor4">'.$rowCells['formEl'].'</td>
                                                        </tr>';
                                                }
                                        }
@@ -1706,12 +1751,12 @@ class t3lib_TCEforms    {
                        }
                }
 
-               return $tRows;          
+               return $tRows;
        }
 
        /**
         * Handler for unknown types.
-        * 
+        *
         * @param       string          The table name of the record
         * @param       string          The field name which this element is supposed to edit
         * @param       array           The record data array where the value(s) for the field can be found
@@ -1725,8 +1770,8 @@ class t3lib_TCEforms      {
        }
 
        /**
-        * User defined type
-        * 
+        * User defined field type
+        *
         * @param       string          The table name of the record
         * @param       string          The field name which this element is supposed to edit
         * @param       array           The record data array where the value(s) for the field can be found
@@ -1738,7 +1783,9 @@ class t3lib_TCEforms      {
                $PA['field']=$field;
                $PA['row']=$row;
 
-               return t3lib_div::callUserFunction($PA['fieldConf']['config']["userFunc"],$PA,$this);
+               $PA['pObj']=&$this;
+
+               return t3lib_div::callUserFunction($PA['fieldConf']['config']['userFunc'],$PA,$this);
        }
 
 
@@ -1757,10 +1804,10 @@ class t3lib_TCEforms    {
         * "Configuration" fetching/processing functions
         *
         ************************************************************/
-       
+
        /**
         * Calculate and return the current "types" pointer value for a record
-        * 
+        *
         * @param       string          The table name. MUST be in $TCA
         * @param       array           The row from the table, should contain at least the "type" field, if applicable.
         * @return      string          Return the "type" value for this record, ready to pick a "types" configuration from the $TCA array.
@@ -1786,7 +1833,7 @@ class t3lib_TCEforms      {
 
        /**
         * Used to adhoc-rearrange the field order normally set in the [types][showitem] list
-        * 
+        *
         * @param       array           A [types][showitem] list of fields, exploded by ","
         * @return      array           Returns rearranged version (keys are changed around as well.)
         * @see getMainFields()
@@ -1806,11 +1853,11 @@ class t3lib_TCEforms    {
                $fields=array_merge($newFields,$fields);                // Candidate for t3lib_div::array_merge() if integer-keys will some day make trouble...
                return $fields;
        }
-       
+
        /**
         * Producing an array of field names NOT to display in the form, based on settings from subtype_value_field, bitmask_excludelist_bits etc.
         * Notice, this list is in NO way related to the "excludeField" flag
-        * 
+        *
         * @param       string          Table name, MUST be in $TCA
         * @param       array           A record from table.
         * @param       string          A "type" pointer value, probably the one calculated based on the record array.
@@ -1819,10 +1866,10 @@ class t3lib_TCEforms    {
         */
        function getExcludeElements($table,$row,$typeNum)       {
                global $TCA;
-               
+
                        // Init:
                $excludeElements=array();
-               
+
                        // If a subtype field is defined for the type
                if ($TCA[$table]['types'][$typeNum]['subtype_value_field'])     {
                        $sTfield = $TCA[$table]['types'][$typeNum]['subtype_value_field'];
@@ -1842,7 +1889,7 @@ class t3lib_TCEforms      {
                                        if (t3lib_div::testInt($bit))   {
                                                $bit = t3lib_div::intInRange($bit,0,30);
                                                if (
-                                                               (substr($bitKey,0,1)=='-' && !($sTValue&pow(2,$bit))) ||        
+                                                               (substr($bitKey,0,1)=='-' && !($sTValue&pow(2,$bit))) ||
                                                                (substr($bitKey,0,1)=='+' && ($sTValue&pow(2,$bit)))
                                                        )       {
                                                        $excludeElements = array_merge($excludeElements,t3lib_div::trimExplode(',',$eList,1));
@@ -1858,7 +1905,7 @@ class t3lib_TCEforms      {
 
        /**
         * Finds possible field to add to the form, based on subtype fields.
-        * 
+        *
         * @param       string          Table name, MUST be in $TCA
         * @param       array           A record from table.
         * @param       string          A "type" pointer value, probably the one calculated based on the record array.
@@ -1867,10 +1914,10 @@ class t3lib_TCEforms    {
         */
        function getFieldsToAdd($table,$row,$typeNum)   {
                global $TCA;
-                       
+
                        // Init:
                $addElements=array();
-               
+
                        // If a subtype field is defined for the type
                if ($TCA[$table]['types'][$typeNum]['subtype_value_field'])     {
                        $sTfield = $TCA[$table]['types'][$typeNum]['subtype_value_field'];
@@ -1884,7 +1931,7 @@ class t3lib_TCEforms      {
 
        /**
         * Merges the current [types][showitem] array with the array of fields to add for the current subtype field of the "type" value.
-        * 
+        *
         * @param       array           A [types][showitem] list of fields, exploded by ","
         * @param       array           The output from getFieldsToAdd()
         * @return      array           Return the modified $fields array.
@@ -1908,17 +1955,17 @@ class t3lib_TCEforms    {
                                $c++;
                        }
                }
-               return $fields; 
+               return $fields;
        }
 
 
        /**
         * Returns TSconfig for table/row
         * Multiple requests to this function will return cached content so there is no performance loss in calling this many times since the information is looked up only once.
-        * 
+        *
         * @param       string          The table name
         * @param       array           The table row (Should at least contain the "uid" value, even if "NEW..." string. The "pid" field is important as well, and negative values will be intepreted as pointing to a record from the same table.)
-        * @param       string          Optionally you can specify the field name as well. If that case the TSconfig for the field is returned.
+        * @param       string          Optionally you can specify the field name as well. In that case the TSconfig for the field is returned.
         * @return      mixed           The TSconfig values (probably in an array)
         * @see t3lib_BEfunc::getTCEFORM_TSconfig()
         */
@@ -1937,17 +1984,17 @@ class t3lib_TCEforms    {
        /**
         * Returns the "special" configuration (from the "types" "showitem" list) for a fieldname based on input table/record
         * (Not used anywhere...?)
-        * 
+        *
         * @param       string          The table name
         * @param       array           The table row (Should at least contain the "uid" value, even if "NEW..." string. The "pid" field is important as well, and negative values will be intepreted as pointing to a record from the same table.)
         * @param       string          Specify the field name.
-        * @return      array           
+        * @return      array
         * @see getSpecConfFromString(), t3lib_BEfunc::getTCAtypes()
         */
        function getSpecConfForField($table,$row,$field)        {
                        // Finds the current "types" configuration for the table/row:
-               $types_fieldConfig=t3lib_BEfunc::getTCAtypes($table,$row);
-               
+               $types_fieldConfig = t3lib_BEfunc::getTCAtypes($table,$row);
+
                        // If this is an array, then traverse it:
                if (is_array($types_fieldConfig))       {
                        foreach($types_fieldConfig as $vconf)   {
@@ -1959,13 +2006,14 @@ class t3lib_TCEforms    {
 
        /**
         * Returns the "special" configuration of an "extra" string (non-parsed)
-        * 
+        *
         * @param       string          The "Part 4" of the fields configuration in "types" "showitem" lists.
+        * @param       string          The ['defaultExtras'] value from field configuration
         * @return      array           An array with the special options in.
         * @see getSpecConfForField(), t3lib_BEfunc::getSpecConfParts()
         */
-       function getSpecConfFromString($extraString)    {
-               return t3lib_BEfunc::getSpecConfParts($extraString);
+       function getSpecConfFromString($extraString, $defaultExtras)    {
+               return t3lib_BEfunc::getSpecConfParts($extraString, $defaultExtras);
        }
 
 
@@ -1986,7 +2034,7 @@ class t3lib_TCEforms      {
 
        /**
         * Prints the selector box form-field for the db/file/select elements (multiple)
-        * 
+        *
         * @param       string          Form element name
         * @param       string          Mode "db", "file" (internal_type for the "group" type) OR blank (then for the "select" type)
         * @param       string          Commalist of "allowed"
@@ -2005,7 +2053,7 @@ class t3lib_TCEforms      {
                $uidList=array();
                $opt=array();
                $itemArrayC=0;
-                       
+
                        // Creating <option> elements:
                if (is_array($itemArray))       {
                        $itemArrayC=count($itemArray);
@@ -2039,31 +2087,59 @@ class t3lib_TCEforms    {
                                break;
                        }
                }
-                       
+
                        // Create selector box of the options
                if (!$selector) {
                        $sSize = $params['autoSizeMax'] ? t3lib_div::intInRange($itemArrayC+1,t3lib_div::intInRange($params['size'],1),$params['autoSizeMax']) : $params['size'];
-                       $selector = '<select size="'.$sSize.'"'.$this->insertDefStyle('group').' multiple="multiple" name="'.$fName.'_list" style="width:200px;"'.$onFocus.'>'.implode('',$opt).'</select>';
+                       $selector = '<select size="'.$sSize.'"'.$this->insertDefStyle('group').' multiple="multiple" name="'.$fName.'_list" '.$onFocus.$params['style'].'>'.implode('',$opt).'</select>';
                }
-               
-                       
-               $icons=array();
+
+
+               $icons = array(
+                       'L' => array(),
+                       'R' => array(),
+               );
                if (!$params['noBrowser'])      {
                        $aOnClick='setFormValueOpenBrowser(\''.$mode.'\',\''.($fName.'|||'.$allowed.'|').'\'); return false;';
-                       $icons[]='<a href="#" onclick="'.htmlspecialchars($aOnClick).'">'.
-                                       '<img src="'.$this->backPath.'gfx/insert3.gif" width="14" height="14" border="0" '.t3lib_BEfunc::titleAltAttrib($this->getLL("l_browse_".($mode=="file"?"file":"db"))).' />'.
+                       $icons['R'][]='<a href="#" onclick="'.htmlspecialchars($aOnClick).'">'.
+                                       '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/insert3.gif','width="14" height="14"').' border="0" '.t3lib_BEfunc::titleAltAttrib($this->getLL('l_browse_'.($mode=='file'?'file':'db'))).' />'.
                                        '</a>';
                }
                if (!$params['dontShowMoveIcons'])      {
-                       $icons[]='<a href="#" onclick="setFormValueManipulate(\''.$fName.'\',\'Up\'); return false;">'.
-                                       '<img src="'.$this->backPath.'gfx/group_totop.gif" width="14" height="14" border="0" '.t3lib_BEfunc::titleAltAttrib($this->getLL("l_move_to_top")).' />'.
+                       $icons['L'][]='<a href="#" onclick="setFormValueManipulate(\''.$fName.'\',\'Up\'); return false;">'.
+                                       '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/group_totop.gif','width="14" height="14"').' border="0" '.t3lib_BEfunc::titleAltAttrib($this->getLL('l_move_to_top')).' />'.
                                        '</a>';
                }
-               $icons[]='<a href="#" onclick="setFormValueManipulate(\''.$fName.'\',\'Remove\'); return false;">'.
-                               '<img src="'.$this->backPath.'gfx/group_clear.gif" width="14" height="14" border="0" '.t3lib_BEfunc::titleAltAttrib($this->getLL("l_remove_selected")).' />'.
+
+               $clipElements = $this->getClipboardElements($allowed,$mode);
+               if (count($clipElements))       {
+                       $aOnClick = '';
+#                      $counter = 0;
+                       foreach($clipElements as $elValue)      {
+                               if ($mode=='file')      {
+                                       $itemTitle = 'unescape(\''.rawurlencode(basename($elValue)).'\')';
+                               } else {        // 'db' mode assumed
+                                       list($itemTable,$itemUid) = explode('|', $elValue);
+                                       $itemTitle = $GLOBALS['LANG']->JScharCode(t3lib_BEfunc::getRecordTitle($itemTable, t3lib_BEfunc::getRecord($itemTable,$itemUid)));
+                                       $elValue = $itemTable.'_'.$itemUid;
+                               }
+                               $aOnClick.= 'setFormValueFromBrowseWin(\''.$fName.'\',unescape(\''.rawurlencode(str_replace('%20',' ',$elValue)).'\'),'.$itemTitle.');';
+
+#                              $counter++;
+#                              if ($params['maxitems'] && $counter >= $params['maxitems'])     {       break;  }       // Makes sure that no more than the max items are inserted... for convenience.
+                       }
+                       $aOnClick.= 'return false;';
+                       $icons['R'][]='<a href="#" onclick="'.htmlspecialchars($aOnClick).'">'.
+                                       '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/insert5.png','width="14" height="14"').' border="0" '.t3lib_BEfunc::titleAltAttrib(sprintf($this->getLL('l_clipInsert_'.($mode=='file'?'file':'db')),count($clipElements))).' />'.
+                                       '</a>';
+               }
+
+               $icons['L'][]='<a href="#" onclick="setFormValueManipulate(\''.$fName.'\',\'Remove\'); return false;">'.
+                               '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/group_clear.gif','width="14" height="14"').' border="0" '.t3lib_BEfunc::titleAltAttrib($this->getLL('l_remove_selected')).' />'.
                                '</a>';
-               $str='<table border=0 cellpadding=0 cellspacing=0 width=1>
-                       '.($params["headers"]?'
+
+               $str='<table border="0" cellpadding="0" cellspacing="0" width="1">
+                       '.($params['headers']?'
                                <tr>
                                        <td>'.$this->wrapLabels($params['headers']['selector']).'</td>
                                        <td></td>
@@ -2077,23 +2153,88 @@ class t3lib_TCEforms    {
                                        $this->wrapLabels($params['info']).
                                '</td>
                                <td valign="top">'.
-                                       implode('<br />',$icons).'</td>
+                                       implode('<br />',$icons['L']).'</td>
+                               <td valign="top">'.
+                                       implode('<br />',$icons['R']).'</td>
                                <td><img src="clear.gif" width="5" height="1" alt="" /></td>
                                <td valign="top">'.
                                        $this->wrapLabels($params['thumbnails']).
                                '</td>
                        </tr>
                </table>';
-               
+
                        // Creating the hidden field which contains the actual value as a comma list.
                $str.='<input type="hidden" name="'.$fName.'" value="'.htmlspecialchars(implode(',',$uidList)).'" />';
-               
+
                return $str;
        }
 
        /**
+        * Returns array of elements from clipboard to insert into GROUP element box.
+        *
+        * @param       string          Allowed elements, Eg "pages,tt_content", "gif,jpg,jpeg,png"
+        * @param       string          Mode of relations: "db" or "file"
+        * @return      array           Array of elements in values (keys are insignificant), if none found, empty array.
+        */
+       function getClipboardElements($allowed,$mode)   {
+
+               $output = array();
+
+               if (is_object($this->clipObj))  {
+                       switch($mode)   {
+                               case 'file':
+                                       $elFromTable = $this->clipObj->elFromTable('_FILE');
+                                       $allowedExts = t3lib_div::trimExplode(',', $allowed, 1);
+
+                                       if ($allowedExts)       {       // If there are a set of allowed extensions, filter the content:
+                                               foreach($elFromTable as $elValue)       {
+                                                       $pI = pathinfo($elValue);
+                                                       $ext = strtolower($pI['extension']);
+                                                       if (in_array($ext, $allowedExts))       {
+                                                               $output[] = $elValue;
+                                                       }
+                                               }
+                                       } else {        // If all is allowed, insert all: (This does NOT respect any disallowed extensions, but those will be filtered away by the backend TCEmain)
+                                               $output = $elFromTable;
+                                       }
+                               break;
+                               case 'db':
+                                       $allowedTables = t3lib_div::trimExplode(',', $allowed, 1);
+                                       if (!strcmp(trim($allowedTables[0]),'*'))       {       // All tables allowed for relation:
+                                               $output = $this->clipObj->elFromTable('');
+                                       } else {        // Only some tables, filter them:
+                                               foreach($allowedTables as $tablename)   {
+                                                       $elFromTable = $this->clipObj->elFromTable($tablename);
+                                                       $output = array_merge($output,$elFromTable);
+                                               }
+                                       }
+                                       $output = array_keys($output);
+                               break;
+                       }
+               }
+
+               return $output;
+       }
+
+       /**
+        * Wraps the icon of a relation item (database record or file) in a link opening the context menu for the item.
+        * Icons will be wrapped only if $this->enableClickMenu is set. This must be done only if a global SOBE object exists and if the necessary JavaScript for displaying the context menus has been added to the page header.
+        *
+        * @param       string          The icon HTML to wrap
+        * @param       string          Table name (eg. "pages" or "tt_content") OR the absolute path to the file
+        * @param       integer         The uid of the record OR if file, just blank value.
+        * @return      string          HTML
+        */
+       function getClickMenu($str,$table,$uid='')      {
+               if ($this->enableClickMenu)     {
+                       $onClick = $GLOBALS['SOBE']->doc->wrapClickMenuOnIcon($str,$table,$uid,1,'','+copy,info,edit,view', TRUE);
+                       return '<a href="#" onclick="'.htmlspecialchars($onClick).'">'.$str.'</a>';
+               }
+       }
+
+       /**
         * Rendering wizards for form fields.
-        * 
+        *
         * @param       array           Array with the real item in the first value, and an alternative item in the second value.
         * @param       array           The "wizard" key from the config array for the field (from TCA)
         * @param       string          Table name
@@ -2106,30 +2247,30 @@ class t3lib_TCEforms    {
         * @return      string          The new item value.
         */
        function renderWizards($itemKinds,$wizConf,$table,$row,$field,&$PA,$itemName,$specConf,$RTE=0)  {
-       
+
                        // Init:
                $fieldChangeFunc = $PA['fieldChangeFunc'];
                $item = $itemKinds[0];
-               $outArr=array();
-               $fName='['.$table.']['.$row["uid"].']['.$field.']';
+               $outArr = array();
+               $fName = '['.$table.']['.$row['uid'].']['.$field.']';
                $md5ID = t3lib_div::shortmd5($itemName);
 
                        // traverse wizards:
                if (is_array($wizConf) && !$this->disableWizards)       {
                        reset($wizConf);
                        while(list($wid,$wConf)=each($wizConf)) {
-                               if (substr($wid,0,1)!='_' 
+                               if (substr($wid,0,1)!='_'
                                                && (!$wConf['enableByTypeConfig'] || @in_array($wid,$specConf['wizards']['parameters']))
                                                && ($RTE || !$wConf['RTEonly'])
                                        )       {
-                               
+
                                                // Title / icon:
                                        $iTitle = htmlspecialchars($this->sL($wConf['title']));
                                        if ($wConf['icon'])     {
                                                $iDat = $this->getIcon($wConf['icon']);         // THIS is very ODD!!! Check it....
                                                $icon = '<img src="'.$iDat[0].'" '.$iDat[1][3].' border="0"'.t3lib_BEfunc::titleAltAttrib($iTitle).' />';
-                                       } else $icon=$iTitle;
-                                       
+                                       } else $icon = $iTitle;
+
                                        $colorBoxLinks=array();
                                        switch((string)$wConf['type'])  {
                                                case 'userFunc':
@@ -2144,9 +2285,17 @@ class t3lib_TCEforms     {
                                                                $params['pid'] = $row['pid'];
                                                                $params['field'] = $field;
                                                                $params['md5ID'] = $md5ID;
-                                                               $params['returnUrl'] = t3lib_div::linkThisScript();
-                                                               $url = $this->backPath.$wConf['script'].(strstr($wConf['script'],'?') ? '' : '?');
-
+                                                               $params['returnUrl'] = $this->thisReturnUrl();
+
+                                                               if (!strcmp(substr($wConf['script'],0,4), 'EXT:')) {
+                                                                       $wScript = t3lib_div::getFileAbsFileName($wConf['script']);
+                                                                       if ($wScript)   {
+                                                                               $wScript = '../'.substr($wScript,strlen(PATH_site));
+                                                                       } else break;
+                                                               } else {
+                                                                       $wScript = $wConf['script'];
+                                                               }
+                                                               $url = $this->backPath.$wScript.(strstr($wConf['script'],'?') ? '' : '?');
 
                                                                if ((string)$wConf['type']=='colorbox' && !$wConf['script'])    {
                                                                        break;
@@ -2158,9 +2307,9 @@ class t3lib_TCEforms      {
                                                                                                '</a>';
                                                                }
 
-                                                               $params['formName']=$this->formName;
-                                                               $params['itemName']=$itemName;
-                                                               $params['fieldChangeFunc']=$fieldChangeFunc;
+                                                               $params['formName'] = $this->formName;
+                                                               $params['itemName'] = $itemName;
+                                                               $params['fieldChangeFunc'] = $fieldChangeFunc;
                                                                if ((string)$wConf['type']=='popup' || (string)$wConf['type']=='colorbox')      {
                                                                                // Current form value is passed as P[currentValue]!
                                                                        $addJS = $wConf['popup_onlyOpenIfSelected']?'if (!TBE_EDITOR_curSelected(\''.$itemName.'_list\')){alert('.$GLOBALS['LANG']->JScharCode($this->getLL('m_noSelItemForEdit')).'); return false;}':'';
@@ -2169,17 +2318,25 @@ class t3lib_TCEforms    {
                                                                                                $addJS.
                                                                                                'vHWin=window.open(\''.$url.t3lib_div::implodeArrayForUrl('',array('P'=>$params)).'\'+\'&P[currentValue]=\'+TBE_EDITOR_rawurlencode('.$this->elName($itemName).'.value,200)'.$curSelectedValues.',\'popUp'.$md5ID.'\',\''.$wConf['JSopenParams'].'\');'.
                                                                                                'vHWin.focus();return false;';
-                                                                       $colorBoxLinks=Array('<a href="#" onclick="'.htmlspecialchars($aOnClick).'">','</a>');
+                                                                       $colorBoxLinks = Array('<a href="#" onclick="'.htmlspecialchars($aOnClick).'">','</a>');
                                                                        if ((string)$wConf['type']=='popup')    {
                                                                                $outArr[] = $colorBoxLinks[0].$icon.$colorBoxLinks[1];
                                                                        }
                                                                } elseif ((string)$wConf['type']=='userFunc')   {
-                                                                       $params['item']=&$item;
-                                                                       $params['icon']=$icon;
-                                                                       $params['iTitle']=$iTitle;
-                                                                       $params['wConf']=$wConf;
-                                                                       $params['row']=$row;
-                                                                       $outArr[]=t3lib_div::callUserFunction($wConf['userFunc'],$params,$this);
+                                                                       $params['item'] = &$item;
+                                                                       $params['icon'] = $icon;
+                                                                       $params['iTitle'] = $iTitle;
+                                                                       $params['wConf'] = $wConf;
+                                                                       $params['row'] = $row;
+                                                                       $outArr[] = t3lib_div::callUserFunction($wConf['userFunc'],$params,$this);
+                                                               }
+
+                                                                       // Hide?
+                                                               if (is_array($wConf['hideParent']) || $wConf['hideParent'])     {
+                                                                       $item = $itemKinds[1];
+                                                                       if (is_array($wConf['hideParent']))     {
+                                                                               $item.= $this->getSingleField_typeNone_render($wConf['hideParent'], $PA['itemFormElValue']);
+                                                                       }
                                                                }
                                                        }
                                                break;
@@ -2188,7 +2345,7 @@ class t3lib_TCEforms      {
                                                        $TSconfig = $this->setTSconfig($table,$row);
                                                        $TSconfig[$field] = $TSconfig[$field]['wizards.'][$wid.'.'];
                                                        $selItems = $this->addSelectOptionsToItemArray($this->initItemArray($fieldValue),$fieldValue,$TSconfig,$field);
-                                                       
+
                                                        reset($selItems);
                                                        $opt=array();
                                                        $opt[]='<option>'.$iTitle.'</option>';
@@ -2225,11 +2382,11 @@ class t3lib_TCEforms    {
                                        }
                                }
                        }
-                       
+
                                // For each rendered wizard, put them together around the item.
                        if (count($outArr))     {
                                if ($wizConf['_HIDDENFIELD'])   $item = $itemKinds[1];
-                       
+
                                $outStr='';
                                $vAlign = $wizConf['_VALIGN'] ? ' valign="'.$wizConf['_VALIGN'].'"' : '';
                                if (count($outArr)>1 || $wizConf['_PADDING'])   {
@@ -2241,7 +2398,7 @@ class t3lib_TCEforms      {
                                                $dist=$dist?'<td><img src="clear.gif" height="1" width="'.$dist.'" alt="" /></td>':'';
                                                $outStr='<tr><td'.$vAlign.'>'.implode('</td>'.$dist.'<td'.$vAlign.'>',$outArr).'</td></tr>';
                                        }
-                                       $outStr='<table border="0" cellpadding="'.intval($wizConf["_PADDING"]).'" cellspacing="0">'.$outStr.'</table>';
+                                       $outStr='<table border="0" cellpadding="'.intval($wizConf['_PADDING']).'" cellspacing="0">'.$outStr.'</table>';
                                } else {
                                        $outStr=implode('',$outArr);
                                }
@@ -2263,8 +2420,8 @@ class t3lib_TCEforms      {
        }
 
        /**
-        * Get icon
-        * 
+        * Get icon (for example for selector boxes)
+        *
         * @param       string          Icon reference
         * @return      array           Array with two values; the icon file reference, the icon file information array (getimagesize())
         */
@@ -2291,7 +2448,7 @@ class t3lib_TCEforms      {
 
        /**
         * Wraps a string with a link to the palette.
-        * 
+        *
         * @param       string          The string to wrap in an A-tag
         * @param       string          The table name for which to open the palette.
         * @param       array           The record array
@@ -2307,7 +2464,7 @@ class t3lib_TCEforms      {
 
                $aOnClick = $this->blur().substr($palJSFunc,0,-3).'0);return false;';
 
-               $iconCode = '<a href="#" onclick="'.htmlspecialchars($aOnClick).'"'.t3lib_BEfunc::titleAttrib($table).'>'.
+               $iconCode = '<a href="#" onclick="'.htmlspecialchars($aOnClick).'" title="'.htmlspecialchars($table).'">'.
                                        $header.
                                        '</a>';
                return $retFunc ? array($iconCode,$palJSFunc) : $iconCode;
@@ -2315,7 +2472,7 @@ class t3lib_TCEforms      {
 
        /**
         * Creates checkbox parameters
-        * 
+        *
         * @param       string          Form element name
         * @param       integer         The value of the checkbox (representing checkboxes with the bits)
         * @param       integer         Checkbox # (0-9?)
@@ -2333,7 +2490,7 @@ class t3lib_TCEforms      {
 
        /**
         * Returns element reference for form element name
-        * 
+        *
         * @param       string          Form element name
         * @return      string          Form element reference (JS)
         */
@@ -2343,10 +2500,10 @@ class t3lib_TCEforms    {
 
        /**
         * Returns the "No title" string if the input $str is empty.
-        * 
+        *
         * @param       string          The string which - if empty - will become the no-title string.
         * @param       array           Array with wrappin parts for the no-title output (in keys [0]/[1])
-        * @return      string          
+        * @return      string
         */
        function noTitle($str,$wrapParts=array())       {
                return strcmp($str,'') ? $str : $wrapParts[0].'['.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.no_title').']'.$wrapParts[1];
@@ -2354,7 +2511,7 @@ class t3lib_TCEforms      {
 
        /**
         * Returns 'this.blur();' string, if supported.
-        * 
+        *
         * @return      string          If the current browser supports styles, the string 'this.blur();' is returned.
         */
        function blur() {
@@ -2362,9 +2519,18 @@ class t3lib_TCEforms     {
        }
 
        /**
+        * Returns the "returnUrl" of the form. Can be set externally or will be taken from "t3lib_div::linkThisScript()"
+        *
+        * @return      string          Return URL of current script
+        */
+       function thisReturnUrl()        {
+               return $this->returnUrl ? $this->returnUrl : t3lib_div::linkThisScript();
+       }
+
+       /**
         * Returns the form field for a single HIDDEN field.
         * (Not used anywhere...?)
-        * 
+        *
         * @param       string          Table name
         * @param       string          Field name
         * @param       array           The row
@@ -2383,11 +2549,11 @@ class t3lib_TCEforms    {
                        $out = $item;
                }
                return $out;
-       }       
+       }
 
        /**
         * Returns parameters to set the width for a <input>-element
-        * 
+        *
         * @param       integer         The abstract size value (1-48)
         * @param       boolean         If this is for a text area.
         * @return      string          Either a "style" attribute string or "cols"/"size" attribute string.
@@ -2408,7 +2574,7 @@ class t3lib_TCEforms      {
 
        /**
         * Returns parameters to set with for a textarea field
-        * 
+        *
         * @param       integer         The abstract width (1-48)
         * @param       string          Empty or "off" (text wrapping in the field or not)
         * @return      string          The "cols" attribute string (or style from formWidth())
@@ -2425,7 +2591,7 @@ class t3lib_TCEforms      {
 
        /**
         * Get style CSS values for the current field type.
-        * 
+        *
         * @param       string          Field type (eg. "check", "radio", "select")
         * @return      string          CSS attributes
         */
@@ -2440,10 +2606,10 @@ class t3lib_TCEforms    {
                        }
                }
        }
-       
+
        /**
         * Return default "style" attribute line.
-        * 
+        *
         * @param       string          Field type (eg. "check", "radio", "select")
         * @return      string          CSS attributes
         */
@@ -2455,15 +2621,15 @@ class t3lib_TCEforms    {
        }
 
 
-       
-       
-       
-       
-       
-       
-       
-       
-       
+
+
+
+
+
+
+
+
+
 
        /************************************************************
         *
@@ -2474,7 +2640,7 @@ class t3lib_TCEforms      {
        /**
         * Initialize item array (for checkbox, selectorbox, radio buttons)
         * Will resolve the label value.
-        * 
+        *
         * @param       array           The "columns" array for the field (from TCA)
         * @return      array           An array of arrays with three elements; label, value, icon
         */
@@ -2491,7 +2657,7 @@ class t3lib_TCEforms      {
 
        /**
         * Merges items into an item-array
-        * 
+        *
         * @param       array           The existing item array
         * @param       array           An array of items to add. NOTICE: The keys are mapped to values, and the values and mapped to be labels. No possibility of adding an icon.
         * @return      array           The updated $item array
@@ -2509,7 +2675,7 @@ class t3lib_TCEforms      {
 
        /**
         * Perform user processing of the items arrays of checkboxes, selectorboxes and radio buttons.
-        * 
+        *
         * @param       array           The array of items (label,value,icon)
         * @param       array           The "itemsProcFunc." from fieldTSconfig of the field.
         * @param       array           The config array for the field.
@@ -2520,7 +2686,7 @@ class t3lib_TCEforms      {
         */
        function procItems($items,$iArray,$config,$table,$row,$field)   {
                global $TCA;
-               
+
                $params=array();
                $params['items'] = &$items;
                $params['config'] = $config;
@@ -2528,14 +2694,14 @@ class t3lib_TCEforms    {
                $params['table'] = $table;
                $params['row'] = $row;
                $params['field'] = $field;
-       
+
                t3lib_div::callUserFunction($config['itemsProcFunc'],$params,$this);
                return $items;
        }
-       
+
        /**
-        * addSelect options
-        * 
+        * Add selector box items of more exotic kinds.
+        *
         * @param       array           The array of items (label,value,icon)
         * @param       array           The "columns" array for the field (from TCA)
         * @param       array           TSconfig for the table/row
@@ -2544,7 +2710,7 @@ class t3lib_TCEforms      {
         */
        function addSelectOptionsToItemArray($items,$fieldValue,$TSconfig,$field)       {
                global $TCA;
-                       
+
                        // Values from foreign tables:
                if ($fieldValue['config']['foreign_table'])     {
                        $items = $this->foreignTable($items,$fieldValue,$TSconfig,$field);
@@ -2611,10 +2777,10 @@ class t3lib_TCEforms    {
                        // Return the items:
                return $items;
        }
-       
+
        /**
         * Creates value/label pair for a backend module (main and sub)
-        * 
+        *
         * @param       string          The module key
         * @return      string          The rawurlencoded 2-part string to transfer to interface
         * @access private
@@ -2627,23 +2793,23 @@ class t3lib_TCEforms    {
                if (count($pp)>1)       $label.=$GLOBALS['LANG']->moduleLabels['tabs'][$pp[0].'_tab'].'>';
                        // Add modules own label now:
                $label.= $GLOBALS['LANG']->moduleLabels['tabs'][$value.'_tab'];
-               
+
                return $label;
        }
-       
+
        /**
         * Adds records from a foreign table (for selector boxes)
-        * 
+        *
         * @param       array           The array of items (label,value,icon)
         * @param       array           The 'columns' array for the field (from TCA)
         * @param       array           TSconfig for the table/row
         * @param       string          The fieldname
         * @param       boolean         If set, then we are fetching the 'neg_' foreign tables.
         * @return      array           The $items array modified.
-        * @see addSelectOptionsToItemArray(), t3lib_BEfunc::foreign_table_where_query()
+        * @see addSelectOptionsToItemArray(), t3lib_BEfunc::exec_foreign_table_where_query()
         */
        function foreignTable($items,$fieldValue,$TSconfig,$field,$pFFlag=0)    {
-               global $TCA;    
+               global $TCA;
 
                        // Init:
                $pF=$pFFlag?'neg_':'';
@@ -2651,24 +2817,23 @@ class t3lib_TCEforms    {
                $uidPre = $pFFlag?'-':'';
 
                        // Get query:
-               $query= t3lib_BEfunc::foreign_table_where_query($fieldValue,$field,$TSconfig,$pF);
+               $res = t3lib_BEfunc::exec_foreign_table_where_query($fieldValue,$field,$TSconfig,$pF);
 
                        // Perform lookup
-               $res = @mysql (TYPO3_db, $query);
-               if (mysql_error())      { 
-                       debug(array(mysql_error()."\n\nQuery:\n ".$query."\n\nThis may indicate a table defined in tables.php is not existing in the database!"));
-                       exit;
+               if ($GLOBALS['TYPO3_DB']->sql_error())  {
+                       echo($GLOBALS['TYPO3_DB']->sql_error()."\n\nThis may indicate a table defined in tables.php is not existing in the database!");
+                       return array();
                }
-               
+
                        // Get label prefix.
                $lPrefix = $this->sL($fieldValue['config'][$pF.'foreign_table_prefix']);
 
                        // Get icon field + path if any:
                $iField = $TCA[$f_table]['ctrl']['selicon_field'];
                $iPath = trim($TCA[$f_table]['ctrl']['selicon_field_path']);
-               
+
                        // Traverse the selected rows to add them:
-               while ($row = mysql_fetch_assoc($res))  {
+               while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))      {
                                // Prepare the icon if available:
                        if ($iField && $iPath && $row[$iField]) {
                                $iParts = t3lib_div::trimExplode(',',$row[$iField],1);
@@ -2676,13 +2841,13 @@ class t3lib_TCEforms    {
                        } else $icon='';
                                // Add the item:
                        $items[] = array(
-                               t3lib_div::fixed_lgd($lPrefix.strip_tags(t3lib_BEfunc::getRecordTitle($f_table,$row)),$this->titleLen), 
-                               $uidPre.$row['uid'], 
+                               t3lib_div::fixed_lgd($lPrefix.strip_tags(t3lib_BEfunc::getRecordTitle($f_table,$row)),$this->titleLen),
+                               $uidPre.$row['uid'],
                                $icon
                        );
                }
                return $items;
-       }       
+       }
 
 
 
@@ -2717,8 +2882,8 @@ class t3lib_TCEforms      {
        /**
         * Sets the fancy front-end design of the editor.
         * Frontend
-        * 
-        * @return      void            
+        *
+        * @return      void
         */
        function setFancyDesign()       {
                $this->fieldTemplate='
@@ -2728,7 +2893,7 @@ class t3lib_TCEforms      {
        <tr>
                <td nowrap="nowrap" bgcolor="#ABBBB4"><img name="req_###FIELD_TABLE###_###FIELD_ID###_###FIELD_FIELD###" src="clear.gif" width="10" height="10" alt="" /><img name="cm_###FIELD_TABLE###_###FIELD_ID###_###FIELD_FIELD###" src="clear.gif" width="7" height="10" alt="" /><font face="verdana" size="1" color="black">###FIELD_ITEM###</font>###FIELD_PAL_LINK_ICON###</td>
        </tr>   ';
-       
+
                $this->totalWrap='<table border="0" cellpadding="1" cellspacing="0" bgcolor="black"><tr><td><table border="0" cellpadding="2" cellspacing="0">|</table></td></tr></table>';
 
                $this->palFieldTemplate='
@@ -2744,15 +2909,15 @@ class t3lib_TCEforms    {
        /**
         * Sets the design to the backend design.
         * Backend
-        * 
-        * @return      void            
+        *
+        * @return      void
         */
        function setNewBEDesign()       {
                $light=0;
-               
+
                $this->totalWrap='
                <table border="0" cellspacing="0" cellpadding="0" width="'.($this->docLarge?440+150:440).'">'.
-                       '<tr bgcolor="'.t3lib_div::modifyHTMLColorAll($GLOBALS["SOBE"]->doc->bgColor2,$light).'">       
+                       '<tr bgcolor="'.t3lib_div::modifyHTMLColorAll($GLOBALS['SOBE']->doc->bgColor2,$light).'">
                                <td>&nbsp;</td>
                                <td>###RECORD_ICON### <font color="#333366"><b>###TABLE_TITLE###</b></font> ###ID_NEW_INDICATOR### - ###RECORD_LABEL###</td>
                        </tr>'.
@@ -2783,11 +2948,11 @@ class t3lib_TCEforms    {
                                <td>&nbsp;</td>
                                <td nowrap="nowrap" valign="top"><strong>###FIELD_HEADER###</strong></td>
                        </tr>';
-                       
+
                $this->sectionWrap='
                        <tr>
                                <td colspan="2"><img src="clear.gif" width="1" height="###SPACE_BEFORE###" alt="" /></td>
-                       </tr>                   
+                       </tr>
                        <tr>
                                <td colspan="2"><table ###TABLE_ATTRIBS###>###CONTENT###</table></td>
                        </tr>
@@ -2796,10 +2961,10 @@ class t3lib_TCEforms    {
 
        /**
         * This inserts the content of $inArr into the field-template
-        * 
+        *
         * @param       array           Array with key/value pairs to insert in the template.
         * @param       string          Alternative template to use instead of the default.
-        * @return      string          
+        * @return      string
         */
        function intoTemplate($inArr,$altTemplate='')   {
                                // Put into template_
@@ -2822,7 +2987,7 @@ class t3lib_TCEforms      {
         * @param       string          The field name which this element is supposed to edit
         * @param       array           The record data array where the value(s) for the field can be found
         * @param       array           An array with additional configuration options.
-        * @return array        marker array for template output
+        * @return      array           marker array for template output
         * @see function intoTemplate()
         */
        function addUserTemplateMarkers($marker,$table,$field,$row,&$PA)        {
@@ -2832,22 +2997,22 @@ class t3lib_TCEforms    {
        /**
         * Wrapping labels
         * Currently not implemented - just returns input value.
-        * 
+        *
         * @param       string          Input string.
         * @return      string          Output string.
         */
        function wrapLabels($str)       {
                return $str;
        }
-       
+
        /**
         * Wraps all the table rows into a single table.
         * Used externally from scripts like alt_doc.php and db_layout.php (which uses TCEforms...)
-        * 
+        *
         * @param       string          Code to output between table-parts; table rows
         * @param       array           The record
         * @param       string          The table name
-        * @return      string          
+        * @return      string
         */
        function wrapTotal($c,$rec,$table)      {
                $parts = $this->replaceTableWrap(explode('|',$this->totalWrap,2),$rec,$table);
@@ -2856,11 +3021,11 @@ class t3lib_TCEforms    {
 
        /**
         * This replaces markers in the total wrap
-        * 
+        *
         * @param       array           An array of template parts containing some markers.
         * @param       array           The record
         * @param       string          The table name
-        * @return      string          
+        * @return      string
         */
        function replaceTableWrap($arr,$rec,$table)     {
                global $TCA;
@@ -2872,17 +3037,17 @@ class t3lib_TCEforms    {
                        $arr[$k]=str_replace('###TABLE_TITLE###',htmlspecialchars($this->sL($TCA[$table]['ctrl']['title'])),$arr[$k]);
 
                        $titleA=t3lib_BEfunc::titleAltAttrib($this->getRecordPath($table,$rec));
-                       $arr[$k]=str_replace('###RECORD_ICON###',t3lib_iconWorks::getIconImage($table,$rec,$this->backPath,'align="absmiddle"'.$titleA),$arr[$k]);
+                       $arr[$k]=str_replace('###RECORD_ICON###',t3lib_iconWorks::getIconImage($table,$rec,$this->backPath,'class="absmiddle"'.$titleA),$arr[$k]);
                }
                return $arr;
        }
 
        /**
         * Wraps an element in the $out_array with the template row for a "section" ($this->sectionWrap)
-        * 
+        *
         * @param       array           The array with form elements stored in (passed by reference and changed!)
         * @param       integer         The pointer to the entry in the $out_array  (passed by reference and incremented!)
-        * @return      void            
+        * @return      void
         */
        function wrapBorder(&$out_array,&$out_pointer)  {
                if ($this->sectionWrap && $out_array[$out_pointer])     {
@@ -2901,9 +3066,9 @@ class t3lib_TCEforms      {
 
        /**
         * Replaces colorscheme markers in the template string
-        * 
+        *
         * @param       string          Template string with markers to be substituted.
-        * @return      string          
+        * @return      string
         */
        function rplColorScheme($inTemplate)    {
                $inTemplate = str_replace('###BGCOLOR###',$this->colorScheme[0]?' bgcolor="'.$this->colorScheme[0].'"':'',$inTemplate);
@@ -2915,21 +3080,21 @@ class t3lib_TCEforms    {
        /**
         * Returns divider.
         * Currently not implemented and returns only blank value.
-        * 
-        * @return      string          
+        *
+        * @return      string
         */
        function getDivider()   {
-               //return "<HR>";
+               //return "<hr />";
        }
 
        /**
         * Creates HTML output for a palette
-        * 
+        *
         * @param       array           The palette array to print
         * @return      string          HTML output
         */
        function printPalette($palArr)  {
-               $out="";
+               $out='';
                reset($palArr);
                $bgColor=' bgcolor="'.$this->colorScheme[2].'"';
                while(list(,$content)=each($palArr))    {
@@ -2951,11 +3116,11 @@ class t3lib_TCEforms    {
                $out='<table border="0" cellpadding="0" cellspacing="0">
                        <tr>
                                <td><img src="clear.gif" width="'.intval($this->paletteMargin).'" height="1" alt="" /></td>'.
-                                       implode("",$hRow).'
+                                       implode('',$hRow).'
                        </tr>
                        <tr>
                                <td></td>'.
-                               implode("",$iRow).'
+                               implode('',$iRow).'
                        </tr>
                </table>';
 
@@ -2964,7 +3129,7 @@ class t3lib_TCEforms      {
 
        /**
         * Returns help-text ICON if configured for.
-        * 
+        *
         * @param       string          The table name
         * @param       string          The field name
         * @param       boolean         Force the return of the help-text icon.
@@ -2974,17 +3139,17 @@ class t3lib_TCEforms    {
                if ($this->globalShowHelp && $GLOBALS['TCA_DESCR'][$table]['columns'][$field] && (($this->edit_showFieldHelp=='icon'&&!$this->doLoadTableDescr($table)) || $force))     {
                        $aOnClick = 'vHWin=window.open(\''.$this->backPath.'view_help.php?tfID='.($table.'.'.$field).'\',\'viewFieldHelp\',\'height=300,width=250,status=0,menubar=0,scrollbars=1\');vHWin.focus();return false;';
                        return '<a href="#" onclick="'.htmlspecialchars($aOnClick).'">'.
-                                       '<img src="'.$this->backPath.'gfx/helpbubble.gif" width="14" height="14" hspace="2" border="0" align="absmiddle"'.($GLOBALS['CLIENT']['FORMSTYLE']?' style="cursor:help;"':'').' alt="" />'.
+                                       '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/helpbubble.gif','width="14" height="14"').' hspace="2" border="0" class="absmiddle"'.($GLOBALS['CLIENT']['FORMSTYLE']?' style="cursor:help;"':'').' alt="" />'.
                                        '</a>';
                } else return '&nbsp;';
        }
 
        /**
         * Returns help text DESCRIPTION, if configured for.
-        * 
+        *
         * @param       string          The table name
         * @param       string          The field name
-        * @return      string          
+        * @return      string
         */
        function helpText($table,$field)        {
                if ($this->globalShowHelp && $GLOBALS['TCA_DESCR'][$table]['columns'][$field] && ($this->edit_showFieldHelp=='text' || $this->doLoadTableDescr($table)))        {
@@ -2998,15 +3163,15 @@ class t3lib_TCEforms    {
                                        '</td><td valign="top">'.
                                        $this->helpTextFontTag.
                                        $GLOBALS['LANG']->hscAndCharConv($fDat['description'],0).
-                                       '</font></td></tr></table>';            
+                                       '</font></td></tr></table>';
                }
        }
 
        /**
         * Setting the current color scheme ($this->colorScheme) based on $this->defColorScheme plus input string.
-        * 
+        *
         * @param       string          A color scheme string.
-        * @return      void            
+        * @return      void
         */
        function setColorScheme($scheme)        {
                $this->colorScheme=$this->defColorScheme;
@@ -3019,8 +3184,8 @@ class t3lib_TCEforms      {
 
        /**
         * Reset color schemes.
-        * 
-        * @return      void            
+        *
+        * @return      void
         */
        function resetSchemes() {
                $this->setColorScheme($GLOBALS['TBE_STYLES']['colorschemes'][0]);
@@ -3030,8 +3195,8 @@ class t3lib_TCEforms      {
 
        /**
         * Store current color scheme
-        * 
-        * @return      void            
+        *
+        * @return      void
         */
        function storeSchemes() {
                $this->savedSchemes['colorScheme'] = $this->colorScheme;
@@ -3041,8 +3206,8 @@ class t3lib_TCEforms      {
 
        /**
         * Restore the saved color scheme
-        * 
-        * @return      void            
+        *
+        * @return      void
         */
        function restoreSchemes()       {
                $this->colorScheme=$this->savedSchemes['colorScheme'];
@@ -3069,47 +3234,63 @@ class t3lib_TCEforms    {
         ********************************************/
 
        /**
-        * JavaScript code used for input-field evaluation.
-        * 
-        * @param       string          The identification of the form on the page.
+        * JavaScript code added BEFORE the form is drawn:
+        *
         * @return      string          A <script></script> section with JavaScript.
         */
-       function JStop($formname='forms[0]')    {
-               if (count($this->RTEwindows))   {
+       function JStop()        {
+
+               $out = '';
+
+                       // Additional top HTML:
+               if (count($this->additionalCode_pre))   {
+                       $out.= implode('
+
+                               <!-- NEXT: -->
+                       ',$this->additionalCode_pre);
+               }
+
+                       // Additional top JavaScript
+               if (count($this->additionalJS_pre))     {
                        $out.='
-                               <script type="text/javascript">
-                                       /*<![CDATA[*/
-                                               var TBE_RTE_WINDOWS=new Array();
-
-                                               function TBE_EDITOR_setRTEref(RTEobj,theField,loadContent)      {       //
-                                                       TBE_RTE_WINDOWS[theField]=RTEobj;
-                                                       if (loadContent)        {
-                                                               RTEobj.setHTML(document.'.$formname.'[theField].value);
-                                                       }
-                                               }
-                                       /*]]>*/
-                               </script>
+
+
+               <!--
+                       JavaScript in top of page (before form):
+               -->
+
+               <script type="text/javascript">
+                       /*<![CDATA[*/
+
+                       '.implode('
+
+                               // NEXT:
+                       ',$this->additionalJS_pre).'
+
+                       /*]]>*/
+               </script>
                        ';
                }
+
+                       // Return result:
                return $out;
        }
-       
+
        /**
         * JavaScript code used for input-field evaluation.
-        * 
+        *
         *              Example use:
-        *              
+        *
         *              $msg.='Distribution time (hh:mm dd-mm-yy):<br /><input type="text" name="send_mail_datetime_hr" onchange="typo3FormFieldGet(\'send_mail_datetime\', \'datetime\', \'\', 0,0);"'.$GLOBALS['TBE_TEMPLATE']->formWidth(20).' /><input type="hidden" value="'.time().'" name="send_mail_datetime" /><br />';
         *              $this->extJSCODE.='typo3FormFieldSet("send_mail_datetime", "datetime", "", 0,0);';
-        *              
+        *
         *              ... and then include the result of this function after the form
-        * 
+        *
         * @param       string          The identification of the form on the page.
         * @return      string          A <script></script> section with JavaScript.
         */
        function JSbottom($formname='forms[0]') {
-       
-                       $GLOBALS['JS_INCLUDED_jsfunc_evalfield_js']=1;
+
                                // required
                        $reqLines=array();
                        $reqLinesCheck=array();
@@ -3132,18 +3313,9 @@ class t3lib_TCEforms     {
                                $reqRangeCheck[]="                                      if (!TBE_EDITOR_checkRange(document.".$formname."['".$itemName."_list'],".$range[0].",".$range[1]."))   {OK=0;}";
                                $reqRangeSet[]="                                        if (!TBE_EDITOR_checkRange(document.".$formname."['".$itemName."_list'],".$range[0].",".$range[1]."))   {TBE_EDITOR_setImage('req_".$range['imgName']."','TBE_EDITOR_req');}";
                        }
-//     debug($reqRange);
-
-                       $RTEwinArr = array();
-                       $RTEwinArrTransfer = array();
-                       reset($this->RTEwindows);
-                       while(list(,$itemName)=each($this->RTEwindows)) {
-                               $RTEwinArr[]="                                  TBE_RTE_WINDOWS['".$itemName."']=0;";
-                               $RTEwinArrTransfer[]="                                  if(TBE_RTE_WINDOWS['".$itemName."'])    {document.".$formname."['".$itemName."'].value = TBE_RTE_WINDOWS['".$itemName."'].getHTML();}else{OK++;}";
-                       }                       
 
                        $this->TBE_EDITOR_fieldChanged_func='TBE_EDITOR_fieldChanged_fName(fName,formObj[fName+"_list"]);';
-                       
+
                        if ($this->loadMD5_JS)  {
                        $out.='
                        <script type="text/javascript" src="'.$this->backPath.'md5.js"></script>';
@@ -3152,11 +3324,11 @@ class t3lib_TCEforms    {
                        <script type="text/javascript" src="'.$this->backPath.'t3lib/jsfunc.evalfield.js"></script>
                        <script type="text/javascript">
                                /*<![CDATA[*/
-                               
-                               var TBE_EDITOR_req=new Image();         TBE_EDITOR_req.src = "'.$this->backPath.'gfx/required_h.gif"; 
-                               var TBE_EDITOR_cm=new Image();          TBE_EDITOR_cm.src = "'.$this->backPath.'gfx/content_client.gif"; 
-                               var TBE_EDITOR_sel=new Image();         TBE_EDITOR_sel.src = "'.$this->backPath.'gfx/content_selected.gif"; 
-                               var TBE_EDITOR_clear=new Image();       TBE_EDITOR_clear.src = "'.$this->backPath.'clear.gif"; 
+
+                               var TBE_EDITOR_req=new Image();         TBE_EDITOR_req.src = "'.t3lib_iconWorks::skinImg($this->backPath,'gfx/required_h.gif','',1).'";
+                               var TBE_EDITOR_cm=new Image();          TBE_EDITOR_cm.src = "'.t3lib_iconWorks::skinImg($this->backPath,'gfx/content_client.gif','',1).'";
+                               var TBE_EDITOR_sel=new Image();         TBE_EDITOR_sel.src = "'.t3lib_iconWorks::skinImg($this->backPath,'gfx/content_selected.gif','',1).'";
+                               var TBE_EDITOR_clear=new Image();       TBE_EDITOR_clear.src = "'.$this->backPath.'clear.gif";
                                var TBE_REQUIRED=new Array();
 '.implode(chr(10),$reqLines).'
 
@@ -3165,32 +3337,29 @@ class t3lib_TCEforms    {
                                var TBE_RANGE_upper=new Array();
 '.implode(chr(10),$reqRange).'
 
-'.implode(chr(10),$RTEwinArr).'                                
+                               // $this->additionalJS_post:
+'.implode(chr(10),$this->additionalJS_post).'
 
                                var TBE_EDITOR_loadTime = 0;
                                var TBE_EDITOR_isChanged = 0;
 
-                                       //
-                               function TBE_EDITOR_loginRefreshed()    {
+                               function TBE_EDITOR_loginRefreshed()    {       //
                                        var date = new Date();
                                        TBE_EDITOR_loadTime = Math.floor(date.getTime()/1000);
                                        if (top.busy && top.busy.loginRefreshed)        {top.busy.loginRefreshed();}
                                }
-                                       //
-                               function TBE_EDITOR_checkLoginTimeout() {
+                               function TBE_EDITOR_checkLoginTimeout() {       //
                                        var date = new Date();
                                        var theTime = Math.floor(date.getTime()/1000);
                                        if (theTime > TBE_EDITOR_loadTime+'.intval($GLOBALS['BE_USER']->auth_timeout_field).'-10)       {
                                                return true;
                                        }
                                }
-                                       //
-                               function TBE_EDITOR_setHiddenContent(RTEcontent,theField)       {
+                               function TBE_EDITOR_setHiddenContent(RTEcontent,theField)       {       //
                                        document.'.$formname.'[theField].value = RTEcontent;
                                        alert(document.'.$formname.'[theField].value);
                                }
-                                       //
-                               function TBE_EDITOR_fieldChanged_fName(fName,el)        {
+                               function TBE_EDITOR_fieldChanged_fName(fName,el)        {       //
                                        var idx='.(2+substr_count($this->prependFormFieldNames,'[')).';
                                        var table = TBE_EDITOR_split(fName, "[", idx);
                                        var uid = TBE_EDITOR_split(fName, "[", idx+1);
@@ -3201,15 +3370,14 @@ class t3lib_TCEforms    {
                                        field = field.substr(0,field.length-1);
                                        TBE_EDITOR_fieldChanged(table,uid,field,el);
                                }
-                                       //
-                               function TBE_EDITOR_fieldChanged(table,uid,field,el)    {
+                               function TBE_EDITOR_fieldChanged(table,uid,field,el)    {       //
                                        var theField = "'.$this->prependFormFieldNames.'["+table+"]["+uid+"]["+field+"]";
                                        TBE_EDITOR_isChanged = 1;
 
                                                // Set change image:
                                        var imgObjName = "cm_"+table+"_"+uid+"_"+field;
                                        TBE_EDITOR_setImage(imgObjName,"TBE_EDITOR_cm");
-                                       
+
                                                // Set change image
                                        if (document.'.$formname.'[theField] && document.'.$formname.'[theField].type=="select-one" && document.'.$formname.'[theField+"_selIconVal"])  {
                                                var imgObjName = "selIcon_"+table+"_"+uid+"_"+field+"_";
@@ -3217,7 +3385,7 @@ class t3lib_TCEforms      {
                                                document.'.$formname.'[theField+"_selIconVal"].value = document.'.$formname.'[theField].selectedIndex;
                                                TBE_EDITOR_setImage(imgObjName+document.'.$formname.'[theField+"_selIconVal"].value,"TBE_EDITOR_sel");
                                        }
-                                       
+
                                                // Set required flag:
                                        var imgReqObjName = "req_"+table+"_"+uid+"_"+field;
                                        if (TBE_REQUIRED[theField] && document.'.$formname.'[theField]) {
@@ -3239,43 +3407,52 @@ class t3lib_TCEforms    {
                                        ').'
                                }
                                '.($this->isPalettedoc?'
-                                       //
-                               function TBE_EDITOR_setOriginalFormFieldValue(theField) {
-                                       if ('.$this->isPalettedoc.' && '.$this->isPalettedoc.'.'.$formname.' && '.$this->isPalettedoc.'.'.$formname.'[theField]) {
-                                               '.$this->isPalettedoc.'.'.$formname.'[theField].value = document.'.$formname.'[theField].value;
+                               function TBE_EDITOR_setOriginalFormFieldValue(theField) {       //
+                                       if ('.$this->isPalettedoc.' && '.$this->isPalettedoc.'.document.'.$formname.' && '.$this->isPalettedoc.'.document.'.$formname.'[theField]) {
+                                               '.$this->isPalettedoc.'.document.'.$formname.'[theField].value = document.'.$formname.'[theField].value;
                                        }
                                }
                                ':'').'
-                                       //
-                               function TBE_EDITOR_isFormChanged(noAlert)      {
+                               function TBE_EDITOR_isFormChanged(noAlert)      {       //
                                        if (TBE_EDITOR_isChanged && !noAlert && confirm('.$GLOBALS['LANG']->JScharCode($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.fieldsChanged')).'))        {
                                                return 0;
                                        }
                                        return TBE_EDITOR_isChanged;
                                }
-                                       //
-                               function TBE_EDITOR_checkAndDoSubmit(sendAlert) {
+                               function TBE_EDITOR_checkAndDoSubmit(sendAlert) {       //
                                        if (TBE_EDITOR_checkSubmit(sendAlert))  {
                                                TBE_EDITOR_submitForm();
                                        }
                                }
-                                       //
-                               function TBE_EDITOR_checkSubmit(sendAlert)      {
+
+                               /**
+                                * Checks if the form can be submitted according to any possible restrains like required values, item numbers etc.
+                                * Returns true if the form can be submitted, otherwise false (and might issue an alert message, if "sendAlert" is 1)
+                                * If "sendAlert" is false, no error message will be shown upon false return value (if "1" then it will).
+                                * If "sendAlert" is "-1" then the function will ALWAYS return true regardless of constraints (except if login has expired) - this is used in the case where a form field change requests a form update and where it is accepted that constraints are not observed (form layout might change so other fields are shown...)
+                                */
+                               function TBE_EDITOR_checkSubmit(sendAlert)      {       //
                                        if (TBE_EDITOR_checkLoginTimeout() && confirm('.$GLOBALS['LANG']->JScharCode($this->getLL('m_refresh_login')).'))       {
                                                vHWin=window.open(\''.$this->backPath.'login_frameset.php?\',\'relogin\',\'height=300,width=400,status=0,menubar=0\');
                                                vHWin.focus();
                                                return false;
                                        }
                                        var OK=1;
-//alert();
-'.implode(chr(10),$RTEwinArrTransfer).'
+
+                                       // $this->additionalJS_post:
+'.implode(chr(10),$this->additionalJS_submit).'
+
                                        if(!OK) {
-                                               alert(unescape("SYSTEM ERROR: The Rich Text Editors ("+OK+") content could not be read. This IS an error, although it should not be regular.\nThe form is not saved. Try again.o\n\nPlease report the error to your administrator if it persists."));
+                                               if (!confirm(unescape("SYSTEM ERROR: One or more Rich Text Editors on the page could not be contacted. This IS an error, although it should not be regular.\nYou can save the form now by pressing OK, but you will loose the Rich Text Editor content if you do.\n\nPlease report the error to your administrator if it persists.")))  {
+                                                       return false;
+                                               } else {
+                                                       OK = 1;
+                                               }
                                        }
-                                       
+
 '.implode(chr(10),$reqLinesCheck).'
 '.implode(chr(10),$reqRangeCheck).'
-                                       
+
                                        if (OK || sendAlert==-1)        {
                                                return true;
                                        } else {
@@ -3283,37 +3460,32 @@ class t3lib_TCEforms    {
                                                return false;
                                        }
                                }
-                                       //
-                               function TBE_EDITOR_checkRange(el,lower,upper)  {
+                               function TBE_EDITOR_checkRange(el,lower,upper)  {       //
                                        if (el && el.length>=lower && el.length<=upper) {
                                                return true;
                                        } else {
                                                return false;
                                        }
                                }
-                                       //
-                               function TBE_EDITOR_initRequired()      {
+                               function TBE_EDITOR_initRequired()      {       //
 '.implode(chr(10),$reqLinesSet).'
 '.implode(chr(10),$reqRangeSet).'
                                }
-                                       //
-                               function TBE_EDITOR_setImage(name,imgName)      {
+                               function TBE_EDITOR_setImage(name,imgName)      {       //
                                        if (document[name]) {document[name].src = eval(imgName+".src");}
                                }
-                                       //
-                               function TBE_EDITOR_submitForm()        {
+                               function TBE_EDITOR_submitForm()        {       //
                                        '.($this->doSaveFieldName?'document.'.$this->formName."['".$this->doSaveFieldName."'].value=1;":'').'
                                        document.'.$this->formName.'.submit();
                                }
-                                       //
-                               function typoSetup      ()      {
+                               function typoSetup      ()      {       //
                                        this.passwordDummy = "********";
                                        this.decimalSign = ".";
                                }
                                var TS = new typoSetup();
                                var evalFunc = new evalFunc();
-                                       //
-                               function typo3FormFieldSet(theField, evallist, is_in, checkbox, checkboxValue)  {
+
+                               function typo3FormFieldSet(theField, evallist, is_in, checkbox, checkboxValue)  {       //
                                        if (document.'.$formname.'[theField])   {
                                                var theFObj = new evalFunc_dummy (evallist,is_in, checkbox, checkboxValue);
                                                var theValue = document.'.$formname.'[theField].value;
@@ -3326,8 +3498,7 @@ class t3lib_TCEforms      {
                                                }
                                        }
                                }
-                                       //
-                               function typo3FormFieldGet(theField, evallist, is_in, checkbox, checkboxValue, checkbox_off, checkSetValue)     {
+                               function typo3FormFieldGet(theField, evallist, is_in, checkbox, checkboxValue, checkbox_off, checkSetValue)     {       //
                                        if (document.'.$formname.'[theField])   {
                                                var theFObj = new evalFunc_dummy (evallist,is_in, checkbox, checkboxValue);
                                                if (checkbox_off)       {
@@ -3342,8 +3513,7 @@ class t3lib_TCEforms      {
                                                typo3FormFieldSet(theField, evallist, is_in, checkbox, checkboxValue);
                                        }
                                }
-                                       //
-                               function TBE_EDITOR_split(theStr1, delim, index) {      
+                               function TBE_EDITOR_split(theStr1, delim, index) {              //
                                        var theStr = ""+theStr1;
                                        var lengthOfDelim = delim.length;
                                        sPos = -lengthOfDelim;
@@ -3353,11 +3523,10 @@ class t3lib_TCEforms    {
                                                if (sPos==-1)   {return null;}
                                        }
                                        ePos = theStr.indexOf(delim, sPos+lengthOfDelim);
-                                       if(ePos == -1)  {ePos = theStr.length;} 
+                                       if(ePos == -1)  {ePos = theStr.length;}
                                        return (theStr.substring(sPos+lengthOfDelim,ePos));
                                }
-                                       //
-                               function TBE_EDITOR_palUrl(inData,fieldList,fieldNum,table,uid,isOnFocus) {     
+                               function TBE_EDITOR_palUrl(inData,fieldList,fieldNum,table,uid,isOnFocus) {             //
                                        var url = "'.$this->backPath.'alt_palette.php?inData="+inData+"&formName='.rawurlencode($this->formName).'"+"&prependFormFieldNames='.rawurlencode($this->prependFormFieldNames).'";
                                        var field = "";
                                        var theField="";
@@ -3367,14 +3536,13 @@ class t3lib_TCEforms    {
                                                if (document.'.$formname.'[theField])           url+="&rec["+field+"]="+TBE_EDITOR_rawurlencode(document.'.$formname.'[theField].value);
                                        }
                                        if (top.topmenuFrame)   {
-                                               top.topmenuFrame.document.location = url+"&backRef="+(top.content.list_frame?"top.content.list_frame":"top.content");
+                                               top.topmenuFrame.document.location = url+"&backRef="+(top.content.list_frame ? (top.content.list_frame.view_frame ? "top.content.list_frame.view_frame" : "top.content.list_frame") : "top.content");
                                        } else if (!isOnFocus) {
                                                var vHWin=window.open(url,"palette","height=300,width=200,status=0,menubar=0,scrollbars=1");
                                                vHWin.focus();
                                        }
                                }
-                                       //
-                               function TBE_EDITOR_curSelected(theField)       {
+                               function TBE_EDITOR_curSelected(theField)       {       //
                                        var fObjSel = document.'.$formname.'[theField];
                                        var retVal="";
                                        if (fObjSel && fObjSel.type=="select-multiple") {
@@ -3387,8 +3555,7 @@ class t3lib_TCEforms      {
                                        }
                                        return retVal;
                                }
-                                       //
-                               function TBE_EDITOR_rawurlencode(str,maxlen)    {
+                               function TBE_EDITOR_rawurlencode(str,maxlen)    {       //
                                        var output = str;
                                        if (maxlen)     output = output.substr(0,200);
                                        output = escape(output);
@@ -3398,8 +3565,7 @@ class t3lib_TCEforms      {
                                        output = TBE_EDITOR_str_replace("@","%40", output);
                                        return output;
                                }
-                                       //
-                               function TBE_EDITOR_str_replace(match,replace,string)   {
+                               function TBE_EDITOR_str_replace(match,replace,string)   {       //
                                        var input = ""+string;
                                        var matchStr = ""+match;
                                        if (!matchStr)  {return string;}
@@ -3420,7 +3586,7 @@ class t3lib_TCEforms      {
                                /*<![CDATA[*/
 
                                '.$this->extJSCODE.'
-                               
+
                                TBE_EDITOR_initRequired();
                                TBE_EDITOR_loginRefreshed();
                                /*]]>*/
@@ -3430,33 +3596,26 @@ class t3lib_TCEforms    {
 
        /**
         * Used to connect the db/file browser with this document and the formfields on it!
-        * 
+        *
         * @param       string          Form object reference (including "document.")
         * @return      string          JavaScript functions/code (NOT contained in a <script>-element)
         */
        function dbFileCon($formObj='document.forms[0]')        {
-               $str='  
-               
+               $str='
+
                        // ***************
                        // Used to connect the db/file browser with this document and the formfields on it!
                        // ***************
-               
+
                        var browserWin="";
-                               //
-                       function setFormValueOpenBrowser (mode,params) {
+
+                       function setFormValueOpenBrowser(mode,params) { //
                                var url = "'.$this->backPath.'browser.php?mode="+mode+"&bparams="+params;
-                               if (!browserWin)        {
-                                       browserWin = window.open(url,"Typo3WinBrowser","height=350,width="+(mode=="db"?650:600)+",status=0,menubar=0,resizable=1,scrollbars=1");
-                                       browserWin.typoWin = self;
-                                       browserWin.focus();
-                               } else {
-                                       browserWin.content.document.location=url;
-                                       browserWin.typoWin = self;
-                                       browserWin.focus();
-                               }
+
+                               browserWin = window.open(url,"Typo3WinBrowser","height=350,width="+(mode=="db"?650:600)+",status=0,menubar=0,resizable=1,scrollbars=1");
+                               browserWin.focus();
                        }
-                               //
-                       function setFormValueFromBrowseWin(fName,value,label)   {
+                       function setFormValueFromBrowseWin(fName,value,label)   {       //
                                var formObj = setFormValue_getFObj(fName)
                                if (formObj)    {
                                        fObj = formObj[fName+"_list"];
@@ -3473,24 +3632,22 @@ class t3lib_TCEforms    {
                                        if (setOK)      {
                                                fObj.length++;
                                                fObj.options[l].value=value;
-                                               fObj.options[l].text=label;
-               
+                                               fObj.options[l].text=unescape(label);
+
                                                        // Traversing list and set the hidden-field
                                                setHiddenFromList(fObj,formObj[fName]);
                                                '.$this->TBE_EDITOR_fieldChanged_func.'
                                        }
                                }
                        }
-                               //
-                       function setHiddenFromList(fObjSel,fObjHid)     {
+                       function setHiddenFromList(fObjSel,fObjHid)     {       //
                                l=fObjSel.length;
                                fObjHid.value="";
                                for (a=0;a<l;a++)       {
                                        fObjHid.value+=fObjSel.options[a].value+",";
                                }
                        }
-                               //
-                       function setFormValueManipulate(fName,type)     {
+                       function setFormValueManipulate(fName,type)     {       //
                                var formObj = setFormValue_getFObj(fName)
                                if (formObj)    {
                                        var localArray_V = new Array();
@@ -3529,37 +3686,44 @@ class t3lib_TCEforms    {
                                        '.$this->TBE_EDITOR_fieldChanged_func.'
                                }
                        }
-                               //
-                       function setFormValue_getFObj(fName)    {
+                       function setFormValue_getFObj(fName)    {       //
                                var formObj = '.$formObj.';
                                if (formObj)    {
                                        if (formObj[fName] && formObj[fName+"_list"] && formObj[fName+"_list"].type=="select-multiple") {
                                                return formObj;
-                                       } else {        
+                                       } else {
                                                alert("Formfields missing:\n fName: "+formObj[fName]+"\n fName_list:"+formObj[fName+"_list"]+"\n type:"+formObj[fName+"_list"].type+"\n fName:"+fName);
                                        }
                                }
                                return "";
                        }
-               
+
                        // END: dbFileCon parts.
-               ';      
+               ';
                return $str;
        }
 
        /**
-        * Prints necessary JS
-        * 
-        * @return      void            
+        * Prints necessary JavaScript for TCEforms (after the form HTML).
+        *
+        * @return      void
         */
        function printNeededJSFunctions()       {
                        // JS evaluation:
                $out = $this->JSbottom($this->formName);
-                       // 
-               if ($this->printNeededJS["dbFileIcons"])        {
-                       $out.= '<script type="text/javascript">
+                       //
+               if ($this->printNeededJS['dbFileIcons'])        {
+                       $out.= '
+
+
+
+                       <!--
+                               JavaScript after the form has been drawn:
+                       -->
+
+                       <script type="text/javascript">
                                /*<![CDATA[*/
-                       '.$this->dbFileCon("document.".$this->formName).'
+                       '.$this->dbFileCon('document.'.$this->formName).'
                                /*]]>*/
                        </script>';
                }
@@ -3567,9 +3731,9 @@ class t3lib_TCEforms      {
        }
 
        /**
-        * Returns for the top
-        * 
-        * @return      void            
+        * Returns necessary JavaScript for the top
+        *
+        * @return      void
         */
        function printNeededJSFunctions_top()   {
                        // JS evaluation:
@@ -3614,47 +3778,49 @@ class t3lib_TCEforms    {
 
        /**
         * Gets default record. Maybe not used anymore. FE-editor?
-        * 
-        * @param       string          Table
-        * @param       integer         PID
+        *
+        * @param       string          Database Tablename
+        * @param       integer         PID value (positive / negative)
         * @return      array           "default" row.
         */
        function getDefaultRecord($table,$pid=0)        {
                global $TCA;
                if ($TCA[$table])       {
                        t3lib_div::loadTCA($table);
-                       $row=array();
+                       $row = array();
+
                        if ($pid<0 && $TCA[$table]['ctrl']['useColumnsForDefaultValues'])       {
                                        // Fetches the previous record:
-                               $query = 'SELECT * FROM '.$table.' WHERE uid='.abs($pid).t3lib_BEfunc::deleteClause($table);
-                               $res = mysql(TYPO3_db,$query);
-                               echo mysql_error();
-                               if ($drow = mysql_fetch_assoc($res))    {
+                               $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, 'uid='.abs($pid).t3lib_BEfunc::deleteClause($table));
+                               if ($drow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))        {
                                                // Gets the list of fields to copy from the previous record.
-                                       $fArr=explode(',',$TCA[$table]['ctrl']['useColumnsForDefaultValues']);
-                                       while(list(,$theF)=each($fArr)) {
+                                       $fArr = explode(',',$TCA[$table]['ctrl']['useColumnsForDefaultValues']);
+                                       foreach($fArr as $theF) {
                                                if ($TCA[$table]['columns'][$theF])     {
-                                                       $row[$theF]=$drow[$theF];
+                                                       $row[$theF] = $drow[$theF];
                                                }
                                        }
                                }
+                               $GLOBALS['TYPO3_DB']->sql_free_result($res);
                        }
-                       reset($TCA[$table]['columns']);
-                       while(list($field,$info)=each($TCA[$table]['columns'])) {
+
+                       foreach($TCA[$table]['columns'] as $field => $info)     {
                                if (isset($info['config']['default']))  {
-                                       $row[$field]=$info['config']['default'];
+                                       $row[$field] = $info['config']['default'];
                                }
                        }
+
                        return $row;
                }
        }
 
        /**
-        * Return record path
-        * 
+        * Return record path (visually formatted, using t3lib_BEfunc::getRecordPath() )
+        *
         * @param       string          Table name
         * @param       array           Record array
         * @return      string          The record path.
+        * @see t3lib_BEfunc::getRecordPath()
         */
        function getRecordPath($table,$rec)     {
                list($tscPID,$thePidValue)=$this->getTSCpid($table,$rec['uid'],$rec['pid']);
@@ -3666,8 +3832,8 @@ class t3lib_TCEforms      {
        /**
         * Returns the select-page read-access SQL clause.
         * Returns cached string, so you can call this function as much as you like without performance loss.
-        * 
-        * @return      string          
+        *
+        * @return      string
         */
        function readPerms()    {
                if (!$this->perms_clause_set)   {
@@ -3676,10 +3842,10 @@ class t3lib_TCEforms    {
                }
                return $this->perms_clause;
        }
-       
+
        /**
         * Fetches language label for key
-        * 
+        *
         * @param       string          Language label reference, eg. 'LLL:EXT:lang/locallang_core.php:labels.blablabla'
         * @return      string          The value of the label, fetched for the current backend language.
         */
@@ -3689,10 +3855,10 @@ class t3lib_TCEforms    {
 
        /**
         * Returns language label from locallang_core.php
-        * Labels must be prefixed with either "l_" or "m_". 
+        * Labels must be prefixed with either "l_" or "m_".
         * The prefix "l_" maps to the prefix "labels." inside locallang_core.php
         * The prefix "m_" maps to the prefix "mess." inside locallang_core.php
-        * 
+        *
         * @param       string          The label key
         * @return      string          The value of the label, fetched for the current backend language.
         */
@@ -3704,19 +3870,19 @@ class t3lib_TCEforms    {
                        case 'm_':
                                return $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:mess.'.substr($str,2));
                        break;
-               } 
+               }
        }
 
        /**
         * Returns true, if the palette, $palette, is collapsed (not shown, but found in top-frame) for the table.
-        * 
+        *
         * @param       string          The table name
         * @param       integer         The palette pointer/number
-        * @return      boolean         
+        * @return      boolean
         */
        function isPalettesCollapsed($table,$palette)   {
                global $TCA;
-               
+
                if ($TCA[$table]['ctrl']['canNotCollapse']) return 0;
                if (is_array($TCA[$table]['palettes'][$palette]) && $TCA[$table]['palettes'][$palette]['canNotCollapse'])       return 0;
                return $this->palettesCollapsed;
@@ -3724,14 +3890,14 @@ class t3lib_TCEforms    {
 
        /**
         * Returns true, if the evaluation of the required-field code is OK.
-        * 
+        *
         * @param       string          The required-field code
         * @param       array           The record to evaluate
-        * @return      boolean         
+        * @return      boolean
         */
        function isDisplayCondition($displayCond,$row)  {
                $output = FALSE;
-               
+
                $parts = explode(':',$displayCond);
                switch((string)$parts[0])       {       // Type of condition:
                        case 'FIELD':
@@ -3768,17 +3934,19 @@ class t3lib_TCEforms    {
                                }
                        break;
                }
-               
+
                return $output;
        }
 
        /**
         * Return TSCpid (cached)
-        * 
-        * @param       string          Table
-        * @param       string          UID
-        * @param       string          PID
-        * @return      Return          TSCpid
+        * Using t3lib_BEfunc::getTSCpid()
+        *
+        * @param       string          Tablename
+        * @param       string          UID value
+        * @param       string          PID value
+        * @return      integer         Returns the REAL pid of the record, if possible. If both $uid and $pid is strings, then pid=-1 is returned as an error indication.
+        * @see t3lib_BEfunc::getTSCpid()
         */
        function getTSCpid($table,$uid,$pid)    {
                $key = $table.':'.$uid.':'.$pid;
@@ -3790,9 +3958,9 @@ class t3lib_TCEforms      {
 
        /**
         * Returns true if descriptions should be loaded always
-        * 
+        *
         * @param       string          Table for which to check
-        * @return      boolean         
+        * @return      boolean
         */
        function doLoadTableDescr($table)       {
                global $TCA;
@@ -3801,17 +3969,16 @@ class t3lib_TCEforms    {
 
        /**
         * Returns an array of available languages (to use for FlexForms)
-        * 
+        *
         * @param       boolean         If set, only languages which are paired with a static_info_table / static_language record will be returned.
         * @param       boolean         If set, an array entry for a default language is set.
-        * @return      array           
+        * @return      array
         */
        function getAvailableLanguages($onlyIsoCoded=1,$setDefault=1)   {
                $isL = t3lib_extMgm::isLoaded('static_info_tables');
-               
+
                        // Find all language records in the system:
-               $query = 'SELECT static_lang_isocode,title,uid FROM sys_language WHERE pid=0 AND NOT hidden '.t3lib_BEfunc::deleteClause('sys_language').' ORDER BY title';
-               $res = mysql(TYPO3_db,$query);
+               $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('static_lang_isocode,title,uid', 'sys_language', 'pid=0 AND NOT hidden'.t3lib_BEfunc::deleteClause('sys_language'), '', 'title');
 
                        // Traverse them:
                $output=array();
@@ -3822,14 +3989,14 @@ class t3lib_TCEforms    {
                                'ISOcode' => 'DEF'
                        );
                }
-               while($row=mysql_fetch_assoc($res))     {
+               while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))       {
                        $output[$row['uid']]=$row;
-                       
+
                        if ($isL && $row['static_lang_isocode'])        {
                                $rr = t3lib_BEfunc::getRecord('static_languages',$row['static_lang_isocode'],'lg_iso_2');
                                if ($rr['lg_iso_2'])    $output[$row['uid']]['ISOcode']=$rr['lg_iso_2'];
                        }
-                       
+
                        if ($onlyIsoCoded && !$output[$row['uid']]['ISOcode'])  unset($output[$row['uid']]);
                }
                return $output;
@@ -3846,24 +4013,24 @@ class t3lib_TCEforms    {
 
 /**
  * Extension class for the rendering of TCEforms in the frontend
- * 
- * @author     Kasper Skårhøj <kasper@typo3.com>
+ *
+ * @author     Kasper Skaarhoj <kasper@typo3.com>
  */
 class t3lib_TCEforms_FE extends t3lib_TCEforms {
 
        /**
         * Function for wrapping labels.
-        * 
+        *
         * @param       string          The string to wrap
-        * @return      string          
+        * @return      string
         */
        function wrapLabels($str)       {
                return '<font face="verdana" size="1" color="black">'.$str.'</font>';
        }
 
        /**
-        * Prints the palette
-        * 
+        * Prints the palette in the frontend editing (forms-on-page?)
+        *
         * @param       array           The palette array to print
         * @return      string          HTML output
         */
@@ -3890,4 +4057,4 @@ class t3lib_TCEforms_FE extends t3lib_TCEforms {
 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_tceforms.php']) {
        include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_tceforms.php']);
 }
-?>
\ No newline at end of file
+?>