[BUGFIX] Allow Tx_ as class prefix
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_tceforms.php
index 2bd17ea..c05d9b8 100644 (file)
@@ -1,37 +1,36 @@
 <?php
 /***************************************************************
-*  Copyright notice
-*
-*  (c) 1999-2010 Kasper Skaarhoj (kasperYYYY@typo3.com)
-*  All rights reserved
-*
-*  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
-*  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
-*  GNU General Public License for more details.
-*
-*  This copyright notice MUST APPEAR in all copies of the script!
-***************************************************************/
+ *  Copyright notice
+ *
+ *  (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
+ *  All rights reserved
+ *
+ *  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
+ *  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
+ *  GNU General Public License for more details.
+ *
+ *  This copyright notice MUST APPEAR in all copies of the script!
+ ***************************************************************/
 /**
  * Contains TYPO3 Core Form generator - AKA "TCEforms"
  *
- * $Id$
- * Revised for TYPO3 3.6 August/2003 by Kasper Skaarhoj
+ * Revised for TYPO3 3.6 August/2003 by Kasper Skårhøj
  * XHTML compliant
  *
- * @author     Kasper Skaarhoj <kasperYYYY@typo3.com>
+ * @author     Kasper Skårhøj <kasperYYYY@typo3.com>
  */
 /**
  * [CLASS/FUNCTION INDEX of SCRIPT]
  *
  *
  *  196: class t3lib_TCEforms
- *  302:     function t3lib_TCEforms()
- *  338:     function initDefaultBEmode()
+ *  302:        function t3lib_TCEforms()
+ *  338:        function initDefaultBEmode()
  *
- *              SECTION: Rendering the forms, fields etc
- *  385:     function getSoloField($table,$row,$theFieldToReturn)
- *  424:     function getMainFields($table,$row,$depth=0)
- *  618:     function getListedFields($table,$row,$list)
- *  660:     function getPaletteFields($table,$row,$palette,$header='',$itemList='',$collapsedHeader='')
- *  737:     function getSingleField($table,$field,$row,$altName='',$palette=0,$extra='',$pal=0)
- *  900:     function getSingleField_SW($table,$field,$row,&$PA)
+ *                       SECTION: Rendering the forms, fields etc
+ *  385:        function getSoloField($table,$row,$theFieldToReturn)
+ *  424:        function getMainFields($table,$row,$depth=0)
+ *  618:        function getListedFields($table,$row,$list)
+ *  660:        function getPaletteFields($table,$row,$palette,$header='',$itemList='',$collapsedHeader='')
+ *  737:        function getSingleField($table,$field,$row,$altName='',$palette=0,$extra='',$pal=0)
+ *  900:        function getSingleField_SW($table,$field,$row,&$PA)
  *
- *              SECTION: Rendering of each TCEform field type
- *  976:     function getSingleField_typeInput($table,$field,$row,&$PA)
- * 1057:     function getSingleField_typeText($table,$field,$row,&$PA)
- * 1178:     function getSingleField_typeCheck($table,$field,$row,&$PA)
- * 1244:     function getSingleField_typeRadio($table,$field,$row,&$PA)
- * 1279:     function getSingleField_typeSelect($table,$field,$row,&$PA)
- * 1359:     function getSingleField_typeSelect_single($table,$field,$row,&$PA,$config,$selItems,$nMV_label)
- * 1490:     function getSingleField_typeSelect_checkbox($table,$field,$row,&$PA,$config,$selItems,$nMV_label)
- * 1609:     function getSingleField_typeSelect_singlebox($table,$field,$row,&$PA,$config,$selItems,$nMV_label)
- * 1719:     function getSingleField_typeSelect_multiple($table,$field,$row,&$PA,$config,$selItems,$nMV_label)
- * 1823:     function getSingleField_typeGroup($table,$field,$row,&$PA)
- * 1992:     function getSingleField_typeNone($table,$field,$row,&$PA)
- * 2008:     function getSingleField_typeNone_render($config,$itemValue)
- * 2070:     function getSingleField_typeFlex($table,$field,$row,&$PA)
- * 2205:     function getSingleField_typeFlex_langMenu($languages,$elName,$selectedLanguage,$multi=1)
- * 2224:     function getSingleField_typeFlex_sheetMenu($sArr,$elName,$sheetKey)
- * 2259:     function getSingleField_typeFlex_draw($dataStruct,$editData,$cmdData,$table,$field,$row,&$PA,$formPrefix='',$level=0,$tRows=array())
- * 2452:     function getSingleField_typeUnknown($table,$field,$row,&$PA)
- * 2467:     function getSingleField_typeUser($table,$field,$row,&$PA)
+ *                       SECTION: Rendering of each TCEform field type
+ *  976:        function getSingleField_typeInput($table,$field,$row,&$PA)
+ * 1057:        function getSingleField_typeText($table,$field,$row,&$PA)
+ * 1178:        function getSingleField_typeCheck($table,$field,$row,&$PA)
+ * 1244:        function getSingleField_typeRadio($table,$field,$row,&$PA)
+ * 1279:        function getSingleField_typeSelect($table,$field,$row,&$PA)
+ * 1359:        function getSingleField_typeSelect_single($table,$field,$row,&$PA,$config,$selItems,$nMV_label)
+ * 1490:        function getSingleField_typeSelect_checkbox($table,$field,$row,&$PA,$config,$selItems,$nMV_label)
+ * 1609:        function getSingleField_typeSelect_singlebox($table,$field,$row,&$PA,$config,$selItems,$nMV_label)
+ * 1719:        function getSingleField_typeSelect_multiple($table,$field,$row,&$PA,$config,$selItems,$nMV_label)
+ * 1823:        function getSingleField_typeGroup($table,$field,$row,&$PA)
+ * 1992:        function getSingleField_typeNone($table,$field,$row,&$PA)
+ * 2008:        function getSingleField_typeNone_render($config,$itemValue)
+ * 2070:        function getSingleField_typeFlex($table,$field,$row,&$PA)
+ * 2205:        function getSingleField_typeFlex_langMenu($languages,$elName,$selectedLanguage,$multi=1)
+ * 2224:        function getSingleField_typeFlex_sheetMenu($sArr,$elName,$sheetKey)
+ * 2259:        function getSingleField_typeFlex_draw($dataStruct,$editData,$cmdData,$table,$field,$row,&$PA,$formPrefix='',$level=0,$tRows=array())
+ * 2452:        function getSingleField_typeUnknown($table,$field,$row,&$PA)
+ * 2467:        function getSingleField_typeUser($table,$field,$row,&$PA)
  *
- *              SECTION: Field content processing
- * 2496:     function formatValue ($config, $itemValue)
+ *                       SECTION: Field content processing
+ * 2496:        function formatValue ($config, $itemValue)
  *
- *              SECTION: "Configuration" fetching/processing functions
- * 2588:     function getRTypeNum($table,$row)
- * 2614:     function rearrange($fields)
- * 2640:     function getExcludeElements($table,$row,$typeNum)
- * 2688:     function getFieldsToAdd($table,$row,$typeNum)
- * 2713:     function mergeFieldsWithAddedFields($fields,$fieldsToAdd)
- * 2745:     function setTSconfig($table,$row,$field='')
- * 2767:     function getSpecConfForField($table,$row,$field)
- * 2788:     function getSpecConfFromString($extraString, $defaultExtras)
- * 3007:     function loadPaletteElements($table, $row, $palette, $itemList='')
+ *                       SECTION: "Configuration" fetching/processing functions
+ * 2588:        function getRTypeNum($table,$row)
+ * 2614:        function rearrange($fields)
+ * 2640:        function getExcludeElements($table,$row,$typeNum)
+ * 2688:        function getFieldsToAdd($table,$row,$typeNum)
+ * 2713:        function mergeFieldsWithAddedFields($fields,$fieldsToAdd)
+ * 2745:        function setTSconfig($table,$row,$field='')
+ * 2767:        function getSpecConfForField($table,$row,$field)
+ * 2788:        function getSpecConfFromString($extraString, $defaultExtras)
+ * 3007:        function loadPaletteElements($table, $row, $palette, $itemList='')
  *
- *              SECTION: Display of localized content etc.
- * 2816:     function registerDefaultLanguageData($table,$rec)
- * 2848:     function getLanguageOverlayRawValue($table, $row, $field, $fieldConf)
- * 2876:     function renderDefaultLanguageContent($table,$field,$row,$item)
- * 2899:     function renderDefaultLanguageDiff($table,$field,$row,$item)
+ *                       SECTION: Display of localized content etc.
+ * 2816:        function registerDefaultLanguageData($table,$rec)
+ * 2848:        function getLanguageOverlayRawValue($table, $row, $field, $fieldConf)
+ * 2876:        function renderDefaultLanguageContent($table,$field,$row,$item)
+ * 2899:        function renderDefaultLanguageDiff($table,$field,$row,$item)
  *
- *              SECTION: Form element helper functions
- * 2955:     function dbFileIcons($fName,$mode,$allowed,$itemArray,$selector='',$params=array(),$onFocus='')
- * 3108:     function getClipboardElements($allowed,$mode)
- * 3157:     function getClickMenu($str,$table,$uid='')
- * 3178:     function renderWizards($itemKinds,$wizConf,$table,$row,$field,&$PA,$itemName,$specConf,$RTE=0)
- * 3382:     function getIcon($icon)
- * 3409:     function optionTagStyle($iconString)
- * 3425:     function extractValuesOnlyFromValueLabelList($itemFormElValue)
- * 3447:     function wrapOpenPalette($header,$table,$row,$palette,$retFunc=0)
- * 3471:     function checkBoxParams($itemName,$thisValue,$c,$iCount,$addFunc='')
- * 3485:     function elName($itemName)
- * 3496:     function noTitle($str,$wrapParts=array())
- * 3505:     function blur()
- * 3514:     function thisReturnUrl()
- * 3527:     function getSingleHiddenField($table,$field,$row)
- * 3549:     function formWidth($size=48,$textarea=0)
- * 3576:     function formWidthText($size=48,$wrap='')
- * 3592:     function formElStyle($type)
- * 3603:     function formElClass($type)
- * 3614:     function formElStyleClassValue($type, $class=FALSE)
- * 3638:     function insertDefStyle($type)
- * 3657:     function getDynTabMenu($parts, $idString)
+ *                       SECTION: Form element helper functions
+ * 2955:        function dbFileIcons($fName,$mode,$allowed,$itemArray,$selector='',$params=array(),$onFocus='')
+ * 3108:        function getClipboardElements($allowed,$mode)
+ * 3157:        function getClickMenu($str,$table,$uid='')
+ * 3178:        function renderWizards($itemKinds,$wizConf,$table,$row,$field,&$PA,$itemName,$specConf,$RTE=0)
+ * 3382:        function getIcon($icon)
+ * 3409:        function optionTagStyle($iconString)
+ * 3425:        function extractValuesOnlyFromValueLabelList($itemFormElValue)
+ * 3447:        function wrapOpenPalette($header,$table,$row,$palette,$retFunc=0)
+ * 3471:        function checkBoxParams($itemName,$thisValue,$c,$iCount,$addFunc='')
+ * 3485:        function elName($itemName)
+ * 3496:        function noTitle($str,$wrapParts=array())
+ * 3505:        function blur()
+ * 3514:        function thisReturnUrl()
+ * 3527:        function getSingleHiddenField($table,$field,$row)
+ * 3549:        function formWidth($size=48,$textarea=0)
+ * 3576:        function formWidthText($size=48,$wrap='')
+ * 3592:        function formElStyle($type)
+ * 3603:        function formElClass($type)
+ * 3614:        function formElStyleClassValue($type, $class=FALSE)
+ * 3638:        function insertDefStyle($type)
+ * 3657:        function getDynTabMenu($parts, $idString)
  *
- *              SECTION: Item-array manipulation functions (check/select/radio)
- * 3696:     function initItemArray($fieldValue)
- * 3714:     function addItems($items,$iArray)
- * 3736:     function procItems($items,$iArray,$config,$table,$row,$field)
- * 3760:     function addSelectOptionsToItemArray($items,$fieldValue,$TSconfig,$field)
- * 3980:     function addSelectOptionsToItemArray_makeModuleData($value)
- * 4002:     function foreignTable($items,$fieldValue,$TSconfig,$field,$pFFlag=0)
+ *                       SECTION: Item-array manipulation functions (check/select/radio)
+ * 3696:        function initItemArray($fieldValue)
+ * 3714:        function addItems($items,$iArray)
+ * 3736:        function procItems($items,$iArray,$config,$table,$row,$field)
+ * 3760:        function addSelectOptionsToItemArray($items,$fieldValue,$TSconfig,$field)
+ * 3980:        function addSelectOptionsToItemArray_makeModuleData($value)
+ * 4002:        function foreignTable($items,$fieldValue,$TSconfig,$field,$pFFlag=0)
  *
- *              SECTION: Template functions
- * 4083:     function setNewBEDesign()
- * 4138:     function intoTemplate($inArr,$altTemplate='')
- * 4162:     function addUserTemplateMarkers($marker,$table,$field,$row,&$PA)
- * 4173:     function wrapLabels($str)
- * 4186:     function wrapTotal($c,$rec,$table)
- * 4199:     function replaceTableWrap($arr,$rec,$table)
- * 4236:     function wrapBorder(&$out_array,&$out_pointer)
- * 4258:     function rplColorScheme($inTemplate)
- * 4278:     function getDivider()
- * 4288:     function printPalette($palArr)
- * 4339:     function helpTextIcon($table,$field,$force=0)
- * 4359:     function helpText($table,$field)
- * 4380:     function setColorScheme($scheme)
- * 4404:     function resetSchemes()
- * 4415:     function storeSchemes()
- * 4427:     function restoreSchemes()
+ *                       SECTION: Template functions
+ * 4083:        function setNewBEDesign()
+ * 4138:        function intoTemplate($inArr,$altTemplate='')
+ * 4162:        function addUserTemplateMarkers($marker,$table,$field,$row,&$PA)
+ * 4173:        function wrapLabels($str)
+ * 4186:        function wrapTotal($c,$rec,$table)
+ * 4199:        function replaceTableWrap($arr,$rec,$table)
+ * 4236:        function wrapBorder(&$out_array,&$out_pointer)
+ * 4258:        function rplColorScheme($inTemplate)
+ * 4278:        function getDivider()
+ * 4288:        function printPalette($palArr)
+ * 4339:        function helpTextIcon($table,$field,$force=0)
+ * 4359:        function helpText($table,$field)
+ * 4380:        function setColorScheme($scheme)
+ * 4404:        function resetSchemes()
+ * 4415:        function storeSchemes()
+ * 4427:        function restoreSchemes()
  *
- *              SECTION: JavaScript related functions
- * 4457:     function JStop()
- * 4508:     function JSbottom($formname='forms[0]')
- * 4835:     function dbFileCon($formObj='document.forms[0]')
- * 5053:     function printNeededJSFunctions()
- * 5080:     function printNeededJSFunctions_top()
+ *                       SECTION: JavaScript related functions
+ * 4457:        function JStop()
+ * 4508:        function JSbottom($formname='forms[0]')
+ * 4835:        function dbFileCon($formObj='document.forms[0]')
+ * 5053:        function printNeededJSFunctions()
+ * 5080:        function printNeededJSFunctions_top()
  *
- *              SECTION: Various helper functions
- * 5128:     function getDefaultRecord($table,$pid=0)
- * 5167:     function getRecordPath($table,$rec)
- * 5181:     function readPerms()
- * 5195:     function sL($str)
- * 5208:     function getLL($str)
- * 5229:     function isPalettesCollapsed($table,$palette)
- * 5245:     function isDisplayCondition($displayCond,$row,$ffValueKey='')
- * 5349:     function getTSCpid($table,$uid,$pid)
- * 5363:     function doLoadTableDescr($table)
- * 5375:     function getAvailableLanguages($onlyIsoCoded=1,$setDefault=1)
+ *                       SECTION: Various helper functions
+ * 5128:        function getDefaultRecord($table,$pid=0)
+ * 5167:        function getRecordPath($table,$rec)
+ * 5181:        function readPerms()
+ * 5195:        function sL($str)
+ * 5208:        function getLL($str)
+ * 5229:        function isPalettesCollapsed($table,$palette)
+ * 5245:        function isDisplayCondition($displayCond,$row,$ffValueKey='')
+ * 5349:        function getTSCpid($table,$uid,$pid)
+ * 5363:        function doLoadTableDescr($table)
+ * 5375:        function getAvailableLanguages($onlyIsoCoded=1,$setDefault=1)
  *
  *
  * 5417: class t3lib_TCEforms_FE extends t3lib_TCEforms
- * 5425:     function wrapLabels($str)
- * 5435:     function printPalette($palArr)
- * 5460:     function setFancyDesign()
+ * 5425:        function wrapLabels($str)
+ * 5435:        function printPalette($palArr)
+ * 5460:        function setFancyDesign()
  *
  * TOTAL FUNCTIONS: 100
  * (This index is automatically created/updated by the extension "extdeveval")
  */
 
 
-
-
-
-
-
-
-
-
-
-
-
-
-
 /**
  * 'TCEforms' - Class for creating the backend editing forms.
  *
- * @author     Kasper Skaarhoj <kasperYYYY@typo3.com>
- * @coauthor   Rene Fritz <r.fritz@colorcube.de>
+ * @author     Kasper Skårhøj <kasperYYYY@typo3.com>
+ * @coauthor   René Fritz <r.fritz@colorcube.de>
  * @package TYPO3
  * @subpackage t3lib
  */
-class t3lib_TCEforms   {
+class t3lib_TCEforms {
 
                // variables not commented yet.... (do so...)
        var $palFieldArr = array();
@@ -206,99 +192,98 @@ class t3lib_TCEforms      {
        var $transformedRow = array();
        var $extJSCODE = '';
        var $printNeededJS = array();
-       var $hiddenFieldAccum=array();
-       var $TBE_EDITOR_fieldChanged_func='';
-       var $loadMD5_JS=1;
-       var $prevBorderStyle='[nothing here...]';       // Something unique...
-       var $allowUpload=0;                             // If set direct upload fields will be shown
-       var $titleLen=15;                                       // @deprecated since TYPO3 4.1: $BE_USER->uc['titleLen'] but what is default??
-       var $defaultLanguageData = array();     // Array where records in the default language is stored. (processed by transferdata)
-       var $defaultLanguageData_diff = array();        // Array where records in the default language is stored (raw without any processing. used for making diff)
+       var $hiddenFieldAccum = array();
+       var $TBE_EDITOR_fieldChanged_func = '';
+       var $loadMD5_JS = 1;
+       var $prevBorderStyle = '[nothing here...]'; // Something unique...
+       var $allowUpload = 0; // If set direct upload fields will be shown
+       var $titleLen = 15; // @deprecated since TYPO3 4.1: $GLOBALS['BE_USER']->uc['titleLen'] but what is default??
+       var $defaultLanguageData = array(); // Array where records in the default language is stored. (processed by transferdata)
+       var $defaultLanguageData_diff = array(); // Array where records in the default language is stored (raw without any processing. used for making diff)
        var $additionalPreviewLanguageData = array();
 
 
                // 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 $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 (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 $localizationMode='';                       // If true, the forms are rendering only localization relevant fields of the records.
-       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 $backPath = ''; // Set this to the 'backPath' pointing back to the typo3 admin directory from the script where this form is displayed.
+       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 (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 $localizationMode = ''; // If TRUE, the forms are rendering only localization relevant fields of the records.
+       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.
 
        /**
         * Set to initialized clipboard object; Then the element browser will offer a link to paste in records from clipboard.
         *
         * @var t3lib_clipboard
         */
-       var $clipObj=FALSE;
-       var $enableClickMenu=FALSE;                     // Enable click menu on reference icons.
-       var $enableTabMenu = FALSE;                     // Enable Tab Menus. If set to true, the JavaScript content from template::getDynTabMenuJScode() must be included in the document.
-       var $renderReadonly = FALSE;            // When enabled all fields are rendered non-editable.
+       var $clipObj = FALSE;
+       var $enableClickMenu = FALSE; // Enable click menu on reference icons.
+       var $enableTabMenu = FALSE; // Enable Tab Menus.
+       var $renderReadonly = FALSE; // When enabled all fields are rendered non-editable.
 
-       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.
+       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 $prependCmdFieldNames = 'cmd';                      // The string to prepend commands for tcemain::process_cmdmap 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 $allowOverrideMatrix = array();                     // Whitelist that allows TCA field configuration to be overridden by TSconfig, @see overrideFieldConf()
-
+       var $prependFormFieldNames = 'data'; // The string to prepend formfield names with.
+       var $prependCmdFieldNames = 'cmd'; // The string to prepend commands for tcemain::process_cmdmap 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 $allowOverrideMatrix = array(); // Whitelist that allows TCA field configuration to be overridden by TSconfig, @see overrideFieldConf()
 
 
                // INTERNAL, dynamic
-       var $perms_clause='';                                           // Set by readPerms()  (caching)
-       var $perms_clause_set=0;                                        // Set by readPerms()  (caching-flag)
-       var $edit_showFieldHelp='';                                     // Used to indicate the mode of CSH (Context Sensitive Help), whether it should be icons-only ('icon'), full description ('text') or not at all (blank).
-       var $docLarge=0;                                                        // If set, the forms will be rendered a little wider, more precisely with a factor of $this->form_largeComp.
-       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 $classScheme;                                                       // Contains current class scheme
-       var $defColorScheme;                                            // Contains the default color scheme
-       var $defClassScheme;                                            // Contains the default class scheme
-       var $fieldStyle;                                                        // Contains field style values
-       var $borderStyle;                                                       // Contains border style values.
-
-       var $commentMessages=array();                           // An accumulation of messages from the class.
+       var $perms_clause = ''; // Set by readPerms()  (caching)
+       var $perms_clause_set = 0; // Set by readPerms()  (caching-flag)
+       var $edit_showFieldHelp = ''; // Used to indicate the mode of CSH (Context Sensitive Help), whether it should be icons-only ('icon'), full description ('text') or not at all (blank).
+       var $docLarge = 0; // If set, the forms will be rendered a little wider, more precisely with a factor of $this->form_largeComp.
+       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 $classScheme; // Contains current class scheme
+       var $defColorScheme; // Contains the default color scheme
+       var $defClassScheme; // Contains the default class scheme
+       var $fieldStyle; // Contains field style values
+       var $borderStyle; // Contains border style values.
+
+       var $commentMessages = array(); // An accumulation of messages from the class.
 
                // INTERNAL, templates
-       var $totalWrap='<hr />|<hr />';                         // Total wrapping for the table rows.
-       var $fieldTemplate='<strong>###FIELD_NAME###</strong><br />###FIELD_ITEM###<hr />';     // Field template
-       var $sectionWrap='';                                            // Wrapping template code for a section
-       var $palFieldTemplateHeader='';                         // Template for palette headers
-       var $palFieldTemplate='';                                       // Template for palettes
+       var $totalWrap = '<hr />|<hr />'; // Total wrapping for the table rows.
+       var $fieldTemplate = '<strong>###FIELD_NAME###</strong><br />###FIELD_ITEM###<hr />'; // Field template
+       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)
-       var $hiddenFieldListArr = array();                      // This array of fields will be set as hidden-fields instead of rendered normally! For instance palette fields edited in the top frame are set as hidden fields since the main form has to submit the values. The top frame actually just sets the value in the main form!
-       var $requiredFields=array();                            // Used to register input-field names, which are required. (Done during rendering of the fields). This information is then used later when the JavaScript is made.
-       var $requiredAdditional=array();                        // Used to register input-field names, which are required an have additional requirements (e.g. like a date/time must be positive integer). The information of this array is merged with $this->requiredFields later.
-       var $requiredElements=array();                          // Used to register the min and max number of elements for selectorboxes where that apply (in the "group" type for instance)
-       var $requiredNested=array();                            // Used to determine where $requiredFields or $requiredElements are nested (in Tabs or IRRE)
-       var $renderDepth=0;                                                     // Keeps track of the rendering depth of nested records.
-       var $savedSchemes=array();                                      // Color scheme buffer.
-       var $dynNestedStack = array();                          // holds the path an element is nested in (e.g. required for RTEhtmlarea)
+       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)
+       var $hiddenFieldListArr = array(); // This array of fields will be set as hidden-fields instead of rendered normally! For instance palette fields edited in the top frame are set as hidden fields since the main form has to submit the values. The top frame actually just sets the value in the main form!
+       var $requiredFields = array(); // Used to register input-field names, which are required. (Done during rendering of the fields). This information is then used later when the JavaScript is made.
+       var $requiredAdditional = array(); // Used to register input-field names, which are required an have additional requirements (e.g. like a date/time must be positive integer). The information of this array is merged with $this->requiredFields later.
+       var $requiredElements = array(); // Used to register the min and max number of elements for selectorboxes where that apply (in the "group" type for instance)
+       var $requiredNested = array(); // Used to determine where $requiredFields or $requiredElements are nested (in Tabs or IRRE)
+       var $renderDepth = 0; // Keeps track of the rendering depth of nested records.
+       var $savedSchemes = array(); // Color scheme buffer.
+       var $dynNestedStack = array(); // holds the path an element is nested in (e.g. required for RTEhtmlarea)
 
                // 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.
-       var $additionalJS_delete = array();                     // Additional JavaScript executed when section element is deleted. This is neceessary, for example, to correctly clean up HTMLArea RTE (bug #8232)
+       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.
+       var $additionalJS_delete = array(); // Additional JavaScript executed when section element is deleted. This is neceessary, for example, to correctly clean up HTMLArea RTE (bug #8232)
 
        /**
         * Instance of t3lib_tceforms_inline
@@ -306,12 +291,11 @@ class t3lib_TCEforms      {
         * @var t3lib_TCEforms_inline
         */
        var $inline;
-       var $hookObjectsMainFields = array();                   // Array containing hook class instances called once for a form
-       var $hookObjectsSingleField = array();                  // Array containing hook class instances called for each field
-       var $extraFormHeaders = array();                        // Rows gettings inserted into the alt_doc headers (when called from alt_doc.php)
-
-
+       var $hookObjectsMainFields = array(); // Array containing hook class instances called once for a form
+       var $hookObjectsSingleField = array(); // Array containing hook class instances called for each field
+       var $extraFormHeaders = array(); // Rows gettings inserted into the alt_doc headers (when called from alt_doc.php)
 
+       public $templateFile = ''; // Form templates, relative to typo3 directory
 
 
        /**
@@ -319,24 +303,24 @@ class t3lib_TCEforms      {
         *
         * @return      void
         */
-       function t3lib_TCEforms()       {
+       function __construct() {
                global $CLIENT, $TYPO3_CONF_VARS;
 
                $this->clientInfo = t3lib_div::clientInfo();
 
                $this->RTEenabled = $GLOBALS['BE_USER']->isRTE();
-               if (!$this->RTEenabled) {
-                       $this->RTEenabled_notReasons = implode(LF,$GLOBALS['BE_USER']->RTE_errors);
-                       $this->commentMessages[] = 'RTE NOT ENABLED IN SYSTEM due to:'.LF.$this->RTEenabled_notReasons;
+               if (!$this->RTEenabled) {
+                       $this->RTEenabled_notReasons = implode(LF, $GLOBALS['BE_USER']->RTE_errors);
+                       $this->commentMessages[] = 'RTE NOT ENABLED IN SYSTEM due to:' . LF . $this->RTEenabled_notReasons;
                }
 
                        // Default color+class scheme
                $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
-                       'black',        // Field header font color
-                       '#666666'       // Palette field header font color
+                       $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
+                       'black', // Field header font color
+                       '#666666' // Palette field header font color
                );
                $this->defColorScheme = array();
 
@@ -358,28 +342,30 @@ class t3lib_TCEforms      {
                );
 
                        // Create instance of t3lib_TCEforms_inline only if this a non-IRRE-AJAX call:
-               if (!isset($GLOBALS['ajaxID']) || strpos($GLOBALS['ajaxID'], 't3lib_TCEforms_inline::')!==0) {
+               if (!isset($GLOBALS['ajaxID']) || strpos($GLOBALS['ajaxID'], 't3lib_TCEforms_inline::') !== 0) {
                        $this->inline = t3lib_div::makeInstance('t3lib_TCEforms_inline');
                }
                        // Create instance of t3lib_TCEforms_suggest only if this a non-Suggest-AJAX call:
-               if (!isset($GLOBALS['ajaxID']) || strpos($GLOBALS['ajaxID'], 't3lib_TCEforms_suggest::')!==0) {
+               if (!isset($GLOBALS['ajaxID']) || strpos($GLOBALS['ajaxID'], 't3lib_TCEforms_suggest::') !== 0) {
                        $this->suggest = t3lib_div::makeInstance('t3lib_TCEforms_suggest');
                }
 
                        // Prepare user defined objects (if any) for hooks which extend this function:
                $this->hookObjectsMainFields = array();
-               if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tceforms.php']['getMainFieldsClass']))  {
-                       foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tceforms.php']['getMainFieldsClass'] as $classRef)   {
+               if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tceforms.php']['getMainFieldsClass'])) {
+                       foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tceforms.php']['getMainFieldsClass'] as $classRef) {
                                $this->hookObjectsMainFields[] = t3lib_div::getUserObj($classRef);
                        }
                }
                $this->hookObjectsSingleField = array();
-               if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tceforms.php']['getSingleFieldClass'])) {
-                       foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tceforms.php']['getSingleFieldClass'] as $classRef)  {
+               if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tceforms.php']['getSingleFieldClass'])) {
+                       foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tceforms.php']['getSingleFieldClass'] as $classRef) {
                                $this->hookObjectsSingleField[] = t3lib_div::getUserObj($classRef);
                        }
                }
 
+               $this->templateFile = 'templates/tceforms.html';
+
        }
 
        /**
@@ -387,37 +373,21 @@ class t3lib_TCEforms      {
         *
         * @return      void
         */
-       function initDefaultBEmode()    {
-               global $BE_USER;
+       function initDefaultBEmode() {
                $this->prependFormFieldNames = 'data';
                $this->formName = 'editform';
                $this->setNewBEDesign();
-               $this->docLarge = $BE_USER->uc['edit_wideDocument'] ? 1 : 0;
-               $this->edit_showFieldHelp = $BE_USER->uc['edit_showFieldHelp'];
+               $this->docLarge = ($GLOBALS['BE_USER']->uc['edit_wideDocument'] ? 1 : 0);
+               $this->edit_showFieldHelp = $GLOBALS['BE_USER']->uc['edit_showFieldHelp'];
 
-               $this->edit_docModuleUpload = $BE_USER->uc['edit_docModuleUpload'];
-               $this->titleLen = $BE_USER->uc['titleLen'];             // @deprecated since TYPO3 4.1
+               $this->edit_docModuleUpload = $GLOBALS['BE_USER']->uc['edit_docModuleUpload'];
+               $this->titleLen = $GLOBALS['BE_USER']->uc['titleLen']; // @deprecated since TYPO3 4.1
 
                $this->inline->init($this);
                $this->suggest->init($this);
        }
 
 
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
        /*******************************************************
         *
         * Rendering the forms, fields etc
@@ -435,25 +405,23 @@ class t3lib_TCEforms      {
         * @return      string          HTML output
         * @see getMainFields()
         */
-       function getSoloField($table,$row,$theFieldToReturn)    {
-               global $TCA;
-
-               if ($TCA[$table])       {
+       function getSoloField($table, $row, $theFieldToReturn) {
+               if ($GLOBALS['TCA'][$table]) {
                        t3lib_div::loadTCA($table);
-                       $typeNum = $this->getRTypeNum($table,$row);
-                       if ($TCA[$table]['types'][$typeNum])    {
-                               $itemList = $TCA[$table]['types'][$typeNum]['showitem'];
-                               if ($itemList)  {
-                                       $fields = t3lib_div::trimExplode(',',$itemList,1);
-                                       $excludeElements = $this->excludeElements = $this->getExcludeElements($table,$row,$typeNum);
+                       $typeNum = $this->getRTypeNum($table, $row);
+                       if ($GLOBALS['TCA'][$table]['types'][$typeNum]) {
+                               $itemList = $GLOBALS['TCA'][$table]['types'][$typeNum]['showitem'];
+                               if ($itemList) {
+                                       $fields = t3lib_div::trimExplode(',', $itemList, 1);
+                                       $excludeElements = $this->excludeElements = $this->getExcludeElements($table, $row, $typeNum);
 
-                                       foreach($fields as $fieldInfo) {
-                                               $parts = explode(';',$fieldInfo);
+                                       foreach ($fields as $fieldInfo) {
+                                               $parts = explode(';', $fieldInfo);
 
                                                $theField = trim($parts[0]);
-                                               if (!in_array($theField,$excludeElements) && !strcmp($theField,$theFieldToReturn))      {
-                                                       if ($TCA[$table]['columns'][$theField]) {
-                                                               $sField = $this->getSingleField($table,$theField,$row,$parts[1],1,$parts[3],$parts[2]);
+                                               if (!in_array($theField, $excludeElements) && !strcmp($theField, $theFieldToReturn)) {
+                                                       if ($GLOBALS['TCA'][$table]['columns'][$theField]) {
+                                                               $sField = $this->getSingleField($table, $theField, $row, $parts[1], 1, $parts[3], $parts[2]);
                                                                return $sField['ITEM'];
                                                        }
                                                }
@@ -473,136 +441,140 @@ class t3lib_TCEforms    {
         * @return      string          HTML output
         * @see getSoloField()
         */
-       function getMainFields($table,$row,$depth=0)    {
-               global $TCA, $TYPO3_CONF_VARS;
-
-               $this->renderDepth=$depth;
+       function getMainFields($table, $row, $depth = 0) {
+               $this->renderDepth = $depth;
 
                        // Init vars:
                $out_array = array(array());
                $out_array_meta = array(array(
-                       'title' => $this->getLL('l_generalTab')
-               ));
+                                                                       'title' => $this->getLL('l_generalTab')
+                                                               ));
 
-               $out_pointer=0;
-               $out_sheet=0;
-               $this->palettesRendered=array();
-               $this->palettesRendered[$this->renderDepth][$table]=array();
+               $out_pointer = 0;
+               $out_sheet = 0;
+               $this->palettesRendered = array();
+               $this->palettesRendered[$this->renderDepth][$table] = array();
 
                        // Hook: getMainFields_preProcess (requested by Thomas Hempel for use with the "dynaflex" extension)
-               foreach ($this->hookObjectsMainFields as $hookObj)      {
-                       if (method_exists($hookObj,'getMainFields_preProcess')) {
-                               $hookObj->getMainFields_preProcess($table,$row,$this);
+               foreach ($this->hookObjectsMainFields as $hookObj) {
+                       if (method_exists($hookObj, 'getMainFields_preProcess')) {
+                               $hookObj->getMainFields_preProcess($table, $row, $this);
                        }
                }
 
-               if ($TCA[$table])       {
+               if ($GLOBALS['TCA'][$table]) {
 
                                // Load the full TCA for the table.
                        t3lib_div::loadTCA($table);
 
                                // Get dividers2tabs setting from TCA of the current table:
-                       $dividers2tabs =& $TCA[$table]['ctrl']['dividers2tabs'];
+                       $dividers2tabs =& $GLOBALS['TCA'][$table]['ctrl']['dividers2tabs'];
 
                                // Load the description content for the table.
-                       if ($this->edit_showFieldHelp || $this->doLoadTableDescr($table))       {
+                       if ($this->edit_showFieldHelp || $this->doLoadTableDescr($table)) {
                                $GLOBALS['LANG']->loadSingleTableDescription($table);
                        }
                                // Get the current "type" value for the record.
-                       $typeNum = $this->getRTypeNum($table,$row);
+                       $typeNum = $this->getRTypeNum($table, $row);
 
                                // Find the list of fields to display:
-                       if ($TCA[$table]['types'][$typeNum])    {
-                               $itemList = $TCA[$table]['types'][$typeNum]['showitem'];
-                               if ($itemList)  {       // If such a list existed...
+                       if ($GLOBALS['TCA'][$table]['types'][$typeNum]) {
+                               $itemList = $GLOBALS['TCA'][$table]['types'][$typeNum]['showitem'];
+                               if ($itemList) { // If such a list existed...
                                                // Explode the field list and possibly rearrange the order of the fields, if configured for
-                                       $fields = t3lib_div::trimExplode(',',$itemList,1);
-                                       if ($this->fieldOrder)  {
+                                       $fields = t3lib_div::trimExplode(',', $itemList, 1);
+                                       if ($this->fieldOrder) {
                                                $fields = $this->rearrange($fields);
                                        }
 
                                                // Get excluded fields, added fiels and put it together:
-                                       $excludeElements = $this->excludeElements = $this->getExcludeElements($table,$row,$typeNum);
-                                       $fields = $this->mergeFieldsWithAddedFields($fields,$this->getFieldsToAdd($table,$row,$typeNum));
+                                       $excludeElements = $this->excludeElements = $this->getExcludeElements($table, $row, $typeNum);
+                                       $fields = $this->mergeFieldsWithAddedFields($fields, $this->getFieldsToAdd($table, $row, $typeNum));
 
                                                // If TCEforms will render a tab menu in the next step, push the name to the tab stack:
                                        $tabIdentString = '';
                                        $tabIdentStringMD5 = '';
-                                       if (strstr($itemList, '--div--') !== false && $this->enableTabMenu && $dividers2tabs) {
-                                               $tabIdentString = 'TCEforms:'.$table.':'.$row['uid'];
+                                       if (strstr($itemList, '--div--') !== FALSE && $this->enableTabMenu && $dividers2tabs) {
+                                               $tabIdentString = 'TCEforms:' . $table . ':' . $row['uid'];
                                                $tabIdentStringMD5 = $GLOBALS['TBE_TEMPLATE']->getDynTabMenuId($tabIdentString);
                                                        // Remember that were currently working on the general tab:
                                                if (isset($fields[0]) && strpos($fields[0], '--div--') !== 0) {
-                                                       $this->pushToDynNestedStack('tab', $tabIdentStringMD5.'-1');
+                                                       $this->pushToDynNestedStack('tab', $tabIdentStringMD5 . '-1');
                                                }
                                        }
 
                                                // Traverse the fields to render:
-                                       $cc=0;
-                                       foreach($fields as $fieldInfo)  {
+                                       $cc = 0;
+                                       foreach ($fields as $fieldInfo) {
                                                        // Exploding subparts of the field configuration:
-                                               $parts = explode(';',$fieldInfo);
+                                               $parts = explode(';', $fieldInfo);
 
                                                        // Getting the style information out:
-                                               $color_style_parts = t3lib_div::trimExplode('-',$parts[4]);
-                                               if (strcmp($color_style_parts[0],''))   {
+                                               $color_style_parts = t3lib_div::trimExplode('-', $parts[4]);
+                                               if (strcmp($color_style_parts[0], '')) {
                                                        $this->setColorScheme($GLOBALS['TBE_STYLES']['colorschemes'][intval($color_style_parts[0])]);
                                                }
-                                               if (strcmp($color_style_parts[1],''))   {
+                                               if (strcmp($color_style_parts[1], '')) {
                                                        $this->fieldStyle = $GLOBALS['TBE_STYLES']['styleschemes'][intval($color_style_parts[1])];
-                                                       if (!isset($this->fieldStyle))  $this->fieldStyle = $GLOBALS['TBE_STYLES']['styleschemes'][0];
+                                                       if (!isset($this->fieldStyle)) {
+                                                               $this->fieldStyle = $GLOBALS['TBE_STYLES']['styleschemes'][0];
+                                                       }
                                                }
-                                               if (strcmp($color_style_parts[2],''))   {
-                                                       $this->wrapBorder($out_array[$out_sheet],$out_pointer);
+                                               if (strcmp($color_style_parts[2], '')) {
+                                                       $this->wrapBorder($out_array[$out_sheet], $out_pointer);
                                                        $this->borderStyle = $GLOBALS['TBE_STYLES']['borderschemes'][intval($color_style_parts[2])];
-                                                       if (!isset($this->borderStyle)) $this->borderStyle = $GLOBALS['TBE_STYLES']['borderschemes'][0];
+                                                       if (!isset($this->borderStyle)) {
+                                                               $this->borderStyle = $GLOBALS['TBE_STYLES']['borderschemes'][0];
+                                                       }
                                                }
 
                                                        // Render the field:
                                                $theField = $parts[0];
-                                               if (!in_array($theField,$excludeElements))      {
-                                                       if ($TCA[$table]['columns'][$theField]) {
-                                                               $sFieldPal='';
+                                               if (!in_array($theField, $excludeElements)) {
+                                                       if ($GLOBALS['TCA'][$table]['columns'][$theField]) {
+                                                               $sFieldPal = '';
 
-                                                               if ($parts[2] && !isset($this->palettesRendered[$this->renderDepth][$table][$parts[2]]))        {
-                                                                       $sFieldPal=$this->getPaletteFields($table,$row,$parts[2]);
+                                                               if ($parts[2] && !isset($this->palettesRendered[$this->renderDepth][$table][$parts[2]])) {
+                                                                       $sFieldPal = $this->getPaletteFields($table, $row, $parts[2]);
                                                                        $this->palettesRendered[$this->renderDepth][$table][$parts[2]] = 1;
                                                                }
-                                                               $sField = $this->getSingleField($table,$theField,$row,$parts[1],0,$parts[3],$parts[2]);
-                                                               if ($sField)    { $sField.= $sFieldPal; }
+                                                               $sField = $this->getSingleField($table, $theField, $row, $parts[1], 0, $parts[3], $parts[2]);
+                                                               if ($sField) {
+                                                                       $sField .= $sFieldPal;
+                                                               }
 
-                                                               $out_array[$out_sheet][$out_pointer].= $sField;
-                                                       } elseif ($theField=='--div--') {
-                                                               if ($cc>0)      {
-                                                                       $out_array[$out_sheet][$out_pointer].=$this->getDivider();
+                                                               $out_array[$out_sheet][$out_pointer] .= $sField;
+                                                       } elseif ($theField == '--div--') {
+                                                               if ($cc > 0) {
+                                                                       $out_array[$out_sheet][$out_pointer] .= $this->getDivider();
 
                                                                        if ($this->enableTabMenu && $dividers2tabs) {
-                                                                               $this->wrapBorder($out_array[$out_sheet],$out_pointer);
+                                                                               $this->wrapBorder($out_array[$out_sheet], $out_pointer);
                                                                                        // Remove last tab entry from the dynNestedStack:
                                                                                $out_sheet++;
                                                                                        // Remove the previous sheet from stack (if any):
-                                                                               $this->popFromDynNestedStack('tab', $tabIdentStringMD5.'-'.($out_sheet));
+                                                                               $this->popFromDynNestedStack('tab', $tabIdentStringMD5 . '-' . ($out_sheet));
                                                                                        // Remember on which sheet we're currently working:
-                                                                               $this->pushToDynNestedStack('tab', $tabIdentStringMD5.'-'.($out_sheet+1));
+                                                                               $this->pushToDynNestedStack('tab', $tabIdentStringMD5 . '-' . ($out_sheet + 1));
                                                                                $out_array[$out_sheet] = array();
                                                                                $out_array_meta[$out_sheet]['title'] = $this->sL($parts[1]);
-                                                                                       // Register newline for Tab
-                                                                               $out_array_meta[$out_sheet]['newline'] = ($parts[2] == "newline");
+                                                                                       // Register newline for Tab
+                                                                               $out_array_meta[$out_sheet]['newline'] = ($parts[2] == "newline");
                                                                        }
-                                                               } else {        // Setting alternative title for "General" tab if "--div--" is the very first element.
+                                                               } else { // Setting alternative title for "General" tab if "--div--" is the very first element.
                                                                        $out_array_meta[$out_sheet]['title'] = $this->sL($parts[1]);
                                                                                // Only add the first tab to the dynNestedStack if there are more tabs:
                                                                        if ($tabIdentString && strpos($itemList, '--div--', strlen($fieldInfo))) {
-                                                                               $this->pushToDynNestedStack('tab', $tabIdentStringMD5.'-1');
+                                                                               $this->pushToDynNestedStack('tab', $tabIdentStringMD5 . '-1');
                                                                        }
                                                                }
-                                                       } elseif($theField=='--palette--')      {
-                                                               if ($parts[2] && !isset($this->palettesRendered[$this->renderDepth][$table][$parts[2]]))        {
+                                                       } elseif ($theField == '--palette--') {
+                                                               if ($parts[2] && !isset($this->palettesRendered[$this->renderDepth][$table][$parts[2]])) {
                                                                                // render a 'header' if not collapsed
-                                                                       if ($TCA[$table]['palettes'][$parts[2]]['canNotCollapse'] AND $parts[1]) {
-                                                                               $out_array[$out_sheet][$out_pointer].=$this->getPaletteFields($table,$row,$parts[2],$this->sL($parts[1]));
+                                                                       if ($GLOBALS['TCA'][$table]['palettes'][$parts[2]]['canNotCollapse'] && $parts[1]) {
+                                                                               $out_array[$out_sheet][$out_pointer] .= $this->getPaletteFields($table, $row, $parts[2], $this->sL($parts[1]));
                                                                        } else {
-                                                                               $out_array[$out_sheet][$out_pointer].=$this->getPaletteFields($table,$row,$parts[2],'','',$this->sL($parts[1]));
+                                                                               $out_array[$out_sheet][$out_pointer] .= $this->getPaletteFields($table, $row, $parts[2], '', '', $this->sL($parts[1]));
                                                                        }
                                                                        $this->palettesRendered[$this->renderDepth][$table][$parts[2]] = 1;
                                                                }
@@ -616,61 +588,63 @@ class t3lib_TCEforms      {
                }
 
                        // Hook: getMainFields_postProcess (requested by Thomas Hempel for use with the "dynaflex" extension)
-               foreach ($this->hookObjectsMainFields as $hookObj)      {
-                       if (method_exists($hookObj,'getMainFields_postProcess'))        {
-                               $hookObj->getMainFields_postProcess($table,$row,$this);
+               foreach ($this->hookObjectsMainFields as $hookObj) {
+                       if (method_exists($hookObj, 'getMainFields_postProcess')) {
+                               $hookObj->getMainFields_postProcess($table, $row, $this);
                        }
                }
 
                        // Wrapping a border around it all:
-               $this->wrapBorder($out_array[$out_sheet],$out_pointer);
+               $this->wrapBorder($out_array[$out_sheet], $out_pointer);
 
                        // Resetting styles:
                $this->resetSchemes();
 
                        // Rendering Main palettes, if any
-               $mParr = t3lib_div::trimExplode(',',$TCA[$table]['ctrl']['mainpalette']);
+               $mParr = t3lib_div::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['mainpalette']);
                $i = 0;
-               if (count($mParr))      {
-                       foreach ($mParr as $mP) {
-                               if (!isset($this->palettesRendered[$this->renderDepth][$table][$mP]))   {
-                                       $temp_palettesCollapsed=$this->palettesCollapsed;
-                                       $this->palettesCollapsed=0;
-                                       $label = ($i==0?$this->getLL('l_generalOptions'):$this->getLL('l_generalOptions_more'));
-                                       $out_array[$out_sheet][$out_pointer].=$this->getPaletteFields($table,$row,$mP,$label);
-                                       $this->palettesCollapsed=$temp_palettesCollapsed;
+               if (count($mParr)) {
+                       foreach ($mParr as $mP) {
+                               if (!isset($this->palettesRendered[$this->renderDepth][$table][$mP])) {
+                                       $temp_palettesCollapsed = $this->palettesCollapsed;
+                                       $this->palettesCollapsed = 0;
+                                       $label = ($i == 0 ? $this->getLL('l_generalOptions') : $this->getLL('l_generalOptions_more'));
+                                       $out_array[$out_sheet][$out_pointer] .= $this->getPaletteFields($table, $row, $mP, $label);
+                                       $this->palettesCollapsed = $temp_palettesCollapsed;
                                        $this->palettesRendered[$this->renderDepth][$table][$mP] = 1;
                                }
-                               $this->wrapBorder($out_array[$out_sheet],$out_pointer);
+                               $this->wrapBorder($out_array[$out_sheet], $out_pointer);
                                $i++;
-                               if ($this->renderDepth) {
+                               if ($this->renderDepth) {
                                        $this->renderDepth--;
                                }
                        }
                }
 
                        // Return the imploded $out_array:
-               if ($out_sheet>0)       {       // There were --div-- dividers around...
+               if ($out_sheet > 0) { // There were --div-- dividers around...
 
                                // Create parts array for the tab menu:
                        $parts = array();
-                       foreach ($out_array as $idx => $sheetContent)   {
+                       foreach ($out_array as $idx => $sheetContent) {
                                $content = implode('', $sheetContent);
                                if ($content) {
-                                       // Wrap content (row) with table-tag, otherwise tab/sheet will be disabled (see getdynTabMenu() )
-                                       $content = '<table border="0" cellspacing="0" cellpadding="0" width="100%">'.$content.'</table>';
+                                               // Wrap content (row) with table-tag, otherwise tab/sheet will be disabled (see getdynTabMenu() )
+                                       $content = '<table border="0" cellspacing="0" cellpadding="0" width="100%">' . $content . '</table>';
                                }
                                $parts[$idx] = array(
                                        'label' => $out_array_meta[$idx]['title'],
                                        'content' => $content,
-                                       'newline' => $out_array_meta[$idx]['newline'],  // Newline for this tab/sheet
+                                       'newline' => $out_array_meta[$idx]['newline'], // Newline for this tab/sheet
                                );
                        }
 
                        if (count($parts) > 1) {
                                        // Unset the current level of tab menus:
-                               $this->popFromDynNestedStack('tab', $tabIdentStringMD5.'-'.($out_sheet+1));
-                               $dividersToTabsBehaviour = (isset($TCA[$table]['ctrl']['dividers2tabs']) ? $TCA[$table]['ctrl']['dividers2tabs'] : 1);
+                               $this->popFromDynNestedStack('tab', $tabIdentStringMD5 . '-' . ($out_sheet + 1));
+                               $dividersToTabsBehaviour = (isset($GLOBALS['TCA'][$table]['ctrl']['dividers2tabs'])
+                                               ? $GLOBALS['TCA'][$table]['ctrl']['dividers2tabs']
+                                               : 1);
                                $output = $this->getDynTabMenu($parts, $tabIdentString, $dividersToTabsBehaviour);
 
                        } else {
@@ -681,13 +655,13 @@ class t3lib_TCEforms      {
                        $output = '
                                <tr>
                                        <td colspan="2">
-                                       '.$output.'
+                                       ' . $output . '
                                        </td>
                                </tr>';
 
                } else {
                                // Only one, so just implode:
-                       $output = implode('',$out_array[$out_sheet]);
+                       $output = implode('', $out_array[$out_sheet]);
                }
 
                return $output;
@@ -703,31 +677,29 @@ class t3lib_TCEforms      {
         * @param       string          Commalist of fields from the table. These will be shown in the specified order in a form.
         * @return      string          TCEform elements in a string.
         */
-       function getListedFields($table,$row,$list)     {
-               global $TCA;
-
+       function getListedFields($table, $row, $list) {
                t3lib_div::loadTCA($table);
-               if ($this->edit_showFieldHelp || $this->doLoadTableDescr($table))       {
+               if ($this->edit_showFieldHelp || $this->doLoadTableDescr($table)) {
                        $GLOBALS['LANG']->loadSingleTableDescription($table);
                }
 
                $out = '';
-               $types_fieldConfig = t3lib_BEfunc::getTCAtypes($table,$row,1);
+               $types_fieldConfig = t3lib_BEfunc::getTCAtypes($table, $row, 1);
 
-               $editFieldList=array_unique(t3lib_div::trimExplode(',',$list,1));
-               foreach($editFieldList as $theFieldC)   {
-                       list($theField,$palFields) = preg_split('/\[|\]/', $theFieldC);
+               $editFieldList = array_unique(t3lib_div::trimExplode(',', $list, 1));
+               foreach ($editFieldList as $theFieldC) {
+                       list($theField, $palFields) = preg_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],0); // Don't sent palette pointer - there are no options anyways for a field-list.
-                               $out.= $sField;
-                       } elseif($theField=='--div--')  {
-                               $out.= $this->getDivider();
+                       if ($GLOBALS['TCA'][$table]['columns'][$theField]) {
+                               $parts = t3lib_div::trimExplode(';', $types_fieldConfig[$theField]['origString']);
+                               $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();
                        }
-                       if ($palFields) {
-                               $out.= $this->getPaletteFields($table,$row,'','',implode(',',t3lib_div::trimExplode('|',$palFields,1)));
+                       if ($palFields) {
+                               $out .= $this->getPaletteFields($table, $row, '', '', implode(',', t3lib_div::trimExplode('|', $palFields, 1)));
                        }
                }
 
@@ -745,8 +717,8 @@ class t3lib_TCEforms        {
         * @param       string          Optional Link text for activating a palette (when palettes does not have another form element to belong to).
         * @return      string          HTML code.
         */
-       function getPaletteFields($table,$row,$palette,$header='',$itemList='',$collapsedHeader=NULL)   {
-               if (!$this->doPrintPalette)     {
+       function getPaletteFields($table, $row, $palette, $header = '', $itemList = '', $collapsedHeader = NULL) {
+               if (!$this->doPrintPalette) {
                        return '';
                }
 
@@ -754,28 +726,44 @@ class t3lib_TCEforms      {
                $parts = $this->loadPaletteElements($table, $row, $palette, $itemList);
 
                        // Put palette together if there are fields in it:
-               if (count($parts))      {
-                       if ($header)    {
-                               $out .= $this->intoTemplate(
+               if (count($parts)) {
+
+                       $realFields = 0;
+
+                       foreach ($parts as $part) {
+                               if ($part['NAME'] !== '--linebreak--') {
+                                       $realFields++;
+                               }
+                       }
+
+                       if ($realFields > 0) {
+
+                               if ($header) {
+                                       $out .= $this->intoTemplate(
                                                array('HEADER' => htmlspecialchars($header)),
                                                $this->palFieldTemplateHeader
                                        );
-                       }
+                               }
 
-                       $collapsed = $this->isPalettesCollapsed($table,$palette);
+                               $collapsed = $this->isPalettesCollapsed($table, $palette);
 
-                       $thePalIcon = '';
-                       if ($collapsed && $collapsedHeader !== NULL) {
-                               list($thePalIcon,) = $this->wrapOpenPalette(t3lib_iconWorks::getSpriteIcon('actions-system-options-view', array('title' => htmlspecialchars($this->getLL('l_moreOptions')))), $table, $row, $palette, 1);
-                               $thePalIcon = '<span style="margin-left: 20px;">' . $thePalIcon . $collapsedHeader . '</span>';
-                       }
+                               $thePalIcon = '';
+                               if ($collapsed && $collapsedHeader !== NULL) {
+                                       list($thePalIcon,) = $this->wrapOpenPalette(
+                                               t3lib_iconWorks::getSpriteIcon(
+                                                       'actions-system-options-view',
+                                                       array('title' => htmlspecialchars($this->getLL('l_moreOptions')))
+                                               ), $table, $row, $palette, 1);
+                                       $thePalIcon = '<span style="margin-left: 20px;">' . $thePalIcon . $collapsedHeader . '</span>';
+                               }
 
-                       $paletteHtml = $this->wrapPaletteField($this->printPalette($parts), $table, $row ,$palette, $collapsed);
+                               $paletteHtml = $this->wrapPaletteField($this->printPalette($parts), $table, $row, $palette, $collapsed);
 
-                       $out .= $this->intoTemplate(
+                               $out .= $this->intoTemplate(
                                        array('PALETTE' => $thePalIcon . $paletteHtml),
                                        $this->palFieldTemplate
                                );
+                       }
                }
                return $out;
        }
@@ -792,12 +780,11 @@ class t3lib_TCEforms      {
         * @param       integer         The palette pointer.
         * @return      mixed           String (normal) or array (palettes)
         */
-       function getSingleField($table,$field,$row,$altName='',$palette=0,$extra='',$pal=0)     {
-               global $TCA,$BE_USER;
+       function getSingleField($table, $field, $row, $altName = '', $palette = 0, $extra = '', $pal = 0) {
 
                        // Hook: getSingleField_preProcess
-               foreach ($this->hookObjectsSingleField as $hookObj)     {
-                       if (method_exists($hookObj,'getSingleField_preProcess'))        {
+               foreach ($this->hookObjectsSingleField as $hookObj) {
+                       if (method_exists($hookObj, 'getSingleField_preProcess')) {
                                $hookObj->getSingleField_preProcess($table, $field, $row, $altName, $palette, $extra, $pal, $this);
                        }
                }
@@ -809,53 +796,55 @@ class t3lib_TCEforms      {
                $PA['extra'] = $extra;
                $PA['pal'] = $pal;
 
-                       // Make sure to load full $TCA array for the table:
+                       // Make sure to load full $GLOBALS['TCA'] array for the table:
                t3lib_div::loadTCA($table);
 
                        // Get the TCA configuration for the current field:
-               $PA['fieldConf'] = $TCA[$table]['columns'][$field];
-               $PA['fieldConf']['config']['form_type'] = $PA['fieldConf']['config']['form_type'] ? $PA['fieldConf']['config']['form_type'] : $PA['fieldConf']['config']['type'];       // Using "form_type" locally in this script
+               $PA['fieldConf'] = $GLOBALS['TCA'][$table]['columns'][$field];
+               $PA['fieldConf']['config']['form_type'] = $PA['fieldConf']['config']['form_type'] ? $PA['fieldConf']['config']['form_type'] : $PA['fieldConf']['config']['type']; // Using "form_type" locally in this script
 
                $skipThisField = $this->inline->skipField($table, $field, $row, $PA['fieldConf']['config']);
 
                        // Now, check if this field is configured and editable (according to excludefields + other configuration)
-               if (    is_array($PA['fieldConf']) &&
-                               !$skipThisField &&
-                               (!$PA['fieldConf']['exclude'] || $BE_USER->check('non_exclude_fields',$table.':'.$field)) &&
-                               $PA['fieldConf']['config']['form_type']!='passthrough' &&
-                               ($this->RTEenabled || !$PA['fieldConf']['config']['showIfRTE']) &&
-                               (!$PA['fieldConf']['displayCond'] || $this->isDisplayCondition($PA['fieldConf']['displayCond'],$row)) &&
-                               (!$TCA[$table]['ctrl']['languageField'] || $PA['fieldConf']['l10n_display'] || strcmp($PA['fieldConf']['l10n_mode'],'exclude') || $row[$TCA[$table]['ctrl']['languageField']]<=0) &&
-                               (!$TCA[$table]['ctrl']['languageField'] || !$this->localizationMode || $this->localizationMode===$PA['fieldConf']['l10n_cat'])
-                       )       {
-
+               if (is_array($PA['fieldConf']) &&
+                       !$skipThisField &&
+                       (!$PA['fieldConf']['exclude'] || $GLOBALS['BE_USER']->check('non_exclude_fields', $table . ':' . $field)) &&
+                       $PA['fieldConf']['config']['form_type'] != 'passthrough' &&
+                       ($this->RTEenabled || !$PA['fieldConf']['config']['showIfRTE']) &&
+                       (!$PA['fieldConf']['displayCond'] || $this->isDisplayCondition($PA['fieldConf']['displayCond'], $row)) &&
+                       (!$GLOBALS['TCA'][$table]['ctrl']['languageField'] || $PA['fieldConf']['l10n_display'] || strcmp($PA['fieldConf']['l10n_mode'], 'exclude') || $row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] <= 0) &&
+                       (!$GLOBALS['TCA'][$table]['ctrl']['languageField'] || !$this->localizationMode || $this->localizationMode === $PA['fieldConf']['l10n_cat'])
+               ) {
 
 
                                // Fetching the TSconfig for the current table/field. This includes the $row which means that
-                       $PA['fieldTSConfig'] = $this->setTSconfig($table,$row,$field);
+                       $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'])  {
+                       if (!$PA['fieldTSConfig']['disabled']) {
                                        // Override fieldConf by fieldTSconfig:
                                $PA['fieldConf']['config'] = $this->overrideFieldConf($PA['fieldConf']['config'], $PA['fieldTSConfig']);
 
                                        // 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.
-                               $PA['itemFormElID']=$this->prependFormFieldNames.'_'.$table.'_'.$row['uid'].'_'.$field;
+                               $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.
+                               $PA['itemFormElID'] = $this->prependFormFieldNames . '_' . $table . '_' . $row['uid'] . '_' . $field;
 
                                        // set field to read-only if configured for translated records to show default language content as readonly
-                               if ($PA['fieldConf']['l10n_display'] && t3lib_div::inList($PA['fieldConf']['l10n_display'], 'defaultAsReadonly') && $row[$TCA[$table]['ctrl']['languageField']] > 0) {
-                                       $PA['fieldConf']['config']['readOnly'] =  true;
-                                       $PA['itemFormElValue'] = $this->defaultLanguageData[$table.':'.$row['uid']][$field];
+                               if ($PA['fieldConf']['l10n_display']
+                                       && t3lib_div::inList($PA['fieldConf']['l10n_display'], 'defaultAsReadonly')
+                                       && $row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0) {
+                                       $PA['fieldConf']['config']['readOnly'] = TRUE;
+                                       $PA['itemFormElValue'] = $this->defaultLanguageData[$table . ':' . $row['uid']][$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))) {
-                                       if($GLOBALS['BE_USER']->jsConfirmation(1))      {
+                                       ($GLOBALS['TCA'][$table]['ctrl']['type'] && !strcmp($field, $GLOBALS['TCA'][$table]['ctrl']['type']))
+                                       || ($GLOBALS['TCA'][$table]['ctrl']['requestUpdate']
+                                               && t3lib_div::inList($GLOBALS['TCA'][$table]['ctrl']['requestUpdate'], $field))) {
+                                       if ($GLOBALS['BE_USER']->jsConfirmation(1)) {
                                                $alertMsgOnChange = 'if (confirm(TBE_EDITOR.labels.onChangeAlert) && TBE_EDITOR.checkSubmit(-1)){ TBE_EDITOR.submitForm() };';
                                        } else {
                                                $alertMsgOnChange = 'if (TBE_EDITOR.checkSubmit(-1)){ TBE_EDITOR.submitForm() };';
@@ -865,104 +854,108 @@ class t3lib_TCEforms    {
                                }
 
                                        // 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 (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['palette']) {
                                                $paletteFields = $this->loadPaletteElements($table, $row, $PA['pal']);
-                                               if ($PA['pal'] && $this->isPalettesCollapsed($table,$PA['pal']) && count($paletteFields))       {
-                                                       list($thePalIcon,$palJSfunc) = $this->wrapOpenPalette(t3lib_iconWorks::getSpriteIcon('actions-system-options-view', array('title' => htmlspecialchars($this->getLL('l_moreOptions')))),$table,$row,$PA['pal'],1);
+                                               if ($PA['pal'] && $this->isPalettesCollapsed($table, $PA['pal']) && count($paletteFields)) {
+                                                       list($thePalIcon, $palJSfunc) = $this->wrapOpenPalette(t3lib_iconWorks::getSpriteIcon('actions-system-options-view', array('title' => htmlspecialchars($this->getLL('l_moreOptions')))), $table, $row, $PA['pal'], 1);
                                                } else {
                                                        $thePalIcon = '';
                                                        $palJSfunc = '';
                                                }
                                        }
                                                // onFocus attribute to add to the field:
-                                       $PA['onFocus'] = ($palJSfunc && !$BE_USER->uc['dontShowPalettesOnFocusInAB']) ? ' onfocus="'.htmlspecialchars($palJSfunc).'"' : '';
+                                       $PA['onFocus'] = (($palJSfunc && !$GLOBALS['BE_USER']->uc['dontShowPalettesOnFocusInAB'])
+                                               ? ' onfocus="' . htmlspecialchars($palJSfunc) . '"'
+                                               : '');
 
                                                // Find item
-                                       $item='';
+                                       $item = '';
                                        $PA['label'] = ($PA['altName'] ? $PA['altName'] : $PA['fieldConf']['label']);
                                        $PA['label'] = ($PA['fieldTSConfig']['label'] ? $PA['fieldTSConfig']['label'] : $PA['label']);
                                        $PA['label'] = ($PA['fieldTSConfig']['label.'][$GLOBALS['LANG']->lang] ? $PA['fieldTSConfig']['label.'][$GLOBALS['LANG']->lang] : $PA['label']);
                                        $PA['label'] = $this->sL($PA['label']);
                                                // JavaScript code for event handlers:
-                                       $PA['fieldChangeFunc']=array();
-                                       $PA['fieldChangeFunc']['TBE_EDITOR_fieldChanged'] = "TBE_EDITOR.fieldChanged('".$table."','".$row['uid']."','".$field."','".$PA['itemFormElName']."');";
-                                       $PA['fieldChangeFunc']['alert']=$alertMsgOnChange;
+                                       $PA['fieldChangeFunc'] = array();
+                                       $PA['fieldChangeFunc']['TBE_EDITOR_fieldChanged'] = "TBE_EDITOR.fieldChanged('" . $table . "','" . $row['uid'] . "','" . $field . "','" . $PA['itemFormElName'] . "');";
+                                       $PA['fieldChangeFunc']['alert'] = $alertMsgOnChange;
                                                // if this is the child of an inline type and it is the field creating the label
                                        if ($this->inline->isInlineChildAndLabelField($table, $field)) {
                                                $inlineObjectId = implode(
                                                        t3lib_TCEforms_inline::Structure_Separator,
                                                        array(
-                                                               $this->inline->inlineNames['object'],
-                                                               $table,
-                                                               $row['uid']
+                                                                $this->inline->inlineNames['object'],
+                                                                $table,
+                                                                $row['uid']
                                                        )
                                                );
                                                $PA['fieldChangeFunc']['inline'] = "inline.handleChangedField('" . $PA['itemFormElName'] . "','" . $inlineObjectId . "');";
                                        }
 
                                                // Based on the type of the item, call a render function:
-                                       $item = $this->getSingleField_SW($table,$field,$row,$PA);
+                                       $item = $this->getSingleField_SW($table, $field, $row, $PA);
 
                                                // Add language + diff
                                        if ($PA['fieldConf']['l10n_display'] && (t3lib_div::inList($PA['fieldConf']['l10n_display'], 'hideDiff') || t3lib_div::inList($PA['fieldConf']['l10n_display'], 'defaultAsReadonly'))) {
-                                               $renderLanguageDiff = false;
+                                               $renderLanguageDiff = FALSE;
                                        } else {
-                                               $renderLanguageDiff = true;
+                                               $renderLanguageDiff = TRUE;
                                        }
 
                                        if ($renderLanguageDiff) {
-                                               $item = $this->renderDefaultLanguageContent($table,$field,$row,$item);
-                                               $item = $this->renderDefaultLanguageDiff($table,$field,$row,$item);
+                                               $item = $this->renderDefaultLanguageContent($table, $field, $row, $item);
+                                               $item = $this->renderDefaultLanguageDiff($table, $field, $row, $item);
                                        }
 
                                                // If the record has been saved and the "linkTitleToSelf" is set, we make the field name into a link, which will load ONLY this field in alt_doc.php
-                                       $PA['label'] = t3lib_div::deHSCentities(htmlspecialchars($PA['label']));
-                                       if (t3lib_div::testInt($row['uid']) && $PA['fieldTSConfig']['linkTitleToSelf'] && !t3lib_div::_GP('columnsOnly'))       {
-                                               $lTTS_url = $this->backPath.'alt_doc.php?edit['.$table.']['.$row['uid'].']=edit&columnsOnly='.$field.'&returnUrl='.rawurlencode($this->thisReturnUrl());
-                                               $PA['label'] = '<a href="'.htmlspecialchars($lTTS_url).'">'.$PA['label'].'</a>';
+                                       $label = t3lib_div::deHSCentities(htmlspecialchars($PA['label']));
+                                       if (t3lib_div::testInt($row['uid']) && $PA['fieldTSConfig']['linkTitleToSelf'] && !t3lib_div::_GP('columnsOnly')) {
+                                               $lTTS_url = $this->backPath . 'alt_doc.php?edit[' . $table . '][' . $row['uid'] . ']=edit&columnsOnly=' . $field . '&returnUrl=' . rawurlencode($this->thisReturnUrl());
+                                               $label = '<a href="' . htmlspecialchars($lTTS_url) . '">' . $label . '</a>';
                                        }
 
+                                               // wrap the label with help text
+                                       $PA['label'] = $label = t3lib_BEfunc::wrapInHelp($table, $field, $label);
+
                                                // Create output value:
-                                       if ($PA['fieldConf']['config']['form_type']=='user' && $PA['fieldConf']['config']['noTableWrapping'])   {
+                                       if ($PA['fieldConf']['config']['form_type'] == 'user' && $PA['fieldConf']['config']['noTableWrapping']) {
                                                $out = $item;
-                                       } elseif ($PA['palette'])       {
+                                       } elseif ($PA['palette']) {
                                                        // Array:
-                                               $out=array(
-                                                       'NAME'=>$PA['label'],
-                                                       'ID'=>$row['uid'],
-                                                       'FIELD'=>$field,
-                                                       'TABLE'=>$table,
-                                                       'ITEM'=>$item,
-                                                       'HELP_ICON' => $this->helpTextIcon($table,$field,1)
+                                               $out = array(
+                                                       'NAME' => $label,
+                                                       'ID' => $row['uid'],
+                                                       'FIELD' => $field,
+                                                       'TABLE' => $table,
+                                                       'ITEM' => $item
                                                );
-                                               $out = $this->addUserTemplateMarkers($out,$table,$field,$row,$PA);
+                                               $out = $this->addUserTemplateMarkers($out, $table, $field, $row, $PA);
                                        } else {
                                                        // String:
-                                               $out=array(
-                                                       'NAME'=>$PA['label'],
-                                                       'ITEM'=>$item,
-                                                       'TABLE'=>$table,
-                                                       'ID'=>$row['uid'],
-                                                       'HELP_ICON'=>$this->helpTextIcon($table,$field),
-                                                       'HELP_TEXT'=>$this->helpText($table,$field),
-                                                       'PAL_LINK_ICON'=>$thePalIcon,
-                                                       'FIELD'=>$field
+                                               $out = array(
+                                                       'NAME' => $label,
+                                                       'ITEM' => $item,
+                                                       'TABLE' => $table,
+                                                       'ID' => $row['uid'],
+                                                       'PAL_LINK_ICON' => $thePalIcon,
+                                                       'FIELD' => $field
                                                );
-                                               $out = $this->addUserTemplateMarkers($out,$table,$field,$row,$PA);
+                                               $out = $this->addUserTemplateMarkers($out, $table, $field, $row, $PA);
                                                        // String:
-                                               $out=$this->intoTemplate($out);
+                                               $out = $this->intoTemplate($out);
                                        }
                                }
-                       } else $this->commentMessages[]=$this->prependFormFieldNames.'['.$table.']['.$row['uid'].']['.$field.']: Disabled by TSconfig';
+                       } else {
+                               $this->commentMessages[] = $this->prependFormFieldNames . '[' . $table . '][' . $row['uid'] . '][' . $field . ']: Disabled by TSconfig';
+                       }
                }
                        // Hook: getSingleField_postProcess
-               foreach ($this->hookObjectsSingleField as $hookObj)     {
-                       if (method_exists($hookObj,'getSingleField_postProcess'))       {
+               foreach ($this->hookObjectsSingleField as $hookObj) {
+                       if (method_exists($hookObj, 'getSingleField_postProcess')) {
                                $hookObj->getSingleField_postProcess($table, $field, $row, $out, $PA, $this);
                        }
                }
@@ -981,49 +974,49 @@ class t3lib_TCEforms      {
         * @access private
         * @see getSingleField(), getSingleField_typeFlex_draw()
         */
-       function getSingleField_SW($table,$field,$row,&$PA)     {
-               $PA['fieldConf']['config']['form_type'] = $PA['fieldConf']['config']['form_type'] ? $PA['fieldConf']['config']['form_type'] : $PA['fieldConf']['config']['type'];       // Using "form_type" locally in this script
+       function getSingleField_SW($table, $field, $row, &$PA) {
+               $PA['fieldConf']['config']['form_type'] = $PA['fieldConf']['config']['form_type'] ? $PA['fieldConf']['config']['form_type'] : $PA['fieldConf']['config']['type']; // Using "form_type" locally in this script
 
-               // Hook: getSingleField_beforeRender
+                       // Hook: getSingleField_beforeRender
                foreach ($this->hookObjectsSingleField as $hookObject) {
                        if (method_exists($hookObject, 'getSingleField_beforeRender')) {
                                $hookObject->getSingleField_beforeRender($table, $field, $row, $PA);
                        }
                }
 
-               switch($PA['fieldConf']['config']['form_type']) {
+               switch ($PA['fieldConf']['config']['form_type']) {
                        case 'input':
-                               $item = $this->getSingleField_typeInput($table,$field,$row,$PA);
+                               $item = $this->getSingleField_typeInput($table, $field, $row, $PA);
                        break;
                        case 'text':
-                               $item = $this->getSingleField_typeText($table,$field,$row,$PA);
+                               $item = $this->getSingleField_typeText($table, $field, $row, $PA);
                        break;
                        case 'check':
-                               $item = $this->getSingleField_typeCheck($table,$field,$row,$PA);
+                               $item = $this->getSingleField_typeCheck($table, $field, $row, $PA);
                        break;
                        case 'radio':
-                               $item = $this->getSingleField_typeRadio($table,$field,$row,$PA);
+                               $item = $this->getSingleField_typeRadio($table, $field, $row, $PA);
                        break;
                        case 'select':
-                               $item = $this->getSingleField_typeSelect($table,$field,$row,$PA);
+                               $item = $this->getSingleField_typeSelect($table, $field, $row, $PA);
                        break;
                        case 'group':
-                               $item = $this->getSingleField_typeGroup($table,$field,$row,$PA);
+                               $item = $this->getSingleField_typeGroup($table, $field, $row, $PA);
                        break;
                        case 'inline':
-                               $item = $this->inline->getSingleField_typeInline($table,$field,$row,$PA);
+                               $item = $this->inline->getSingleField_typeInline($table, $field, $row, $PA);
                        break;
                        case 'none':
-                               $item = $this->getSingleField_typeNone($table,$field,$row,$PA);
+                               $item = $this->getSingleField_typeNone($table, $field, $row, $PA);
                        break;
                        case 'user':
-                               $item = $this->getSingleField_typeUser($table,$field,$row,$PA);
+                               $item = $this->getSingleField_typeUser($table, $field, $row, $PA);
                        break;
                        case 'flex':
-                               $item = $this->getSingleField_typeFlex($table,$field,$row,$PA);
+                               $item = $this->getSingleField_typeFlex($table, $field, $row, $PA);
                        break;
                        default:
-                               $item = $this->getSingleField_typeUnknown($table,$field,$row,$PA);
+                               $item = $this->getSingleField_typeUnknown($table, $field, $row, $PA);
                        break;
                }
 
@@ -1031,23 +1024,6 @@ class t3lib_TCEforms     {
        }
 
 
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
        /**********************************************************
         *
         * Rendering of each TCEform field type
@@ -1064,65 +1040,69 @@ class t3lib_TCEforms    {
         * @param       array           An array with additional configuration options.
         * @return      string          The HTML code for the TCEform field
         */
-       function getSingleField_typeInput($table,$field,$row,&$PA)      {
+       function getSingleField_typeInput($table, $field, $row, &$PA) {
                $config = $PA['fieldConf']['config'];
 
                $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);
+               $size = t3lib_div::intInRange($config['size'] ? $config['size'] : 30, 5, $this->maxInputWidth);
+               $evalList = t3lib_div::trimExplode(',', $config['eval'], 1);
                $classAndStyleAttributes = $this->formWidthAsArray($size);
 
                $fieldAppendix = '';
-               $cssClasses    = array($classAndStyleAttributes['class']);
-               $cssStyle      = $classAndStyleAttributes['style'];
+               $item = '';
+               $cssClasses = array($classAndStyleAttributes['class']);
+               $cssStyle = $classAndStyleAttributes['style'];
 
-                       // css class and id will show the kind of field
-               if (in_array('date', $evalList)) {
-                       $inputId = uniqid('tceforms-datefield-');
-                       $cssClasses[] = 'tceforms-textfield tceforms-datefield';
-                       $fieldAppendix = t3lib_iconWorks::getSpriteIcon(
-                               'actions-edit-pick-date',
-                               array(
-                                       'style' => 'cursor:pointer;',
-                                       'id' => 'picker-' . $inputId
-                               )
-                       );
+               if (!isset($config['checkbox'])) {
+                       $config['checkbox'] = '0';
+                       $checkboxIsset = FALSE;
+               } else {
+                       $checkboxIsset = TRUE;
+               }
 
-               } elseif (in_array('datetime', $evalList)) {
-                       $inputId = uniqid('tceforms-datetimefield-');
-                       $cssClasses[] = 'tceforms-textfield tceforms-datetimefield';
+               if (in_array('date', $evalList) || in_array('datetime', $evalList)) {
+                       if (in_array('datetime', $evalList)) {
+                               $class = 'datetime';
+                       } else {
+                               $class = 'date';
+                       }
+                       $dateRange = '';
+                       if (isset($config['range']['lower'])) {
+                               $dateRange .= ' lower-' . intval($config['range']['lower']);
+                       }
+                       if (isset($config['range']['upper'])) {
+                               $dateRange .= ' upper-' . intval($config['range']['upper']);
+                       }
+                       $inputId = uniqid('tceforms-' . $class . 'field-');
+                       $cssClasses[] = 'tceforms-textfield tceforms-' . $class . 'field' . $dateRange;
                        $fieldAppendix = t3lib_iconWorks::getSpriteIcon(
                                'actions-edit-pick-date',
                                array(
-                                       'style' => 'cursor:pointer;',
-                                       'id' => 'picker-' . $inputId
+                                        'style' => 'cursor:pointer;',
+                                        'id' => 'picker-' . $inputId
                                )
                        );
-
                } elseif (in_array('timesec', $evalList)) {
                        $inputId = uniqid('tceforms-timesecfield-');
                        $cssClasses[] = 'tceforms-textfield tceforms-timesecfield';
-
                } elseif (in_array('year', $evalList)) {
                        $inputId = uniqid('tceforms-yearfield-');
                        $cssClasses[] = 'tceforms-textfield tceforms-yearfield';
-
                } elseif (in_array('time', $evalList)) {
                        $inputId = uniqid('tceforms-timefield-');
                        $cssClasses[] = 'tceforms-textfield tceforms-timefield';
-
                } elseif (in_array('int', $evalList)) {
                        $inputId = uniqid('tceforms-intfield-');
                        $cssClasses[] = 'tceforms-textfield tceforms-intfield';
-
                } elseif (in_array('double2', $evalList)) {
                        $inputId = uniqid('tceforms-double2field-');
                        $cssClasses[] = 'tceforms-textfield tceforms-double2field';
-
                } else {
                        $inputId = uniqid('tceforms-textfield-');
                        $cssClasses[] = 'tceforms-textfield';
-
+                       if ($checkboxIsset === FALSE) {
+                               $config['checkbox'] = '';
+                       }
                }
                if (isset($config['wizards']['link'])) {
                        $inputId = uniqid('tceforms-linkfield-');
@@ -1133,16 +1113,16 @@ class t3lib_TCEforms    {
                        $cssClasses[] = 'tceforms-textfield tceforms-colorfield';
                }
 
-               if($this->renderReadonly || $config['readOnly'])  {
+               if ($this->renderReadonly || $config['readOnly']) {
                        $itemFormElValue = $PA['itemFormElValue'];
-                       if (in_array('date',$evalList)) {
+                       if (in_array('date', $evalList)) {
                                $config['format'] = 'date';
-                       } elseif (in_array('datetime',$evalList))       {
+                       } elseif (in_array('datetime', $evalList)) {
                                $config['format'] = 'datetime';
-                       } elseif (in_array('time',$evalList))   {
+                       } elseif (in_array('time', $evalList)) {
                                $config['format'] = 'time';
                        }
-                       if (in_array('password',$evalList))     {
+                       if (in_array('password', $evalList)) {
                                $itemFormElValue = $itemFormElValue ? '*********' : '';
                        }
                        return $this->getSingleField_typeNone_render($config, $itemFormElValue);
@@ -1151,71 +1131,77 @@ class t3lib_TCEforms    {
                foreach ($evalList as $func) {
                        switch ($func) {
                                case 'required':
-                                       $this->registerRequiredProperty('field', $table.'_'.$row['uid'].'_'.$field, $PA['itemFormElName']);
+                                       $this->registerRequiredProperty('field', $table . '_' . $row['uid'] . '_' . $field, $PA['itemFormElName']);
                                                // Mark this field for date/time disposal:
                                        if (array_intersect($evalList, array('date', 'datetime', 'time'))) {
-                                                $this->requiredAdditional[$PA['itemFormElName']]['isPositiveNumber'] = true;
+                                               $this->requiredAdditional[$PA['itemFormElName']]['isPositiveNumber'] = TRUE;
                                        }
-                                       break;
+                               break;
                                default:
-                                       if (substr($func, 0, 3) == 'tx_')       {
-                                               // Pair hook to the one in t3lib_TCEmain::checkValue_input_Eval()
-                                               $evalObj = t3lib_div::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func].':&'.$func);
-                                               if (is_object($evalObj) && method_exists($evalObj, 'deevaluateFieldValue'))     {
+                                       if (t3lib_div::hasValidClassPrefix($func)) {
+                                                       // Pair hook to the one in t3lib_TCEmain::checkValue_input_Eval()
+                                               $evalObj = t3lib_div::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func] . ':&' . $func);
+                                               if (is_object($evalObj) && method_exists($evalObj, 'deevaluateFieldValue')) {
                                                        $_params = array(
                                                                'value' => $PA['itemFormElValue']
                                                        );
                                                        $PA['itemFormElValue'] = $evalObj->deevaluateFieldValue($_params);
                                                }
                                        }
-                                       break;
+                               break;
                        }
                }
 
-               $paramsList = "'".$PA['itemFormElName']."','".implode(',',$evalList)."','".trim($config['is_in'])."',".(isset($config['checkbox'])?1:0).",'".$config['checkbox']."'";
-               if (isset($config['checkbox'])) {
-                               // Setting default "click-checkbox" values for eval types "date" and "datetime":
-                       $thisMidnight = gmmktime(0,0,0);
-                       if (in_array('date',$evalList)) {
-                               $checkSetValue = $thisMidnight;
-                       } elseif (in_array('datetime',$evalList))       {
-                               $checkSetValue = $GLOBALS['EXEC_TIME'];
-                       } elseif (in_array('year',$evalList))   {
-                               $checkSetValue = gmdate('Y');
-                       }
-                       $cOnClick = 'typo3form.fieldGet('.$paramsList.',1,\''.$checkSetValue.'\');'.implode('',$PA['fieldChangeFunc']);
-                       $item .= '<input type="checkbox" id="' . uniqid('tceforms-check-') . '" class="' . $this->formElStyleClassValue('check', TRUE) . '" name="' . $PA['itemFormElName'] . '_cb" onclick="' . htmlspecialchars($cOnClick) . '" />';
-               }
-               if ((in_array('date',$evalList) || in_array('datetime',$evalList)) && $PA['itemFormElValue']>0){
+               $paramsList = "'" . $PA['itemFormElName'] . "','" . implode(',', $evalList) . "','" . trim($config['is_in']) . "'," . (isset($config['checkbox']) ? 1 : 0) . ",'" . $config['checkbox'] . "'";
+               if ((in_array('date', $evalList) || in_array('datetime', $evalList))) {
+                       $item .= '<span class="t3-tceforms-input-wrapper-datetime" onmouseOver="if (document.getElementById(\'' .
+                                        $inputId . '\').value) {this.className=\'t3-tceforms-input-wrapper-datetime-hover\';} else {this.className=\'t3-tceforms-input-wrapper-datetime\';};" onmouseOut="this.className=\'t3-tceforms-input-wrapper-datetime\';">';
+
                                // Add server timezone offset to UTC to our stored date
-                       $PA['itemFormElValue'] += date('Z', $PA['itemFormElValue']);
+                       if ($PA['itemFormElValue'] > 0) {
+                               $PA['itemFormElValue'] += date('Z', $PA['itemFormElValue']);
+                       }
+               } else {
+                       $item .= '<span class="t3-tceforms-input-wrapper" onmouseOver="if (document.getElementById(\'' . $inputId .
+                                        '\').value) {this.className=\'t3-tceforms-input-wrapper-hover\';} else {this.className=\'t3-tceforms-input-wrapper\';};" onmouseOut="this.className=\'t3-tceforms-input-wrapper\';">';
                }
 
-               $PA['fieldChangeFunc'] = array_merge(array('typo3form.fieldGet'=>'typo3form.fieldGet('.$paramsList.');'), $PA['fieldChangeFunc']);
-               $mLgd = ($config['max']?$config['max']:256);
-               $iOnChange = implode('',$PA['fieldChangeFunc']);
-
-               $item.='<input type="text" id="' . $inputId . '" class="' . implode(' ', $cssClasses) . '" name="'.$PA['itemFormElName'].'_hr" value="" style="' . $cssStyle . '" 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.
-               $item .= $fieldAppendix;
-               $this->extJSCODE.='typo3form.fieldSet('.$paramsList.');';
+               $PA['fieldChangeFunc'] = array_merge(
+                       array('typo3form.fieldGet' => 'typo3form.fieldGet(' . $paramsList . ');'),
+                       $PA['fieldChangeFunc']
+               );
+                       // old function "checkbox" now the option to set the date / remove the date
+               if (isset($config['checkbox'])) {
+                       $item .= t3lib_iconWorks::getSpriteIcon('actions-input-clear', array('tag' => 'a', 'class' => 't3-tceforms-input-clearer', 'onclick' => 'document.getElementById(\'' . $inputId . '\').value=\'\';document.getElementById(\'' . $inputId . '\').focus();' . implode('', $PA['fieldChangeFunc'])));
+               }
+               $mLgd = ($config['max'] ? $config['max'] : 256);
+               $iOnChange = implode('', $PA['fieldChangeFunc']);
+
+               $item .= '<input type="text" id="' . $inputId .
+                                '" class="' . implode(' ', $cssClasses) . '" name="' . $PA['itemFormElName'] .
+                                '_hr" value="" style="' . $cssStyle . '" 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.
+               $item .= $fieldAppendix . '</span><div style="clear:both;"></div>';
+               $this->extJSCODE .= 'typo3form.fieldSet(' . $paramsList . ');';
 
                        // going through all custom evaluations configured for this field
                foreach ($evalList as $evalData) {
-                       if (substr($evalData, 0, 3) == 'tx_')   {
-                               $evalObj = t3lib_div::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$evalData].':&'.$evalData);
-                               if(is_object($evalObj) && method_exists($evalObj, 'returnFieldJS'))     {
-                                       $this->extJSCODE .= "\n\nfunction ".$evalData."(value) {\n".$evalObj->returnFieldJS()."\n}\n";
+                       if (t3lib_div::hasValidClassPrefix($evalData)) {
+                               $evalObj = t3lib_div::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$evalData] . ':&' . $evalData);
+                               if (is_object($evalObj) && method_exists($evalObj, 'returnFieldJS')) {
+                                       $this->extJSCODE .= "\n\nfunction " . $evalData . "(value) {\n" . $evalObj->returnFieldJS() . "\n}\n";
                                }
                        }
                }
 
                        // 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);
+               $item = $this->renderWizards(array($item, $altItem), $config['wizards'], $table, $row, $field, $PA, $PA['itemFormElName'] . '_hr', $specConf);
 
                return $item;
        }
@@ -1230,13 +1216,13 @@ class t3lib_TCEforms    {
         * @param       array           An array with additional configuration options.
         * @return      string          The HTML code for the TCEform field
         */
-       function getSingleField_typeText($table,$field,$row,&$PA)       {
+       function getSingleField_typeText($table, $field, $row, &$PA) {
 
                        // Init config:
                $config = $PA['fieldConf']['config'];
                $evalList = t3lib_div::trimExplode(',', $config['eval'], 1);
 
-               if($this->renderReadonly || $config['readOnly'])  {
+               if ($this->renderReadonly || $config['readOnly']) {
                        return $this->getSingleField_typeNone_render($config, $PA['itemFormElValue']);
                }
 
@@ -1245,41 +1231,43 @@ class t3lib_TCEforms    {
 
                        // Setting number of rows:
                $origRows = $rows = t3lib_div::intInRange($config['rows'] ? $config['rows'] : 5, 1, 20);
-               if (strlen($PA['itemFormElValue']) > $this->charsPerRow*2)      {
+               if (strlen($PA['itemFormElValue']) > $this->charsPerRow * 2) {
                        $cols = $this->maxTextareaWidth;
-                       $rows = t3lib_div::intInRange(round(strlen($PA['itemFormElValue'])/$this->charsPerRow), count(explode(LF,$PA['itemFormElValue'])), 20);
-                       if ($rows<$origRows)    $rows = $origRows;
+                       $rows = t3lib_div::intInRange(round(strlen($PA['itemFormElValue']) / $this->charsPerRow), count(explode(LF, $PA['itemFormElValue'])), 20);
+                       if ($rows < $origRows) {
+                               $rows = $origRows;
+                       }
                }
 
-               if (in_array('required', $evalList))    {
+               if (in_array('required', $evalList)) {
                        $this->requiredFields[$table . '_' . $row['uid'] . '_' . $field] = $PA['itemFormElName'];
                }
 
                        // 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...
+               $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']);
 
                        // 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']).'" />';
+               $altItem = '<input type="hidden" name="' . htmlspecialchars($PA['itemFormElName']) . '" value="' . htmlspecialchars($PA['itemFormElValue']) . '" />';
 
                        // 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.
-                               t3lib_BEfunc::fixVersioningPid($table,$row);
-                               list($tscPID,$thePidValue) = $this->getTSCpid($table,$row['uid'],$row['pid']);
+                       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.
+                               t3lib_BEfunc::fixVersioningPid($table, $row);
+                               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 ($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) {
+                                       if (!$thisConfig['disabled']) {
+                                               if (!$this->disableRTE) {
                                                        $this->RTEcounter++;
 
                                                                // Find alternative relative path for RTE images/links:
@@ -1288,79 +1276,93 @@ class t3lib_TCEforms    {
 
                                                                // 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);
+                                                       $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);
+                                                       $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!)';
+                                                       $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!';
+                               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>';
+                       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 ($specConf['nowrap'])        {
+                               if ($specConf['nowrap']) {
                                        $wrap = 'off';
                                } else {
                                        $wrap = ($config['wrap'] ? $config['wrap'] : 'virtual');
                                }
 
                                $classes = array();
-                               if ($specConf['fixed-font'])    { $classes[] = 'fixed-font'; }
-                               if ($specConf['enable-tab'])    { $classes[] = 'enable-tab'; }
+                               if ($specConf['fixed-font']) {
+                                       $classes[] = 'fixed-font';
+                               }
+                               if ($specConf['enable-tab']) {
+                                       $classes[] = 'enable-tab';
+                               }
 
-                               $formWidthText = $this->formWidthText($cols,$wrap);
+                               $formWidthText = $this->formWidthText($cols, $wrap);
 
                                        // Extract class attributes from $formWidthText (otherwise it would be added twice to the output)
                                $res = array();
-                               if (preg_match('/ class="(.+?)"/',$formWidthText,$res)) {
-                                       $formWidthText = str_replace(' class="'.$res[1].'"','',$formWidthText);
-                                       $classes = array_merge($classes, explode(' ',$res[1]));
+                               if (preg_match('/ class="(.+?)"/', $formWidthText, $res)) {
+                                       $formWidthText = str_replace(' class="' . $res[1] . '"', '', $formWidthText);
+                                       $classes = array_merge($classes, explode(' ', $res[1]));
                                }
 
-                               if (count($classes))    {
-                                       $class = ' class="tceforms-textarea '.implode(' ',$classes).'"';
-                               } else $class='tceforms-textarea';
+                               if (count($classes)) {
+                                       $class = ' class="tceforms-textarea ' . implode(' ', $classes) . '"';
+                               } else {
+                                       $class = 'tceforms-textarea';
+                               }
 
-                               $evalList = t3lib_div::trimExplode(',',$config['eval'],1);
+                               $evalList = t3lib_div::trimExplode(',', $config['eval'], 1);
                                foreach ($evalList as $func) {
                                        switch ($func) {
                                                case 'required':
-                                                       $this->registerRequiredProperty('field', $table.'_'.$row['uid'].'_'.$field, $PA['itemFormElName']);
-                                                       break;
+                                                       $this->registerRequiredProperty('field', $table . '_' . $row['uid'] . '_' . $field, $PA['itemFormElName']);
+                                               break;
                                                default:
-                                                       if (substr($func, 0, 3) == 'tx_')       {
-                                                               // Pair hook to the one in t3lib_TCEmain::checkValue_input_Eval() and t3lib_TCEmain::checkValue_text_Eval()
-                                                               $evalObj = t3lib_div::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func].':&'.$func);
-                                                               if (is_object($evalObj) && method_exists($evalObj, 'deevaluateFieldValue'))     {
+                                                       if (t3lib_div::hasValidClassPrefix($func)) {
+                                                                       // Pair hook to the one in t3lib_TCEmain::checkValue_input_Eval() and t3lib_TCEmain::checkValue_text_Eval()
+                                                               $evalObj = t3lib_div::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func] . ':&' . $func);
+                                                               if (is_object($evalObj) && method_exists($evalObj, 'deevaluateFieldValue')) {
                                                                        $_params = array(
                                                                                'value' => $PA['itemFormElValue']
                                                                        );
                                                                        $PA['itemFormElValue'] = $evalObj->deevaluateFieldValue($_params);
                                                                }
                                                        }
-                                                       break;
+                                               break;
                                        }
                                }
 
-                               $iOnChange = implode('',$PA['fieldChangeFunc']);
-                               $item.= '
-                                                       <textarea id="' . uniqid('tceforms-textarea-') . '" name="'.$PA['itemFormElName'].'"'.$formWidthText.$class.' 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);
+                               $iOnChange = implode('', $PA['fieldChangeFunc']);
+                               $item .= '
+                                                       <textarea id="' . uniqid('tceforms-textarea-') . '" name="' . $PA['itemFormElName'] . '"' . $formWidthText . $class . ' 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);
                        }
                }
 
@@ -1378,59 +1380,68 @@ class t3lib_TCEforms    {
         * @param       array           An array with additional configuration options.
         * @return      string          The HTML code for the TCEform field
         */
-       function getSingleField_typeCheck($table,$field,$row,&$PA)      {
+       function getSingleField_typeCheck($table, $field, $row, &$PA) {
                $config = $PA['fieldConf']['config'];
 
+               $item = '';
                $disabled = '';
-               if($this->renderReadonly || $config['readOnly'])  {
+               if ($this->renderReadonly || $config['readOnly']) {
                        $disabled = ' disabled="disabled"';
                }
 
                        // Traversing the array of items:
                $selItems = $this->initItemArray($PA['fieldConf']);
-               if ($config['itemsProcFunc']) $selItems = $this->procItems($selItems,$PA['fieldTSConfig']['itemsProcFunc.'],$config,$table,$row,$field);
+               if ($config['itemsProcFunc']) {
+                       $selItems = $this->procItems($selItems, $PA['fieldTSConfig']['itemsProcFunc.'], $config, $table, $row, $field);
+               }
 
-               if (!count($selItems))  {
-                       $selItems[]=array('','');
+               if (!count($selItems)) {
+                       $selItems[] = array('', '');
                }
                $thisValue = intval($PA['itemFormElValue']);
 
                $cols = intval($config['cols']);
-               if ($cols > 1)  {
-                       $item.= '<table border="0" cellspacing="0" cellpadding="0" class="typo3-TCEforms-checkboxArray">';
-                       for ($c=0;$c<count($selItems);$c++) {
+               if ($cols > 1) {
+                       $item .= '<table border="0" cellspacing="0" cellpadding="0" class="typo3-TCEforms-checkboxArray">';
+                       for ($c = 0; $c < count($selItems); $c++) {
                                $p = $selItems[$c];
-                               if(!($c%$cols)) { $item.='<tr>'; }
-                               $cBP = $this->checkBoxParams($PA['itemFormElName'],$thisValue,$c,count($selItems),implode('',$PA['fieldChangeFunc']));
-                               $cBName = $PA['itemFormElName'].'_'.$c;
-                               $cBID = $PA['itemFormElID'].'_'.$c;
-                               $item.= '<td nowrap="nowrap">'.
-                                               '<input type="checkbox"'.$this->insertDefStyle('check').' value="1" name="'.$cBName.'"'.$cBP.$disabled.' id="'.$cBID.'" />'.
-                                               $this->wrapLabels('<label for="'.$cBID.'">'.htmlspecialchars($p[0]).'</label>&nbsp;').
-                                               '</td>';
-                               if(($c%$cols)+1==$cols) {$item.='</tr>';}
+                               if (!($c % $cols)) {
+                                       $item .= '<tr>';
+                               }
+                               $cBP = $this->checkBoxParams($PA['itemFormElName'], $thisValue, $c, count($selItems), implode('', $PA['fieldChangeFunc']));
+                               $cBName = $PA['itemFormElName'] . '_' . $c;
+                               $cBID = $PA['itemFormElID'] . '_' . $c;
+                               $item .= '<td nowrap="nowrap">' .
+                                                '<input type="checkbox"' . $this->insertDefStyle('check') . ' value="1" name="' . $cBName . '"' . $cBP . $disabled . ' id="' . $cBID . '" />' .
+                                                $this->wrapLabels('<label for="' . $cBID . '">' . htmlspecialchars($p[0]) . '</label>&nbsp;') .
+                                                '</td>';
+                               if (($c % $cols) + 1 == $cols) {
+                                       $item .= '</tr>';
+                               }
                        }
-                       if ($c%$cols)   {
-                               $rest=$cols-($c%$cols);
-                               for ($c=0;$c<$rest;$c++) {
-                                       $item.= '<td></td>';
+                       if ($c % $cols) {
+                               $rest = $cols - ($c % $cols);
+                               for ($c = 0; $c < $rest; $c++) {
+                                       $item .= '<td></td>';
+                               }
+                               if ($c > 0) {
+                                       $item .= '</tr>';
                                }
-                               if ($c>0)       { $item.= '</tr>'; }
                        }
-                       $item.= '</table>';
+                       $item .= '</table>';
                } else {
-                       for ($c=0;$c<count($selItems);$c++) {
+                       for ($c = 0; $c < count($selItems); $c++) {
                                $p = $selItems[$c];
-                               $cBP = $this->checkBoxParams($PA['itemFormElName'],$thisValue,$c,count($selItems),implode('',$PA['fieldChangeFunc']));
-                               $cBName = $PA['itemFormElName'].'_'.$c;
-                               $cBID = $PA['itemFormElID'].'_'.$c;
-                               $item.= ($c>0?'<br />':'').
-                                               '<input type="checkbox"'.$this->insertDefStyle('check').' value="1" name="'.$cBName.'"'.$cBP.$PA['onFocus'].$disabled.' id="'.$cBID.'" />'.
-                                               $this->wrapLabels('<label for="'.$cBID.'">'.htmlspecialchars($p[0]).'</label>');
+                               $cBP = $this->checkBoxParams($PA['itemFormElName'], $thisValue, $c, count($selItems), implode('', $PA['fieldChangeFunc']));
+                               $cBName = $PA['itemFormElName'] . '_' . $c;
+                               $cBID = $PA['itemFormElID'] . '_' . $c;
+                               $item .= ($c > 0 ? '<br />' : '') .
+                                                '<input type="checkbox"' . $this->insertDefStyle('check') . ' value="1" name="' . $cBName . '"' . $cBP . $PA['onFocus'] . $disabled . ' id="' . $cBID . '" />' .
+                                                $this->wrapLabels('<label for="' . $cBID . '">' . htmlspecialchars($p[0]) . '</label>');
                        }
                }
                if (!$disabled) {
-                       $item.= '<input type="hidden" name="'.$PA['itemFormElName'].'" value="'.htmlspecialchars($thisValue).'" />';
+                       $item .= '<input type="hidden" name="' . $PA['itemFormElName'] . '" value="' . htmlspecialchars($thisValue) . '" />';
                }
 
                return $item;
@@ -1446,26 +1457,29 @@ class t3lib_TCEforms    {
         * @param       array           An array with additional configuration options.
         * @return      string          The HTML code for the TCEform field
         */
-       function getSingleField_typeRadio($table,$field,$row,&$PA)      {
+       function getSingleField_typeRadio($table, $field, $row, &$PA) {
                $config = $PA['fieldConf']['config'];
 
+               $item = '';
                $disabled = '';
-               if($this->renderReadonly || $config['readOnly'])  {
+               if ($this->renderReadonly || $config['readOnly']) {
                        $disabled = ' disabled="disabled"';
                }
 
                        // Get items for the array:
                $selItems = $this->initItemArray($PA['fieldConf']);
-               if ($config['itemsProcFunc']) $selItems = $this->procItems($selItems,$PA['fieldTSConfig']['itemsProcFunc.'],$config,$table,$row,$field);
+               if ($config['itemsProcFunc']) {
+                       $selItems = $this->procItems($selItems, $PA['fieldTSConfig']['itemsProcFunc.'], $config, $table, $row, $field);
+               }
 
                        // Traverse the items, making the form elements:
-               for ($c=0;$c<count($selItems);$c++) {
+               for ($c = 0; $c < count($selItems); $c++) {
                        $p = $selItems[$c];
-                       $rID = $PA['itemFormElID'].'_'.$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="'.htmlspecialchars($rOnClick).'"'.$rChecked.$PA['onFocus'].$disabled.' id="'.$rID.'" />
-                                       <label for="'.$rID.'">'.htmlspecialchars($p[0]).'</label>
+                       $rID = $PA['itemFormElID'] . '_' . $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="' . htmlspecialchars($rOnClick) . '"' . $rChecked . $PA['onFocus'] . $disabled . ' id="' . $rID . '" />
+                                       <label for="' . $rID . '">' . htmlspecialchars($p[0]) . '</label>
                                        <br />';
                }
 
@@ -1482,14 +1496,13 @@ class t3lib_TCEforms    {
         * @param       array           An array with additional configuration options.
         * @return      string          The HTML code for the TCEform field
         */
-       function getSingleField_typeSelect($table,$field,$row,&$PA)     {
-               global $TCA;
+       function getSingleField_typeSelect($table, $field, $row, &$PA) {
 
                        // Field configuration from TCA:
                $config = $PA['fieldConf']['config'];
 
                $disabled = '';
-               if($this->renderReadonly || $config['readOnly'])  {
+               if ($this->renderReadonly || $config['readOnly']) {
                        $disabled = ' disabled="disabled"';
                }
 
@@ -1514,47 +1527,52 @@ class t3lib_TCEforms    {
                }
 
                        // Possibly remove some items:
-               $removeItems = t3lib_div::trimExplode(',',$PA['fieldTSConfig']['removeItems'],1);
-               foreach($selItems as $tk => $p) {
+               $removeItems = t3lib_div::trimExplode(',', $PA['fieldTSConfig']['removeItems'], 1);
+               foreach ($selItems as $tk => $p) {
 
                                // Checking languages and authMode:
-                       $languageDeny = $TCA[$table]['ctrl']['languageField'] && !strcmp($TCA[$table]['ctrl']['languageField'], $field) && !$GLOBALS['BE_USER']->checkLanguageAccess($p[1]);
-                       $authModeDeny = $config['form_type']=='select' && $config['authMode'] && !$GLOBALS['BE_USER']->checkAuthMode($table,$field,$p[1],$config['authMode']);
-                       if (in_array($p[1],$removeItems) || $languageDeny || $authModeDeny)     {
+                       $languageDeny = $GLOBALS['TCA'][$table]['ctrl']['languageField']
+                               && !strcmp($GLOBALS['TCA'][$table]['ctrl']['languageField'], $field)
+                               && !$GLOBALS['BE_USER']->checkLanguageAccess($p[1]);
+                       $authModeDeny = $config['form_type'] == 'select' && $config['authMode'] && !$GLOBALS['BE_USER']->checkAuthMode($table, $field, $p[1], $config['authMode']);
+                       if (in_array($p[1], $removeItems) || $languageDeny || $authModeDeny) {
                                unset($selItems[$tk]);
                        } elseif (isset($PA['fieldTSConfig']['altLabels.'][$p[1]])) {
-                               $selItems[$tk][0]=$this->sL($PA['fieldTSConfig']['altLabels.'][$p[1]]);
+                               $selItems[$tk][0] = $this->sL($PA['fieldTSConfig']['altLabels.'][$p[1]]);
                        }
 
                                // Removing doktypes with no access:
-                       if ($table.'.'.$field == 'pages.doktype')       {
-                               if (!($GLOBALS['BE_USER']->isAdmin() || t3lib_div::inList($GLOBALS['BE_USER']->groupData['pagetypes_select'],$p[1])))   {
+                       if (($table === 'pages' || $table === 'pages_language_overlay') && $field === 'doktype') {
+                               if (!($GLOBALS['BE_USER']->isAdmin() || t3lib_div::inList($GLOBALS['BE_USER']->groupData['pagetypes_select'], $p[1]))) {
                                        unset($selItems[$tk]);
                                }
                        }
                }
 
                        // Creating the label for the "No Matching Value" entry.
-               $nMV_label = isset($PA['fieldTSConfig']['noMatchingValue_label']) ? $this->sL($PA['fieldTSConfig']['noMatchingValue_label']) : '[ '.$this->getLL('l_noMatchingValue').' ]';
+               $nMV_label = isset($PA['fieldTSConfig']['noMatchingValue_label']) ? $this->sL($PA['fieldTSConfig']['noMatchingValue_label']) : '[ ' . $this->getLL('l_noMatchingValue') . ' ]';
 
                        // Prepare some values:
                $maxitems = intval($config['maxitems']);
 
                        // If a SINGLE selector box...
-               if ($maxitems<=1)       {
-                       $item = $this->getSingleField_typeSelect_single($table,$field,$row,$PA,$config,$selItems,$nMV_label);
-               } elseif (!strcmp($config['renderMode'],'checkbox'))    {       // Checkbox renderMode
-                       $item = $this->getSingleField_typeSelect_checkbox($table,$field,$row,$PA,$config,$selItems,$nMV_label);
-               } elseif (!strcmp($config['renderMode'],'singlebox'))   {       // Single selector box renderMode
-                       $item = $this->getSingleField_typeSelect_singlebox($table,$field,$row,$PA,$config,$selItems,$nMV_label);
-               } else {        // Traditional multiple selector box:
-                       $item = $this->getSingleField_typeSelect_multiple($table,$field,$row,$PA,$config,$selItems,$nMV_label);
+               if ($maxitems <= 1 && $config['renderMode'] !== 'tree') {
+                       $item = $this->getSingleField_typeSelect_single($table, $field, $row, $PA, $config, $selItems, $nMV_label);
+               } elseif (!strcmp($config['renderMode'], 'checkbox')) { // Checkbox renderMode
+                       $item = $this->getSingleField_typeSelect_checkbox($table, $field, $row, $PA, $config, $selItems, $nMV_label);
+               } elseif (!strcmp($config['renderMode'], 'singlebox')) { // Single selector box renderMode
+                       $item = $this->getSingleField_typeSelect_singlebox($table, $field, $row, $PA, $config, $selItems, $nMV_label);
+               } elseif (!strcmp($config['renderMode'], 'tree')) { // Tree renderMode
+                       $treeClass = t3lib_div::makeInstance('t3lib_TCEforms_Tree', $this);
+                       $item = $treeClass->renderField($table, $field, $row, $PA, $config, $selItems, $nMV_label);
+               } else { // Traditional multiple selector box:
+                       $item = $this->getSingleField_typeSelect_multiple($table, $field, $row, $PA, $config, $selItems, $nMV_label);
                }
 
                        // Wizards:
                if (!$disabled) {
-                       $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;
@@ -1574,13 +1592,13 @@ class t3lib_TCEforms    {
         * @return      string          The HTML code for the item
         * @see getSingleField_typeSelect()
         */
-       function getSingleField_typeSelect_single($table,$field,$row,&$PA,$config,$selItems,$nMV_label) {
+       function getSingleField_typeSelect_single($table, $field, $row, &$PA, $config, $selItems, $nMV_label) {
                        // check against inline uniqueness
                $inlineParent = $this->inline->getStructureLevel(-1);
-               if(is_array($inlineParent) && $inlineParent['uid']) {
+               if (is_array($inlineParent) && $inlineParent['uid']) {
                        if ($inlineParent['config']['foreign_table'] == $table && $inlineParent['config']['foreign_unique'] == $field) {
-                               $uniqueIds = $this->inline->inlineData['unique'][$this->inline->inlineNames['object'].'['.$table.']']['used'];
-                               $PA['fieldChangeFunc']['inlineUnique'] = "inline.updateUnique(this,'".$this->inline->inlineNames['object'].'['.$table."]','".$this->inline->inlineNames['form']."','".$row['uid']."');";
+                               $uniqueIds = $this->inline->inlineData['unique'][$this->inline->inlineNames['object'] . '[' . $table . ']']['used'];
+                               $PA['fieldChangeFunc']['inlineUnique'] = "inline.updateUnique(this,'" . $this->inline->inlineNames['object'] . '[' . $table . "]','" . $this->inline->inlineNames['form'] . "','" . $row['uid'] . "');";
                        }
                                // hide uid of parent record for symmetric relations
                        if ($inlineParent['config']['foreign_table'] == $table && ($inlineParent['config']['foreign_field'] == $field || $inlineParent['config']['symmetric_field'] == $field)) {
@@ -1598,127 +1616,149 @@ class t3lib_TCEforms  {
                $size = intval($config['size']);
                $selectedStyle = ''; // Style set on <select/>
 
+               $item = '';
                $disabled = '';
-               if($this->renderReadonly || $config['readOnly'])  {
+               $onChangeIcon = ''; // TODO: icon is used but never assigned
+
+               if ($this->renderReadonly || $config['readOnly']) {
                        $disabled = ' disabled="disabled"';
                        $onlySelectedIconShown = 1;
                }
 
                        // Icon configuration:
-               if ($config['suppress_icons']=='IF_VALUE_FALSE')        {
+               if ($config['suppress_icons'] == 'IF_VALUE_FALSE') {
                        $suppressIcons = !$PA['itemFormElValue'] ? 1 : 0;
-               } elseif ($config['suppress_icons']=='ONLY_SELECTED')   {
-                       $suppressIcons=0;
-                       $onlySelectedIconShown=1;
-               } elseif ($config['suppress_icons'])    {
+               } elseif ($config['suppress_icons'] == 'ONLY_SELECTED') {
+                       $suppressIcons = 0;
+                       $onlySelectedIconShown = 1;
+               } elseif ($config['suppress_icons']) {
                        $suppressIcons = 1;
-               } else $suppressIcons = 0;
+               } else {
+                       $suppressIcons = 0;
+               }
 
                        // Traverse the Array of selector box items:
                $optGroupStart = array();
                $optGroupOpen = FALSE;
-               foreach($selItems as $p)        {
-                       $sM = (!strcmp($PA['itemFormElValue'],$p[1])?' selected="selected"':'');
-                       if ($sM)        {
+               $classesForSelectTag = array();
+               foreach ($selItems as $p) {
+                       $sM = (!strcmp($PA['itemFormElValue'], $p[1]) ? ' selected="selected"' : '');
+                       if ($sM) {
                                $sI = $c;
                                $noMatchingValue = 0;
                        }
 
                                // Getting style attribute value (for icons):
-                       if ($config['iconsInOptionTags'])       {
+                       if ($config['iconsInOptionTags']) {
                                $styleAttrValue = $this->optionTagStyle($p[2]);
                                if ($sM) {
-                                       list($selectIconFile,$selectIconInfo) = $this->getIcon($p[2]);
-                                               if (!empty($selectIconInfo)) {
-                                                       $selectedStyle = ' style="background: #fff url(' . $selectIconFile . ') 0% 50% no-repeat; padding: 1px 1px 1px 24px; -webkit-background-size: 0;"';
-                                               }
+                                       list($selectIconFile, $selectIconInfo) = $this->getIcon($p[2]);
+                                       if (!empty($selectIconInfo)) {
+                                               $selectedStyle = ' style="background-image:url(' . $selectIconFile . ');"';
+                                               $classesForSelectTag[] = 'typo3-TCEforms-select-selectedItemWithBackgroundImage';
+                                       }
                                }
                        }
 
                                // Compiling the <option> tag:
                        if (!($p[1] != $PA['itemFormElValue'] && is_array($uniqueIds) && in_array($p[1], $uniqueIds))) {
-                               if(!strcmp($p[1],'--div--')) {
+                               if (!strcmp($p[1], '--div--')) {
                                        $optGroupStart[0] = $p[0];
-                                       $optGroupStart[1] = $styleAttrValue;
+                                       if ($config['iconsInOptionTags']) {
+                                               $optGroupStart[1] = $this->optgroupTagStyle($p[2]);
+                                       } else {
+                                               $optGroupStart[1] = $styleAttrValue;
+                                       }
 
                                } else {
                                        if (count($optGroupStart)) {
-                                               if($optGroupOpen) { // Closing last optgroup before next one starts
-                                                       $opt[]='</optgroup>' . LF;
+                                               if ($optGroupOpen) { // Closing last optgroup before next one starts
+                                                       $opt[] = '</optgroup>' . LF;
                                                }
-                                               $opt[]= '<optgroup label="'.t3lib_div::deHSCentities(htmlspecialchars($optGroupStart[0])).'"'.
-                                                               ($optGroupStart[1] ? ' style="'.htmlspecialchars($optGroupStart[1]).'"' : '').
-                                                               ' class="c-divider">' . LF;
-                                               $optGroupOpen = true;
+                                               $opt[] = '<optgroup label="' . t3lib_div::deHSCentities(htmlspecialchars($optGroupStart[0])) . '"' .
+                                                                ($optGroupStart[1] ? ' style="' . htmlspecialchars($optGroupStart[1]) . '"' : '') .
+                                                                ' class="c-divider">' . LF;
+                                               $optGroupOpen = TRUE;
                                                $c--;
                                                $optGroupStart = array();
                                        }
-                                       $opt[]= '<option value="'.htmlspecialchars($p[1]).'"'.
-                                                       $sM.
-                                                       ($styleAttrValue ? ' style="'.htmlspecialchars($styleAttrValue).'"' : '').
-                                                       '>' . t3lib_div::deHSCentities(($p[0])) . '</option>' . LF;
+                                       $opt[] = '<option value="' . htmlspecialchars($p[1]) . '"' .
+                                                        $sM .
+                                                        ($styleAttrValue ? ' style="' . htmlspecialchars($styleAttrValue) . '"' : '') .
+                                                        '>' . t3lib_div::deHSCentities(($p[0])) . '</option>' . LF;
                                }
                        }
 
-                               // If there is an icon for the selector box (rendered in table under)...:
-                       if ($p[2] && !$suppressIcons && (!$onlySelectedIconShown || $sM))       {
-                               list($selIconFile,$selIconInfo)=$this->getIcon($p[2]);
-                               $iOnClick = $this->elName($PA['itemFormElName']) . '.selectedIndex=' . $c . '; ' .
-                                       $this->elName($PA['itemFormElName']) . '.style.backgroundImage=' . $this->elName($PA['itemFormElName']) . '.options[' . $c .'].style.backgroundImage; ' .
-                                       implode('',$PA['fieldChangeFunc']).$this->blur().'return false;';
-                               $selicons[]=array(
-                                       (!$onlySelectedIconShown ? '<a href="#" onclick="'.htmlspecialchars($iOnClick).'">' : '').
-                                       '<img src="'.$selIconFile.'" '.$selIconInfo[3].' vspace="2" border="0" title="'.htmlspecialchars($p[0]).'" alt="'.htmlspecialchars($p[0]).'" />'.
+                               // If there is an icon for the selector box (rendered in selicon-table below)...:
+                               // if there is an icon ($p[2]), icons should be shown, and, if only selected are visible, is it selected
+                       if ($p[2] && !$suppressIcons && (!$onlySelectedIconShown || $sM)) {
+                               list($selIconFile, $selIconInfo) = $this->getIcon($p[2]);
+                               if (!empty($selIconInfo)) {
+                                       $iOnClick = $this->elName($PA['itemFormElName']) . '.selectedIndex=' . $c . '; ' .
+                                               $this->elName($PA['itemFormElName']) . '.style.backgroundImage=' . $this->elName($PA['itemFormElName']) . '.options[' . $c . '].style.backgroundImage; ' .
+                                               implode('', $PA['fieldChangeFunc']) . $this->blur() . 'return false;';
+                               } else {
+                                       $iOnClick = $this->elName($PA['itemFormElName']) . '.selectedIndex=' . $c . '; ' .
+                                               $this->elName($PA['itemFormElName']) . '.className=' . $this->elName($PA['itemFormElName']) . '.options[' . $c . '].className; ' .
+                                               implode('', $PA['fieldChangeFunc']) . $this->blur() . 'return false;';
+                               }
+                               $selicons[] = array(
+                                       (!$onlySelectedIconShown ? '<a href="#" onclick="' . htmlspecialchars($iOnClick) . '">' : '') .
+                                       $this->getIconHtml($p[2], htmlspecialchars($p[0]), htmlspecialchars($p[0])) .
                                        (!$onlySelectedIconShown ? '</a>' : ''),
-                                       $c,$sM);
-                               $onChangeIcon = 'this.style.backgroundImage=this.options[this.selectedIndex].style.backgroundImage;';
+                                       $c, $sM);
                        }
                        $c++;
                }
 
-               if($optGroupOpen) { // Closing optgroup if open
-                       $opt[]='</optgroup>';
-                       $optGroupOpen = false;
+               if ($optGroupOpen) { // Closing optgroup if open
+                       $opt[] = '</optgroup>';
+                       $optGroupOpen = FALSE;
                }
 
                        // No-matching-value:
-               if ($PA['itemFormElValue'] && $noMatchingValue && !$PA['fieldTSConfig']['disableNoMatchingValueElement'] && !$config['disableNoMatchingValueElement'])  {
+               if ($PA['itemFormElValue'] && $noMatchingValue && !$PA['fieldTSConfig']['disableNoMatchingValueElement'] && !$config['disableNoMatchingValueElement']) {
                        $nMV_label = @sprintf($nMV_label, $PA['itemFormElValue']);
-                       $opt[]= '<option value="'.htmlspecialchars($PA['itemFormElValue']).'" selected="selected">'.htmlspecialchars($nMV_label).'</option>';
+                       $opt[] = '<option value="' . htmlspecialchars($PA['itemFormElValue']) . '" selected="selected">' . htmlspecialchars($nMV_label) . '</option>';
                }
 
                        // Create item form fields:
-               $sOnChange = 'if (this.options[this.selectedIndex].value==\'--div--\') {this.selectedIndex='.$sI.';} '.implode('',$PA['fieldChangeFunc']);
-               if(!$disabled) {
-                       $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...
+               $sOnChange = 'if (this.options[this.selectedIndex].value==\'--div--\') {this.selectedIndex=' . $sI . ';} ' . implode('', $PA['fieldChangeFunc']);
+               if (!$disabled) {
+                       $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...
+               }
+               if ($config['iconsInOptionTags']) {
+                       $classesForSelectTag[] = 'icon-select';
                }
                $item .= '<select' . $selectedStyle . ' id="' . uniqid('tceforms-select-') . '" name="' . $PA['itemFormElName'] . '"' .
-                                       ($config['iconsInOptionTags'] ? $this->insertDefStyle('select', 'icon-select') : $this->insertDefStyle('select')) .
-                                       ($size ? ' size="' . $size . '"' : '') .
-                                       ' onchange="' . htmlspecialchars($onChangeIcon . $sOnChange) . '"' .
-                                       $PA['onFocus'] . $disabled . '>';
-               $item.= implode('',$opt);
-               $item.= '</select>';
+                                $this->insertDefStyle('select', implode(' ', $classesForSelectTag)) .
+                                ($size ? ' size="' . $size . '"' : '') .
+                                ' onchange="' . htmlspecialchars($onChangeIcon . $sOnChange) . '"' .
+                                $PA['onFocus'] . $disabled . '>';
+               $item .= implode('', $opt);
+               $item .= '</select>';
 
                        // Create icon table:
-               if (count($selicons) && !$config['noIconsBelowSelect']) {
-                       $item.='<table border="0" cellpadding="0" cellspacing="0" class="typo3-TCEforms-selectIcons">';
+               if (count($selicons) && !$config['noIconsBelowSelect']) {
+                       $item .= '<table border="0" cellpadding="0" cellspacing="0" class="typo3-TCEforms-selectIcons">';
                        $selicon_cols = intval($config['selicon_cols']);
-                       if (!$selicon_cols)     $selicon_cols=count($selicons);
-                       $sR = ceil(count($selicons)/$selicon_cols);
-                       $selicons = array_pad($selicons,$sR*$selicon_cols,'');
-                       for($sa=0;$sa<$sR;$sa++)        {
-                               $item.='<tr>';
-                               for($sb=0;$sb<$selicon_cols;$sb++)      {
-                                       $sk=($sa*$selicon_cols+$sb);
-                                       $imgN = 'selIcon_'.$table.'_'.$row['uid'].'_'.$field.'_'.$selicons[$sk][1];
-                                       $imgS = ($selicons[$sk][2]?$this->backPath.'gfx/content_selected.gif':'clear.gif');
-                                       $item.='<td><img name="'.htmlspecialchars($imgN).'" src="'.$imgS.'" width="7" height="10" alt="" /></td>';
-                                       $item.='<td>'.$selicons[$sk][0].'</td>';
+                       if (!$selicon_cols) {
+                               $selicon_cols = count($selicons);
+                       }
+                       $sR = ceil(count($selicons) / $selicon_cols);
+                       $selicons = array_pad($selicons, $sR * $selicon_cols, '');
+                       for ($sa = 0; $sa < $sR; $sa++) {
+                               $item .= '<tr>';
+                               for ($sb = 0; $sb < $selicon_cols; $sb++) {
+                                       $sk = ($sa * $selicon_cols + $sb);
+                                       $imgN = 'selIcon_' . $table . '_' . $row['uid'] . '_' . $field . '_' . $selicons[$sk][1];
+                                       $imgS = ($selicons[$sk][2] ? $this->backPath . 'gfx/content_selected.gif' : 'clear.gif');
+                                       $item .= '<td><img name="' . htmlspecialchars($imgN) . '" src="' . $imgS . '" width="7" height="10" alt="" /></td>';
+                                       $item .= '<td>' . $selicons[$sk][0] . '</td>';
                                }
-                               $item.='</tr>';
+                               $item .= '</tr>';
                        }
-                       $item.='</table>';
+                       $item .= '</table>';
                }
 
                return $item;
@@ -1738,59 +1778,49 @@ class t3lib_TCEforms    {
         * @return      string          The HTML code for the item
         * @see getSingleField_typeSelect()
         */
-       function getSingleField_typeSelect_checkbox($table,$field,$row,&$PA,$config,$selItems,$nMV_label)       {
+       function getSingleField_typeSelect_checkbox($table, $field, $row, &$PA, $config, $selItems, $nMV_label) {
+
+               if (empty($selItems)) {
+                       return '';
+               }
 
                        // Get values in an array (and make unique, which is fine because there can be no duplicates anyway):
                $itemArray = array_flip($this->extractValuesOnlyFromValueLabelList($PA['itemFormElValue']));
 
+               $item = '';
                $disabled = '';
-               if($this->renderReadonly || $config['readOnly'])  {
+               if ($this->renderReadonly || $config['readOnly']) {
                        $disabled = ' disabled="disabled"';
                }
 
                        // Traverse the Array of selector box items:
                $tRows = array();
-               $c=0;
+               $c = 0;
                if (!$disabled) {
-                       $sOnChange = implode('',$PA['fieldChangeFunc']);
-                       $setAll = array();      // Used to accumulate the JS needed to restore the original selection.
+                       $sOnChange = implode('', $PA['fieldChangeFunc']);
+                       $setAll = array(); // Used to accumulate the JS needed to restore the original selection.
                        $unSetAll = array();
-                       foreach($selItems as $p)        {
+                       foreach ($selItems as $p) {
                                        // Non-selectable element:
-                               if (!strcmp($p[1],'--div--'))   {
-                                       if (count($setAll))     {
-                                                       $tRows[] = '
-                                                               <tr class="c-header-checkbox-controls">
-                                                                       <td colspan="3">' .
-                                                                               '<a href="#" onclick="' . htmlspecialchars(implode('', $setAll).' return false;') . '">' .
-                                                                               htmlspecialchars($this->getLL('l_checkAll')) .
-                                                                               '</a>
-                                                                               <a href="#" onclick="' . htmlspecialchars(implode('', $unSetAll).' return false;').'">' .
-                                                                               htmlspecialchars($this->getLL('l_uncheckAll')) .
-                                                                               '</a>
-                                                                       </td>
-                                                               </tr>';
-                                                       $setAll = array();
-                                                       $unSetAll = array();
-                                       }
-
+                               if (!strcmp($p[1], '--div--')) {
                                        $tRows[] = '
                                                <tr class="c-header">
-                                                       <td colspan="3">'.htmlspecialchars($p[0]).'</td>
+                                                       <td colspan="3">' . htmlspecialchars($p[0]) . '</td>
                                                </tr>';
                                } else {
                                                // Selected or not by default:
                                        $sM = '';
-                                       if (isset($itemArray[$p[1]]))   {
+                                       if (isset($itemArray[$p[1]])) {
                                                $sM = ' checked="checked"';
                                                unset($itemArray[$p[1]]);
                                        }
 
                                                // Icon:
-                                       $selIconFile = '';
-                                       if ($p[2])      {
-                                               list($selIconFile,$selIconInfo) = $this->getIcon($p[2]);
-                                       }
+                                       if ($p[2]) {
+                                               $selIcon = $p[2];
+                                       } else {
+                                               $selIcon = t3lib_iconWorks::getSpriteIcon('empty-empty');
+                                       }
 
                                                // Compile row:
                                        $rowId = uniqid('select_checkbox_row_');
@@ -1798,85 +1828,92 @@ class t3lib_TCEforms    {
                                        $onClick = 'this.attributes.getNamedItem("class").nodeValue = ' . $this->elName($PA['itemFormElName'] . '[' . $c . ']') . '.checked ? "c-selectedItem" : "c-unselectedItem";';
                                        $setAll[] = $this->elName($PA['itemFormElName'] . '[' . $c . ']') . '.checked=1;';
                                        $setAll[] .= '$(\'' . $rowId . '\').removeClassName(\'c-unselectedItem\');$(\'' . $rowId . '\').addClassName(\'c-selectedItem\');';
-                                       $unSetAll[] = $this->elName($PA['itemFormElName'].'['.$c.']').'.checked=0;';
+                                       $unSetAll[] = $this->elName($PA['itemFormElName'] . '[' . $c . ']') . '.checked=0;';
                                        $unSetAll[] .= '$(\'' . $rowId . '\').removeClassName(\'c-selectedItem\');$(\'' . $rowId . '\').addClassName(\'c-unselectedItem\');';
                                        $restoreCmd[] = $this->elName($PA['itemFormElName'] . '[' . $c . ']') . '.checked=' . ($sM ? 1 : 0) . ';' .
-                                                               '$(\'' . $rowId . '\').removeClassName(\'c-selectedItem\');$(\'' . $rowId . '\').removeClassName(\'c-unselectedItem\');' .
-                                                               '$(\'' . $rowId . '\').addClassName(\'c-' . ($sM ? '' : 'un') . 'selectedItem\');';
-
-                                       $hasHelp = ($p[3] !='');
+                                                                       '$(\'' . $rowId . '\').removeClassName(\'c-selectedItem\');$(\'' . $rowId . '\').removeClassName(\'c-unselectedItem\');' .
+                                                                       '$(\'' . $rowId . '\').addClassName(\'c-' . ($sM ? '' : 'un') . 'selectedItem\');';
+
+                                               // Check if some help text is available
+                                               // Since TYPO3 4.5 help text is expected to be an associative array
+                                               // with two key, "title" and "description"
+                                               // For the sake of backwards compatibility, we test if the help text
+                                               // is a string and use it as a description (this could happen if items
+                                               // are modified with an itemProcFunc)
+                                       $hasHelp = FALSE;
+                                       $help = '';
+                                       $helpArray = array();
+                                       if ((is_array($p[3]) && count($p[3]) > 0) || !empty($p[3])) {
+                                               $hasHelp = TRUE;
+                                               if (is_array($p[3])) {
+                                                       $helpArray = $p[3];
+                                               } else {
+                                                       $helpArray['description'] = $p[3];
+                                               }
+                                       }
 
                                        $label = t3lib_div::deHSCentities(htmlspecialchars($p[0]));
-                                       $help = $hasHelp ? '<span class="typo3-csh-inline show-right"><span class="header">' . $label . '</span>' .
-                                               '<span class="paragraph">' . $GLOBALS['LANG']->hscAndCharConv(nl2br(trim(htmlspecialchars($p[3]))), false) . '</span></span>' : '';
-
-                                       if ($hasHelp && $this->edit_showFieldHelp == 'icon') {
-                                               $helpIcon  = '<a class="typo3-csh-link" href="#">';
-                                               $helpIcon .= t3lib_iconWorks::getSpriteIcon('actions-system-help-open');
-                                               $helpIcon .= $help;
-                                               $helpIcon .= '</a>';
-                                               $help = $helpIcon;
+                                       if ($hasHelp) {
+                                               $help = t3lib_BEfunc::wrapInHelp('', '', '', $helpArray);
                                        }
 
                                        $tRows[] = '
-                                               <tr id="' . $rowId . '" class="'.($sM ? 'c-selectedItem' : 'c-unselectedItem').'" onclick="'.htmlspecialchars($onClick).'" style="cursor: pointer;">
-                                                       <td width="12"><input type="checkbox"'.$this->insertDefStyle('check').' name="'.htmlspecialchars($PA['itemFormElName'].'['.$c.']').'" value="'.htmlspecialchars($p[1]).'"'.$sM.' onclick="'.htmlspecialchars($sOnChange).'"'.$PA['onFocus'].' /></td>
-                                                       <td class="c-labelCell" onclick="'.htmlspecialchars($onClickCell).'">'.
-                                                               ($selIconFile ? '<img src="'.$selIconFile.'" '.$selIconInfo[3].' vspace="2" border="0" class="absmiddle" style="margin-right: 4px;" alt="" />' : '').
-                                                               $label .
-                                                               '</td>
-                                                               <td class="c-descr" onclick="'.htmlspecialchars($onClickCell).'">' . (strcmp($p[3],'') ? $help : '') . '</td>
+                                               <tr id="' . $rowId . '" class="' . ($sM ? 'c-selectedItem' : 'c-unselectedItem') . '" onclick="' . htmlspecialchars($onClick) . '" style="cursor: pointer;">
+                                                       <td class="c-checkbox"><input type="checkbox"' . $this->insertDefStyle('check') . ' name="' . htmlspecialchars($PA['itemFormElName'] . '[' . $c . ']') . '" value="' . htmlspecialchars($p[1]) . '"' . $sM . ' onclick="' . htmlspecialchars($sOnChange) . '"' . $PA['onFocus'] . ' /></td>
+                                                       <td class="c-labelCell" onclick="' . htmlspecialchars($onClickCell) . '">' .
+                                                          $this->getIconHtml($selIcon) .
+                                                          $label .
+                                                          '</td>
+                                                               <td class="c-descr" onclick="' . htmlspecialchars($onClickCell) . '">' . ((empty($help)) ? '' : $help) . '</td>
                                                </tr>';
                                        $c++;
                                }
                        }
-
-                               // Remaining checkboxes will get their set-all link:
-                       if (count($setAll))     {
-                                       $tRows[] = '
-                                               <tr class="c-header-checkbox-controls">
-                                                       <td colspan="3">'.
-                                                               '<a href="#" onclick="' . htmlspecialchars(implode('', $setAll).' return false;') . '">' .
-                                                               htmlspecialchars($this->getLL('l_checkAll')) .
-                                                               '</a>
-                                                               <a href="#" onclick="' . htmlspecialchars(implode('', $unSetAll).' return false;') . '">' .
-                                                               htmlspecialchars($this->getLL('l_uncheckAll')) .
-                                                               '</a>
-                                                       </td>
-                                               </tr>';
-                       }
                }
 
                        // Remaining values (invalid):
-               if (count($itemArray) && !$PA['fieldTSConfig']['disableNoMatchingValueElement'] && !$config['disableNoMatchingValueElement'])   {
-                       foreach($itemArray as $theNoMatchValue => $temp)        {
+               if (count($itemArray) && !$PA['fieldTSConfig']['disableNoMatchingValueElement'] && !$config['disableNoMatchingValueElement']) {
+                       foreach ($itemArray as $theNoMatchValue => $temp) {
                                        // Compile <checkboxes> tag:
-                               array_unshift($tRows,'
+                               array_unshift($tRows, '
                                                <tr class="c-invalidItem">
-                                                       <td><input type="checkbox"'.$this->insertDefStyle('check').' name="'.htmlspecialchars($PA['itemFormElName'].'['.$c.']').'" value="'.htmlspecialchars($theNoMatchValue).'" checked="checked" onclick="'.htmlspecialchars($sOnChange).'"'.$PA['onFocus'].$disabled.' /></td>
-                                                       <td class="c-labelCell">'.
-                                                               t3lib_div::deHSCentities(htmlspecialchars(@sprintf($nMV_label, $theNoMatchValue))).
-                                                               '</td><td>&nbsp;</td>
+                                                       <td class="c-checkbox"><input type="checkbox"' . $this->insertDefStyle('check') . ' name="' . htmlspecialchars($PA['itemFormElName'] . '[' . $c . ']') . '" value="' . htmlspecialchars($theNoMatchValue) . '" checked="checked" onclick="' . htmlspecialchars($sOnChange) . '"' . $PA['onFocus'] . $disabled . ' /></td>
+                                                       <td class="c-labelCell">' .
+                                                                         t3lib_div::deHSCentities(htmlspecialchars(@sprintf($nMV_label, $theNoMatchValue))) .
+                                                                         '</td><td>&nbsp;</td>
                                                </tr>');
                                $c++;
                        }
                }
 
                        // Add an empty hidden field which will send a blank value if all items are unselected.
-               $item .= '<input type="hidden" name="'.htmlspecialchars($PA['itemFormElName']) . '" value="" />';
-
-                       // Add revert icon
-               if (is_array($restoreCmd)) {
-                       $item .= '<a href="#" onclick="' . implode('', $restoreCmd).' return false;' . '">' .
-                               t3lib_iconWorks::getSpriteIcon('actions-edit-undo', array('title' => htmlspecialchars($this->getLL('l_revertSelection')))) . '</a>';
+               $item .= '<input type="hidden" name="' . htmlspecialchars($PA['itemFormElName']) . '" value="" />';
+
+                       // Remaining checkboxes will get their set-all link:
+               if (count($setAll)) {
+                       $tableHead = '<thead>
+                                       <tr class="c-header-checkbox-controls t3-row-header">
+                                               <td class="c-checkbox">
+                                               <input type="checkbox" class="checkbox" onclick="if (checked) {' . htmlspecialchars(implode('', $setAll) . '} else {' .  implode('', $unSetAll) . '}') . '">
+                                               </td>
+                                               <td colspan="2">
+                                               </td>
+                                       </tr></thead>';
                }
                        // Implode rows in table:
                $item .= '
-                       <table border="0" cellpadding="0" cellspacing="0" class="typo3-TCEforms-select-checkbox">'.
-                               implode('',$tRows).'
+                       <table border="0" cellpadding="0" cellspacing="0" class="typo3-TCEforms-select-checkbox">' .
+                               $tableHead .
+                               '<tbody>' . implode('', $tRows) . '</tbody>
                        </table>
                        ';
 
+                       // Add revert icon
+               if (is_array($restoreCmd)) {
+                       $item .= '<a href="#" onclick="' . implode('', $restoreCmd) . ' return false;' . '">' .
+                                        t3lib_iconWorks::getSpriteIcon('actions-edit-undo', array('title' => htmlspecialchars($this->getLL('l_revertSelection')))) . '</a>';
+               }
+
                return $item;
        }
 
@@ -1894,32 +1931,33 @@ class t3lib_TCEforms    {
         * @return      string          The HTML code for the item
         * @see getSingleField_typeSelect()
         */
-       function getSingleField_typeSelect_singlebox($table,$field,$row,&$PA,$config,$selItems,$nMV_label)      {
+       function getSingleField_typeSelect_singlebox($table, $field, $row, &$PA, $config, $selItems, $nMV_label) {
 
                        // Get values in an array (and make unique, which is fine because there can be no duplicates anyway):
                $itemArray = array_flip($this->extractValuesOnlyFromValueLabelList($PA['itemFormElValue']));
 
+               $item = '';
                $disabled = '';
-               if($this->renderReadonly || $config['readOnly'])  {
+               if ($this->renderReadonly || $config['readOnly']) {
                        $disabled = ' disabled="disabled"';
                }
 
                        // Traverse the Array of selector box items:
                $opt = array();
-               $restoreCmd = array();  // Used to accumulate the JS needed to restore the original selection.
+               $restoreCmd = array(); // Used to accumulate the JS needed to restore the original selection.
                $c = 0;
-               foreach($selItems as $p)        {
+               foreach ($selItems as $p) {
                                // Selected or not by default:
                        $sM = '';
-                       if (isset($itemArray[$p[1]]))   {
+                       if (isset($itemArray[$p[1]])) {
                                $sM = ' selected="selected"';
-                               $restoreCmd[] = $this->elName($PA['itemFormElName'].'[]').'.options['.$c.'].selected=1;';
+                               $restoreCmd[] = $this->elName($PA['itemFormElName'] . '[]') . '.options[' . $c . '].selected=1;';
                                unset($itemArray[$p[1]]);
                        }
 
                                // Non-selectable element:
                        $nonSel = '';
-                       if (!strcmp($p[1],'--div--'))   {
+                       if (!strcmp($p[1], '--div--')) {
                                $nonSel = ' onclick="this.selected=0;" class="c-divider"';
                        }
 
@@ -1929,59 +1967,60 @@ class t3lib_TCEforms    {
                        }
 
                                // Compile <option> tag:
-                       $opt[] = '<option value="'.htmlspecialchars($p[1]).'"'.
-                                               $sM.
-                                               $nonSel.
-                                               ($styleAttrValue ? ' style="'.htmlspecialchars($styleAttrValue).'"' : '').
-                                               '>'.t3lib_div::deHSCentities(htmlspecialchars($p[0])).'</option>';
+                       $opt[] = '<option value="' . htmlspecialchars($p[1]) . '"' .
+                                        $sM .
+                                        $nonSel .
+                                        ($styleAttrValue ? ' style="' . htmlspecialchars($styleAttrValue) . '"' : '') .
+                                        '>' . t3lib_div::deHSCentities(htmlspecialchars($p[0])) . '</option>';
                        $c++;
                }
 
                        // Remaining values:
-               if (count($itemArray) && !$PA['fieldTSConfig']['disableNoMatchingValueElement'] && !$config['disableNoMatchingValueElement'])   {
-                       foreach($itemArray as $theNoMatchValue => $temp)        {
+               if (count($itemArray) && !$PA['fieldTSConfig']['disableNoMatchingValueElement'] && !$config['disableNoMatchingValueElement']) {
+                       foreach ($itemArray as $theNoMatchValue => $temp) {
                                        // Compile <option> tag:
-                               array_unshift($opt,'<option value="'.htmlspecialchars($theNoMatchValue).'" selected="selected">'.t3lib_div::deHSCentities(htmlspecialchars(@sprintf($nMV_label, $theNoMatchValue))).'</option>');
+                               array_unshift($opt, '<option value="' . htmlspecialchars($theNoMatchValue) . '" selected="selected">' . t3lib_div::deHSCentities(htmlspecialchars(@sprintf($nMV_label, $theNoMatchValue))) . '</option>');
                        }
                }
 
                        // Compile selector box:
-               $sOnChange = implode('',$PA['fieldChangeFunc']);
-               $selector_itemListStyle = isset($config['itemListStyle']) ? ' style="'.htmlspecialchars($config['itemListStyle']).'"' : ' style="'.$this->defaultMultipleSelectorStyle.'"';
+               $sOnChange = implode('', $PA['fieldChangeFunc']);
+               $selector_itemListStyle = isset($config['itemListStyle']) ? ' style="' . htmlspecialchars($config['itemListStyle']) . '"' : ' style="' . $this->defaultMultipleSelectorStyle . '"';
                $size = intval($config['size']);
-               $size = $config['autoSizeMax'] ? t3lib_div::intInRange(count($selItems)+1,t3lib_div::intInRange($size,1),$config['autoSizeMax']) : $size;
-               $selectBox = '<select id="' . uniqid('tceforms-multiselect-') . '" name="'.$PA['itemFormElName'].'[]"'.
-                                               $this->insertDefStyle('select', 'tceforms-multiselect').
-                                               ($size ? ' size="'.$size.'"' : '').
-                                               ' multiple="multiple" onchange="'.htmlspecialchars($sOnChange).'"'.
-                                               $PA['onFocus'].
-                                               $selector_itemListStyle.
-                                               $disabled.'>
-                                               '.
-                                       implode('
-                                               ',$opt).'
+               $cssPrefix = ($size === 1) ? 'tceforms-select' : 'tceforms-multiselect';
+               $size = $config['autoSizeMax'] ? t3lib_div::intInRange(count($selItems) + 1, t3lib_div::intInRange($size, 1), $config['autoSizeMax']) : $size;
+               $selectBox = '<select id="' . uniqid($cssPrefix) . '" name="' . $PA['itemFormElName'] . '[]"' .
+                                        $this->insertDefStyle('select', $cssPrefix) .
+                                        ($size ? ' size="' . $size . '"' : '') .
+                                        ' multiple="multiple" onchange="' . htmlspecialchars($sOnChange) . '"' .
+                                        $PA['onFocus'] .
+                                        $selector_itemListStyle .
+                                        $disabled . '>
+                                               ' .
+                                        implode('
+                                               ', $opt) . '
                                        </select>';
 
                        // Add an empty hidden field which will send a blank value if all items are unselected.
                if (!$disabled) {
-                       $item.='<input type="hidden" name="'.htmlspecialchars($PA['itemFormElName']).'" value="" />';
+                       $item .= '<input type="hidden" name="' . htmlspecialchars($PA['itemFormElName']) . '" value="" />';
                }
 
                        // Put it all into a table:
-               $item.= '
+               $item .= '
                        <table border="0" cellspacing="0" cellpadding="0" width="1" class="typo3-TCEforms-select-singlebox">
                                <tr>
                                        <td>
-                                       '.$selectBox.'
+                                       ' . $selectBox . '
                                        <br/>
-                                       <em>'.
-                                               htmlspecialchars($this->getLL('l_holdDownCTRL')).
-                                               '</em>
+                                       <em>' .
+                                htmlspecialchars($this->getLL('l_holdDownCTRL')) .
+                                '</em>
                                        </td>
                                        <td valign="top">
-                                         <a href="#" onclick="'.htmlspecialchars($this->elName($PA['itemFormElName'].'[]').'.selectedIndex=-1;'.implode('',$restoreCmd).' return false;').'" title="' . htmlspecialchars($this->getLL('l_revertSelection')) . '">' .
-                                           t3lib_iconWorks::getSpriteIcon('actions-edit-undo') .
-                                        '</a>
+                                         <a href="#" onclick="' . htmlspecialchars($this->elName($PA['itemFormElName'] . '[]') . '.selectedIndex=-1;' . implode('', $restoreCmd) . ' return false;') . '" title="' . htmlspecialchars($this->getLL('l_revertSelection')) . '">' .
+                                t3lib_iconWorks::getSpriteIcon('actions-edit-undo') .
+                                '</a>
                                        </td>
                                </tr>
                        </table>
@@ -2004,28 +2043,31 @@ class t3lib_TCEforms    {
         * @return      string          The HTML code for the item
         * @see getSingleField_typeSelect()
         */
-       function getSingleField_typeSelect_multiple($table,$field,$row,&$PA,$config,$selItems,$nMV_label)       {
+       function getSingleField_typeSelect_multiple($table, $field, $row, &$PA, $config, $selItems, $nMV_label) {
 
+               $item = '';
                $disabled = '';
-               if($this->renderReadonly || $config['readOnly'])  {
+               if ($this->renderReadonly || $config['readOnly']) {
                        $disabled = ' disabled="disabled"';
                }
 
                        // Setting this hidden field (as a flag that JavaScript can read out)
                if (!$disabled) {
-                       $item.= '<input type="hidden" name="'.$PA['itemFormElName'].'_mul" value="'.($config['multiple']?1:0).'" />';
+                       $item .= '<input type="hidden" name="' . $PA['itemFormElName'] . '_mul" value="' . ($config['multiple'] ? 1 : 0) . '" />';
                }
 
                        // Set max and min items:
-               $maxitems = t3lib_div::intInRange($config['maxitems'],0);
-               if (!$maxitems) $maxitems=100000;
-               $minitems = t3lib_div::intInRange($config['minitems'],0);
+               $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->registerRequiredProperty('range', $PA['itemFormElName'], array($minitems,$maxitems,'imgName'=>$table.'_'.$row['uid'].'_'.$field));
+               $this->registerRequiredProperty('range', $PA['itemFormElName'], array($minitems, $maxitems, 'imgName' => $table . '_' . $row['uid'] . '_' . $field));
 
                        // Get "removeItems":
-               $removeItems = t3lib_div::trimExplode(',',$PA['fieldTSConfig']['removeItems'],1);
+               $removeItems = t3lib_div::trimExplode(',', $PA['fieldTSConfig']['removeItems'], 1);
 
                        // Get the array with selected items:
                $itemArray = t3lib_div::trimExplode(',', $PA['itemFormElValue'], 1);
@@ -2035,11 +2077,11 @@ class t3lib_TCEforms    {
                $itemArray = t3lib_div::keepItemsInArray($itemArray, $PA['fieldTSConfig']['keepItems'], $keepItemsFunc);
 
                        // Perform modification of the selected items array:
-               foreach($itemArray as $tk => $tv) {
-                       $tvP = explode('|',$tv,2);
+               foreach ($itemArray as $tk => $tv) {
+                       $tvP = explode('|', $tv, 2);
                        $evalValue = $tvP[0];
-                       $isRemoved = in_array($evalValue,$removeItems)  || ($config['form_type']=='select' && $config['authMode'] && !$GLOBALS['BE_USER']->checkAuthMode($table,$field,$evalValue,$config['authMode']));
-                       if ($isRemoved && !$PA['fieldTSConfig']['disableNoMatchingValueElement'] && !$config['disableNoMatchingValueElement'])  {
+                       $isRemoved = in_array($evalValue, $removeItems) || ($config['form_type'] == 'select' && $config['authMode'] && !$GLOBALS['BE_USER']->checkAuthMode($table, $field, $evalValue, $config['authMode']));
+                       if ($isRemoved && !$PA['fieldTSConfig']['disableNoMatchingValueElement'] && !$config['disableNoMatchingValueElement']) {
                                $tvP[1] = rawurlencode(@sprintf($nMV_label, $evalValue));
                        } elseif (isset($PA['fieldTSConfig']['altLabels.'][$evalValue])) {
                                $tvP[1] = rawurlencode($this->sL($PA['fieldTSConfig']['altLabels.'][$evalValue]));
@@ -2053,62 +2095,62 @@ class t3lib_TCEforms    {
                                        }
                                }
                        }
-                       $itemArray[$tk] = implode('|',$tvP);
+                       $itemArray[$tk] = implode('|', $tvP);
                }
                $itemsToSelect = '';
 
-               if(!$disabled) {
+               if (!$disabled) {
                                // Create option tags:
                        $opt = array();
                        $styleAttrValue = '';
-                       foreach($selItems as $p)        {
-                               if ($config['iconsInOptionTags'])       {
+                       foreach ($selItems as $p) {
+                               if ($config['iconsInOptionTags']) {
                                        $styleAttrValue = $this->optionTagStyle($p[2]);
                                }
-                               $opt[]= '<option value="'.htmlspecialchars($p[1]).'"'.
-                                                               ($styleAttrValue ? ' style="'.htmlspecialchars($styleAttrValue).'"' : '').
-                                                               '>' . $p[0] . '</option>';
+                               $opt[] = '<option value="' . htmlspecialchars($p[1]) . '"' .
+                                                ($styleAttrValue ? ' style="' . htmlspecialchars($styleAttrValue) . '"' : '') .
+                                                '>' . $p[0] . '</option>';
                        }
 
                                // Put together the selector box:
-                       $selector_itemListStyle = isset($config['itemListStyle']) ? ' style="'.htmlspecialchars($config['itemListStyle']).'"' : ' style="'.$this->defaultMultipleSelectorStyle.'"';
+                       $selector_itemListStyle = isset($config['itemListStyle']) ? ' style="' . htmlspecialchars($config['itemListStyle']) . '"' : ' style="' . $this->defaultMultipleSelectorStyle . '"';
                        $size = intval($config['size']);
-                       $size = $config['autoSizeMax'] ? t3lib_div::intInRange(count($itemArray)+1,t3lib_div::intInRange($size,1),$config['autoSizeMax']) : $size;
-                       if ($config['exclusiveKeys'])   {
-                               $sOnChange = 'setFormValueFromBrowseWin(\''.$PA['itemFormElName'].'\',this.options[this.selectedIndex].value,this.options[this.selectedIndex].text,\''.$config['exclusiveKeys'].'\'); ';
+                       $size = $config['autoSizeMax'] ? t3lib_div::intInRange(count($itemArray) + 1, t3lib_div::intInRange($size, 1), $config['autoSizeMax']) : $size;
+                       if ($config['exclusiveKeys']) {
+                               $sOnChange = 'setFormValueFromBrowseWin(\'' . $PA['itemFormElName'] . '\',this.options[this.selectedIndex].value,this.options[this.selectedIndex].text,\'' . $config['exclusiveKeys'] . '\'); ';
                        } else {
-                               $sOnChange = 'setFormValueFromBrowseWin(\''.$PA['itemFormElName'].'\',this.options[this.selectedIndex].value,this.options[this.selectedIndex].text); ';
+                               $sOnChange = 'setFormValueFromBrowseWin(\'' . $PA['itemFormElName'] . '\',this.options[this.selectedIndex].value,this.options[this.selectedIndex].text); ';
                        }
-                       $sOnChange .= implode('',$PA['fieldChangeFunc']);
+                       $sOnChange .= implode('', $PA['fieldChangeFunc']);
                        $itemsToSelect = '
-                               <select id="' . uniqid('tceforms-multiselect-') . '" name="'.$PA['itemFormElName'].'_sel"'.
-                                                       $this->insertDefStyle('select', 'tceforms-multiselect tceforms-itemstoselect').
-                                                       ($size ? ' size="'.$size.'"' : '').
-                                                       ' onchange="'.htmlspecialchars($sOnChange).'"'.
-                                                       $PA['onFocus'].
-                                                       $selector_itemListStyle.'>
-                                       '.implode('
-                                       ',$opt).'
+                               <select id="' . uniqid('tceforms-multiselect-') . '" name="' . $PA['itemFormElName'] . '_sel"' .
+                                                        $this->insertDefStyle('select', 'tceforms-multiselect tceforms-itemstoselect') .
+                                                        ($size ? ' size="' . $size . '"' : '') .
+                                                        ' onchange="' . htmlspecialchars($sOnChange) . '"' .
+                                                        $PA['onFocus'] .
+                                                        $selector_itemListStyle . '>
+                                       ' . implode('
+                                       ', $opt) . '
                                </select>';
                }
 
                        // Pass to "dbFileIcons" function:
                $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),
+                       '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 />',
-                               'items' => $this->getLL('l_items').':<br />'
+                               'selector' => $this->getLL('l_selected') . ':<br />',
+                               'items' => $this->getLL('l_items') . ':<br />'
                        ),
                        'noBrowser' => 1,
                        'thumbnails' => $itemsToSelect,
                        'readOnly' => $disabled
                );
-               $item.= $this->dbFileIcons($PA['itemFormElName'],'','',$itemArray,'',$params,$PA['onFocus']);
+               $item .= $this->dbFileIcons($PA['itemFormElName'], '', '', $itemArray, '', $params, $PA['onFocus']);
 
                return $item;
        }
@@ -2123,138 +2165,141 @@ class t3lib_TCEforms  {
         * @param       array           An array with additional configuration options.
         * @return      string          The HTML code for the TCEform field
         */
-       function getSingleField_typeGroup($table,$field,$row,&$PA)      {
+       function getSingleField_typeGroup($table, $field, $row, &$PA) {
                        // Init:
                $config = $PA['fieldConf']['config'];
                $internal_type = $config['internal_type'];
                $show_thumbs = $config['show_thumbs'];
                $size = intval($config['size']);
-               $maxitems = t3lib_div::intInRange($config['maxitems'],0);
-               if (!$maxitems) $maxitems=100000;
-               $minitems = t3lib_div::intInRange($config['minitems'],0);
+               $maxitems = t3lib_div::intInRange($config['maxitems'], 0);
+               if (!$maxitems) {
+                       $maxitems = 100000;
+               }
+               $minitems = t3lib_div::intInRange($config['minitems'], 0);
                $allowed = trim($config['allowed']);
                $disallowed = trim($config['disallowed']);
 
+               $item = '';
                $disabled = '';
-               if($this->renderReadonly || $config['readOnly'])  {
+               if ($this->renderReadonly || $config['readOnly']) {
                        $disabled = ' disabled="disabled"';
                }
 
-               $item.= '<input type="hidden" name="'.$PA['itemFormElName'].'_mul" value="'.($config['multiple']?1:0).'"'.$disabled.' />';
-               $this->registerRequiredProperty('range', $PA['itemFormElName'], array($minitems,$maxitems,'imgName'=>$table.'_'.$row['uid'].'_'.$field));
-               $info='';
+               $item .= '<input type="hidden" name="' . $PA['itemFormElName'] . '_mul" value="' . ($config['multiple'] ? 1 : 0) . '"' . $disabled . ' />';
+               $this->registerRequiredProperty('range', $PA['itemFormElName'], array($minitems, $maxitems, 'imgName' => $table . '_' . $row['uid'] . '_' . $field));
+               $info = '';
 
                        // "Extra" configuration; Returns configuration for the field based on settings found in the "types" fieldlist. See http://typo3.org/documentation/document-library/doc_core_api/Wizards_Configuratio/.
                $specConf = $this->getSpecConfFromString($PA['extra'], $PA['fieldConf']['defaultExtras']);
 
+               $PA['itemFormElID_file'] = $PA['itemFormElID'] . '_files';
+
+                       // whether the list controls should be disabled
+               $noList = isset($config['disable_controls']) && t3lib_div::inList($config['disable_controls'], 'list');
+
+                       // if maxitems==1 then automatically replace the current item (in list and file selector)
+               if ($maxitems === 1) {
+                       $this->additionalJS_post[] = "TBE_EDITOR.clearBeforeSettingFormValueFromBrowseWin['" . $PA['itemFormElName'] . "'] = {
+                                       itemFormElID_file: '" . $PA['itemFormElID_file'] . "'
+                               }";
+                       $PA['fieldChangeFunc']['TBE_EDITOR_fieldChanged'] = "setFormValueManipulate('" . $PA['itemFormElName'] . "', 'Remove'); " . $PA['fieldChangeFunc']['TBE_EDITOR_fieldChanged'];
+               } elseif ($noList) {
+                               // if the list controls have been removed and the maximum number is reached, remove the first entry to avoid "write once" field
+                       $PA['fieldChangeFunc']['TBE_EDITOR_fieldChanged'] = "setFormValueManipulate('" . $PA['itemFormElName'] . "', 'RemoveFirstIfFull', '" . $maxitems . "'); " . $PA['fieldChangeFunc']['TBE_EDITOR_fieldChanged'];
+               }
+
                        // Acting according to either "file" or "db" type:
-               switch((string)$config['internal_type'])        {
+               switch ((string) $config['internal_type']) {
                        case 'file_reference':
                                $config['uploadfolder'] = '';
                                // Fall through
-                       case 'file':    // If the element is of the internal type "file":
+                       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).' ';
+                               $tempFT = t3lib_div::trimExplode(',', $allowed, TRUE);
+                               if (!count($tempFT)) {
+                                       $info .= '*';
+                               }
+                               foreach ($tempFT as $ext) {
+                                       if ($ext) {
+                                               $info .= strtoupper($ext) . ' ';
                                        }
                                }
                                        // 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).' ';
+                               $tempFT_dis = t3lib_div::trimExplode(',', $disallowed, TRUE);
+                               if (count($tempFT_dis)) {
+                                       $info .= '<br />';
+                               }
+                               foreach ($tempFT_dis as $ext) {
+                                       if ($ext) {
+                                               $info .= '-' . strtoupper($ext) . ' ';
                                        }
                                }
 
                                        // Making the array of file items:
-                               $itemArray = t3lib_div::trimExplode(',',$PA['itemFormElValue'],1);
+                               $itemArray = t3lib_div::trimExplode(',', $PA['itemFormElValue'], TRUE);
 
                                        // Showing thumbnails:
                                $thumbsnail = '';
-                               if ($show_thumbs)       {
+                               if ($show_thumbs) {
                                        $imgs = array();
-                                       foreach($itemArray as $imgRead) {
-                                               $imgP = explode('|',$imgRead);
+                                       foreach ($itemArray as $imgRead) {
+                                               $imgP = explode('|', $imgRead);
                                                $imgPath = rawurldecode($imgP[0]);
 
                                                $rowCopy = array();
                                                $rowCopy[$field] = $imgPath;
 
-                                                       // Icon + clickmenu:
-                                               $absFilePath = t3lib_div::getFileAbsFileName($config['uploadfolder'] ? $config['uploadfolder'] . '/' . $imgPath : $imgPath);
-
-                                               $fI = pathinfo($imgPath);
-                                               $fileIcon = t3lib_iconWorks::getSpriteIconForFile(
-                                                       strtolower($fI['extension']),
-                                                       array(
-                                                               'title' => htmlspecialchars(
-                                                                       $fI['basename'] .
-                                                                       ($absFilePath && @is_file($absFilePath)
-                                                                               ? ' (' . t3lib_div::formatSize(filesize($absFilePath)) . 'bytes)' :
-                                                                               ' - FILE NOT FOUND!'
-                                                                       )
-                                                               )
-                                                       )
-                                               );
-
-                                               $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).
-                                                                       $imgPath.
-                                                                       '</span>';
+                                               $imgs[] = '<span class="nobr">' . t3lib_BEfunc::thumbCode($rowCopy, $table, $field, $this->backPath, 'thumbs.php', $config['uploadfolder'], 0, ' align="middle"') .
+                                                                 $imgPath .
+                                                                 '</span>';
                                        }
-                                       $thumbsnail = implode('<br />',$imgs);
+                                       $thumbsnail = implode('<br />', $imgs);
                                }
 
                                        // Creating the element:
-                               $noList = isset($config['disable_controls']) && t3lib_div::inList($config['disable_controls'], 'list');
                                $params = array(
                                        'size' => $size,
-                                       'dontShowMoveIcons' => ($maxitems<=1),
-                                       'autoSizeMax' => t3lib_div::intInRange($config['autoSizeMax'],0),
+                                       'dontShowMoveIcons' => ($maxitems <= 1),
+                                       'autoSizeMax' => t3lib_div::intInRange($config['autoSizeMax'], 0),
                                        'maxitems' => $maxitems,
-                                       'style' => isset($config['selectedListStyle']) ? ' style="'.htmlspecialchars($config['selectedListStyle']).'"' : ' style="'.$this->defaultMultipleSelectorStyle.'"',
+                                       'style' => isset($config['selectedListStyle']) ? ' style="' . htmlspecialchars($config['selectedListStyle']) . '"' : ' style="' . $this->defaultMultipleSelectorStyle . '"',
                                        'info' => $info,
                                        'thumbnails' => $thumbsnail,
                                        'readOnly' => $disabled,
                                        'noBrowser' => $noList || (isset($config['disable_controls']) && t3lib_div::inList($config['disable_controls'], 'browser')),
                                        'noList' => $noList,
                                );
-                               $item.= $this->dbFileIcons($PA['itemFormElName'],'file',implode(',',$tempFT),$itemArray,'',$params,$PA['onFocus']);
+                               $item .= $this->dbFileIcons($PA['itemFormElName'], 'file', implode(',', $tempFT), $itemArray, '', $params, $PA['onFocus']);
 
-                               if(!$disabled && !(isset($config['disable_controls']) && t3lib_div::inList($config['disable_controls'], 'upload'))) {
+                               if (!$disabled && !(isset($config['disable_controls']) && t3lib_div::inList($config['disable_controls'], 'upload'))) {
                                                // Adding the upload field:
                                        if ($this->edit_docModuleUpload && $config['uploadfolder']) {
-                                               $item .= '<input type="file" name="' . $PA['itemFormElName_file'] . '"' . $this->formWidth() . ' size="60" onchange="' . implode('', $PA['fieldChangeFunc']) . '" />';
+                                               $item .= '<div id="' . $PA['itemFormElID_file'] . '"><input type="file" name="' . $PA['itemFormElName_file'] . '" size="35" onchange="' . implode('', $PA['fieldChangeFunc']) . '" /></div>';
                                        }
                                }
                        break;
-                       case 'folder':  // If the element is of the internal type "folder":
+                       case 'folder': // If the element is of the internal type "folder":
 
                                        // array of folder items:
                                $itemArray = t3lib_div::trimExplode(',', $PA['itemFormElValue'], 1);
 
                                        // Creating the element:
-                               $noList = isset($config['disable_controls']) && t3lib_div::inList($config['disable_controls'], 'list');
                                $params = array(
-                                       'size'              => $size,
+                                       '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,
-                                       'readOnly'          => $disabled,
+                                       'autoSizeMax' => t3lib_div::intInRange($config['autoSizeMax'], 0),
+                                       'maxitems' => $maxitems,
+                                       'style' => isset($config['selectedListStyle']) ?
+                                                       ' style="' . htmlspecialchars($config['selectedListStyle']) . '"'
+                                                       : ' style="' . $this->defaultMultipleSelectorStyle . '"',
+                                       'info' => $info,
+                                       'readOnly' => $disabled,
                                        'noBrowser' => $noList || (isset($config['disable_controls']) && t3lib_div::inList($config['disable_controls'], 'browser')),
                                        'noList' => $noList,
                                );
 
-                               $item.= $this->dbFileIcons(
+                               $item .= $this->dbFileIcons(
                                        $PA['itemFormElName'],
                                        'folder',
                                        '',
@@ -2264,22 +2309,22 @@ class t3lib_TCEforms    {
                                        $PA['onFocus']
                                );
                        break;
-                       case 'db':      // If the element is of the internal type "db":
+                       case 'db': // If the element is of the internal type "db":
 
                                        // Creating string showing allowed types:
-                               $tempFT = t3lib_div::trimExplode(',', $allowed, true);
+                               $tempFT = t3lib_div::trimExplode(',', $allowed, TRUE);
                                if (!strcmp(trim($tempFT[0]), '*')) {
-                                       $onlySingleTableAllowed = false;
-                                       $info.='<span class="nobr">&nbsp;&nbsp;&nbsp;&nbsp;'.
-                                                       htmlspecialchars($this->getLL('l_allTables')).
-                                                       '</span><br />';
+                                       $onlySingleTableAllowed = FALSE;
+                                       $info .= '<span class="nobr">' .
+                                                        htmlspecialchars($this->getLL('l_allTables')) .
+                                                        '</span><br />';
                                } elseif ($tempFT) {
                                        $onlySingleTableAllowed = (count($tempFT) == 1);
                                        foreach ($tempFT as $theT) {
-                                               $info.= '<span class="nobr">&nbsp;&nbsp;&nbsp;&nbsp;' .
-                                                               t3lib_iconWorks::getSpriteIconForRecord($theT, array()) .
-                                                               htmlspecialchars($this->sL($GLOBALS['TCA'][$theT]['ctrl']['title'])) .
-                                                               '</span><br />';
+                                               $info .= '<span class="nobr">' .
+                                                                t3lib_iconWorks::getSpriteIconForRecord($theT, array()) .
+                                                                htmlspecialchars($this->sL($GLOBALS['TCA'][$theT]['ctrl']['title'])) .
+                                                                '</span><br />';
                                        }
                                }
 
@@ -2288,63 +2333,62 @@ class t3lib_TCEforms    {
                                $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]);
-                                       // For the case that no table was found and only a single table is defined to be allowed, use that one:
+                               $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]);
+                                               // For the case that no table was found and only a single table is defined to be allowed, use that one:
                                        if (!$this_table && $onlySingleTableAllowed) {
                                                $this_table = $allowed;
                                        }
-                                       $itemArray[] = array('table'=>$this_table, 'id'=>$this_uid);
-                                       if (!$disabled && $show_thumbs) {
-                                               $rr = t3lib_BEfunc::getRecordWSOL($this_table,$this_uid);
-                                               $imgs[] = '<span class="nobr">'.
-                                                               $this->getClickMenu(
-                                                                       t3lib_iconWorks::getSpriteIconForRecord(
-                                                                               $this_table,
-                                                                               $rr,
-                                                                               array(
-                                                                                       'style' => 'vertical-align:top',
-                                                                                       'title' => htmlspecialchars(t3lib_BEfunc::getRecordPath($rr['pid'], $perms_clause, 15) . ' [UID: ' . $rr['uid'] . ']"')
-                                                                               )
-                                                                       ),
-                                                                       $this_table,
-                                                                       $this_uid
-                                                               ) .
-                                                               '&nbsp;'.
-                                                               t3lib_BEfunc::getRecordTitle($this_table,$rr,TRUE).' <span class="typo3-dimmed"><em>['.$rr['uid'].']</em></span>'.
-                                                               '</span>';
+                                       $itemArray[] = array('table' => $this_table, 'id' => $this_uid);
+                                       if (!$disabled && $show_thumbs) {
+                                               $rr = t3lib_BEfunc::getRecordWSOL($this_table, $this_uid);
+                                               $imgs[] = '<span class="nobr">' .
+                                                                 $this->getClickMenu(
+                                                                         t3lib_iconWorks::getSpriteIconForRecord(
+                                                                                 $this_table,
+                                                                                 $rr,
+                                                                                 array(
+                                                                                          'style' => 'vertical-align:top',
+                                                                                          'title' => htmlspecialchars(t3lib_BEfunc::getRecordPath($rr['pid'], $perms_clause, 15) . ' [UID: ' . $rr['uid'] . ']')
+                                                                                 )
+                                                                         ),
+                                                                         $this_table,
+                                                                         $this_uid
+                                                                 ) .
+                                                                 '&nbsp;' .
+                                                                 t3lib_BEfunc::getRecordTitle($this_table, $rr, TRUE) . ' <span class="typo3-dimmed"><em>[' . $rr['uid'] . ']</em></span>' .
+                                                                 '</span>';
                                        }
                                }
-                               $thumbsnail='';
-                               if (!$disabled && $show_thumbs) {
-                                       $thumbsnail = implode('<br />',$imgs);
+                               $thumbsnail = '';
+                               if (!$disabled && $show_thumbs) {
+                                       $thumbsnail = implode('<br />', $imgs);
                                }
 
                                        // Creating the element:
-                               $noList = isset($config['disable_controls']) && t3lib_div::inList($config['disable_controls'], 'list');
                                $params = array(
                                        'size' => $size,
-                                       'dontShowMoveIcons' => ($maxitems<=1),
-                                       'autoSizeMax' => t3lib_div::intInRange($config['autoSizeMax'],0),
+                                       'dontShowMoveIcons' => ($maxitems <= 1),
+                                       'autoSizeMax' => t3lib_div::intInRange($config['autoSizeMax'], 0),
                                        'maxitems' => $maxitems,
-                                       'style' => isset($config['selectedListStyle']) ? ' style="'.htmlspecialchars($config['selectedListStyle']).'"' : ' style="'.$this->defaultMultipleSelectorStyle.'"',
+                                       'style' => isset($config['selectedListStyle']) ? ' style="' . htmlspecialchars($config['selectedListStyle']) . '"' : ' style="' . $this->defaultMultipleSelectorStyle . '"',
                                        'info' => $info,
                                        'thumbnails' => $thumbsnail,
                                        'readOnly' => $disabled,
                                        'noBrowser' => $noList || (isset($config['disable_controls']) && t3lib_div::inList($config['disable_controls'], 'browser')),
                                        'noList' => $noList,
                                );
-                               $item.= $this->dbFileIcons($PA['itemFormElName'],'db',implode(',',$tempFT),$itemArray,'',$params,$PA['onFocus'],$table,$field,$row['uid']);
+                               $item .= $this->dbFileIcons($PA['itemFormElName'], 'db', implode(',', $tempFT), $itemArray, '', $params, $PA['onFocus'], $table, $field, $row['uid']);
 
                        break;
                }
 
                        // Wizards:
-               $altItem = '<input type="hidden" name="'.$PA['itemFormElName'].'" value="'.htmlspecialchars($PA['itemFormElValue']).'" />';
+               $altItem = '<input type="hidden" name="' . $PA['itemFormElName'] . '" value="' . htmlspecialchars($PA['itemFormElValue']) . '" />';
                if (!$disabled) {
-                       $item = $this->renderWizards(array($item,$altItem),$config['wizards'],$table,$row,$field,$PA,$PA['itemFormElName'],$specConf);
+                       $item = $this->renderWizards(array($item, $altItem), $config['wizards'], $table, $row, $field, $PA, $PA['itemFormElName'], $specConf);
                }
 
                return $item;
@@ -2360,12 +2404,12 @@ class t3lib_TCEforms    {
         * @param       array           An array with additional configuration options.
         * @return      string          The HTML code for the TCEform field
         */
-       function getSingleField_typeNone($table,$field,$row,&$PA)       {
+       function getSingleField_typeNone($table, $field, $row, &$PA) {
                        // Init:
                $config = $PA['fieldConf']['config'];
                $itemValue = $PA['itemFormElValue'];
 
-               return $this->getSingleField_typeNone_render($config,$itemValue);
+               return $this->getSingleField_typeNone_render($config, $itemValue);
        }
 
        /**
@@ -2376,54 +2420,60 @@ class t3lib_TCEforms    {
         * @return      string          The HTML code for the display
         * @see getSingleField_typeNone();
         */
-       function getSingleField_typeNone_render($config,$itemValue)     {
+       function getSingleField_typeNone_render($config, $itemValue) {
 
-                               // is colorScheme[0] the right value?
-               $divStyle = 'border:solid 1px '.t3lib_div::modifyHTMLColorAll($this->colorScheme[0],-30).';'.$this->defStyle.$this->formElStyle('none').' background-color: '.$this->colorScheme[0].'; padding-left:1px;color:#555;';
+                       // is colorScheme[0] the right value?
+               $divStyle = 'border:solid 1px ' . t3lib_div::modifyHTMLColorAll($this->colorScheme[0], -30) . ';' . $this->defStyle . $this->formElStyle('none') . ' background-color: ' . $this->colorScheme[0] . '; padding-left:1px;color:#555;';
 
-               if ($config['format'])  {
+               if ($config['format']) {
                        $itemValue = $this->formatValue($config, $itemValue);
                }
 
                $rows = intval($config['rows']);
                if ($rows > 1) {
-                       if(!$config['pass_content']) {
+                       if (!$config['pass_content']) {
                                $itemValue = nl2br(htmlspecialchars($itemValue));
                        }
                                // like textarea
                        $cols = t3lib_div::intInRange($config['cols'] ? $config['cols'] : 30, 5, $this->maxTextareaWidth);
                        if (!$config['fixedRows']) {
                                $origRows = $rows = t3lib_div::intInRange($rows, 1, 20);
-                               if (strlen($itemValue)>$this->charsPerRow*2)    {
+                               if (strlen($itemValue) > $this->charsPerRow * 2) {
                                        $cols = $this->maxTextareaWidth;
-                                       $rows = t3lib_div::intInRange(round(strlen($itemValue)/$this->charsPerRow),count(explode(LF,$itemValue)),20);
-                                       if ($rows<$origRows)    $rows=$origRows;
+                                       $rows = t3lib_div::intInRange(round(strlen($itemValue) / $this->charsPerRow), count(explode(LF, $itemValue)), 20);
+                                       if ($rows < $origRows) {
+                                               $rows = $origRows;
+                                       }
                                }
                        }
 
-                       if ($this->docLarge)    $cols = round($cols*$this->form_largeComp);
-                       $width = ceil($cols*$this->form_rowsToStylewidth);
+                       if ($this->docLarge) {
+                               $cols = round($cols * $this->form_largeComp);
+                       }
+                       $width = ceil($cols * $this->form_rowsToStylewidth);
                                // hardcoded: 12 is the height of the font
-                       $height=$rows*12;
+                       $height = $rows * 12;
 
-                       $item='
-                               <div style="'.htmlspecialchars($divStyle.' overflow:auto; height:'.$height.'px; width:'.$width.'px;').'" class="'.htmlspecialchars($this->formElClass('none')).'">'.
-                               $itemValue.
-                               '</div>';
+                       $item = '
+                               <div style="' . htmlspecialchars($divStyle . ' overflow:auto; height:' . $height . 'px; width:' . $width . 'px;') . '" class="' . htmlspecialchars($this->formElClass('none')) . '">' .
+                                       $itemValue .
+                                       '</div>';
                } else {
-                       if(!$config['pass_content']) {
+                       if (!$config['pass_content']) {
                                $itemValue = htmlspecialchars($itemValue);
                        }
 
-                       $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);
+                       $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);
 
                                // overflow:auto crashes mozilla here. Title tag is usefull when text is longer than the div box (overflow:hidden).
                        $item = '
-                               <div style="'.htmlspecialchars($divStyle.' overflow:hidden; width:'.$width.'px;').'" class="'.htmlspecialchars($this->formElClass('none')).'" title="'.$itemValue.'">'.
-                               '<span class="nobr">'.(strcmp($itemValue,'')?$itemValue:'&nbsp;').'</span>'.
-                               '</div>';
+                               <div style="' . htmlspecialchars($divStyle . ' overflow:hidden; width:' . $width . 'px;') . '" class="' . htmlspecialchars($this->formElClass('none')) . '" title="' . $itemValue . '">' .
+                                       '<span class="nobr">' . (strcmp($itemValue, '') ? $itemValue : '&nbsp;') . '</span>' .
+                                       '</div>';
                }
 
                return $item;
@@ -2438,52 +2488,61 @@ class t3lib_TCEforms    {
         * @param       array           An array with additional configuration options.
         * @return      string          The HTML code for the TCEform field
         */
-       function getSingleField_typeFlex($table,$field,$row,&$PA)       {
+       function getSingleField_typeFlex($table, $field, $row, &$PA) {
 
                        // Data Structure:
-               $dataStructArray = t3lib_BEfunc::getFlexFormDS($PA['fieldConf']['config'],$row,$table);
+               $dataStructArray = t3lib_BEfunc::getFlexFormDS($PA['fieldConf']['config'], $row, $table);
+               $item = '';
+
+                       // Manipulate Flexform DS via TSConfig and group access lists
+               if (is_array($dataStructArray)) {
+                       $flexFormHelper = t3lib_div::makeInstance('t3lib_TCEforms_Flexforms');
+                       $dataStructArray = $flexFormHelper->modifyFlexFormDS($dataStructArray, $table, $field, $row, $PA['fieldConf']['config']);
+                       unset($flexFormHelper);
+               }
 
                        // Get data structure:
-               if (is_array($dataStructArray)) {
+               if (is_array($dataStructArray)) {
 
                                // Get data:
                        $xmlData = $PA['itemFormElValue'];
                        $xmlHeaderAttributes = t3lib_div::xmlGetHeaderAttribs($xmlData);
                        $storeInCharset = strtolower($xmlHeaderAttributes['encoding']);
-                       if ($storeInCharset)    {
-                               $currentCharset=$GLOBALS['LANG']->charSet;
-                               $xmlData = $GLOBALS['LANG']->csConvObj->conv($xmlData,$storeInCharset,$currentCharset,1);
-                       }
-                       $editData=t3lib_div::xml2array($xmlData);
-                       if (!is_array($editData))       {       // Must be XML parsing error...
-                               $editData=array();
-                       } elseif (!isset($editData['meta']) || !is_array($editData['meta']))    {
+                       if ($storeInCharset) {
+                               $currentCharset = $GLOBALS['LANG']->charSet;
+                               $xmlData = $GLOBALS['LANG']->csConvObj->conv($xmlData, $storeInCharset, $currentCharset, 1);
+                       }
+                       $editData = t3lib_div::xml2array($xmlData);
+                       if (!is_array($editData)) { // Must be XML parsing error...
+                               $editData = array();
+                       } elseif (!isset($editData['meta']) || !is_array($editData['meta'])) {
                                $editData['meta'] = array();
                        }
 
                                // Find the data structure if sheets are found:
-                       $sheet = $editData['meta']['currentSheetId'] ? $editData['meta']['currentSheetId'] : 'sDEF';    // Sheet to display
+                       $sheet = $editData['meta']['currentSheetId'] ? $editData['meta']['currentSheetId'] : 'sDEF'; // Sheet to display
 
                                // Create sheet menu:
-//                     if (is_array($dataStructArray['sheets']))       {
-//                             #$item.=$this->getSingleField_typeFlex_sheetMenu($dataStructArray['sheets'], $PA['itemFormElName'].'[meta][currentSheetId]', $sheet).'<br />';
-//                     }
+                               //TODO; Why is this commented out?
+                       //                      if (is_array($dataStructArray['sheets']))       {
+                       //                              #$item.=$this->getSingleField_typeFlex_sheetMenu($dataStructArray['sheets'], $PA['itemFormElName'].'[meta][currentSheetId]', $sheet).'<br />';
+                       //                      }
 
                                // Create language menu:
                        $langChildren = $dataStructArray['meta']['langChildren'] ? 1 : 0;
                        $langDisabled = $dataStructArray['meta']['langDisable'] ? 1 : 0;
 
-                       $editData['meta']['currentLangId']=array();
+                       $editData['meta']['currentLangId'] = array();
 
                                // Look up page overlays:
-                       $checkPageLanguageOverlay = $GLOBALS['BE_USER']->getTSConfigVal('options.checkPageLanguageOverlay')?TRUE:FALSE;
-                       if ($checkPageLanguageOverlay)  {
+                       $checkPageLanguageOverlay = $GLOBALS['BE_USER']->getTSConfigVal('options.checkPageLanguageOverlay') ? TRUE : FALSE;
+                       if ($checkPageLanguageOverlay) {
                                $pageOverlays = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
                                        '*',
                                        'pages_language_overlay',
-                                       'pid='.intval($row['pid']).
-                                               t3lib_BEfunc::deleteClause('pages_language_overlay').
-                                               t3lib_BEfunc::versioningPlaceholderClause('pages_language_overlay'),
+                                       'pid=' . intval($row['pid']) .
+                                       t3lib_BEfunc::deleteClause('pages_language_overlay') .
+                                       t3lib_BEfunc::versioningPlaceholderClause('pages_language_overlay'),
                                        '',
                                        '',
                                        '',
@@ -2492,72 +2551,86 @@ class t3lib_TCEforms    {
                        }
                        $languages = $this->getAvailableLanguages();
 
-                       foreach($languages as $lInfo)   {
-                               if ($GLOBALS['BE_USER']->checkLanguageAccess($lInfo['uid']) && (!$checkPageLanguageOverlay || $lInfo['uid']<=0 || is_array($pageOverlays[$lInfo['uid']])))      {
-                                       $editData['meta']['currentLangId'][] =  $lInfo['ISOcode'];
+                       foreach ($languages as $lInfo) {
+                               if ($GLOBALS['BE_USER']->checkLanguageAccess($lInfo['uid']) && (!$checkPageLanguageOverlay || $lInfo['uid'] <= 0 || is_array($pageOverlays[$lInfo['uid']]))) {
+                                       $editData['meta']['currentLangId'][] = $lInfo['ISOcode'];
                                }
                        }
-                       if (!is_array($editData['meta']['currentLangId']) || !count($editData['meta']['currentLangId']))        {
-                               $editData['meta']['currentLangId']=array('DEF');
+                       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 />';
-//                     }
+                               //TODO: Why is this commented out?
+                       //                      if (!$langDisabled && count($languages) > 1)    {
+                       //                              $item.=$this->getSingleField_typeFlex_langMenu($languages, $PA['itemFormElName'].'[meta][currentLangId]', $editData['meta']['currentLangId']).'<br />';
+                       //                      }
 
                        $PA['_noEditDEF'] = FALSE;
-                       if ($langChildren || $langDisabled)     {
+                       if ($langChildren || $langDisabled) {
                                $rotateLang = array('DEF');
                        } else {
-                               if (!in_array('DEF',$editData['meta']['currentLangId']))        {
-                                       array_unshift($editData['meta']['currentLangId'],'DEF');
+                               if (!in_array('DEF', $editData['meta']['currentLangId'])) {
+                                       array_unshift($editData['meta']['currentLangId'], 'DEF');
                                        $PA['_noEditDEF'] = TRUE;
                                }
                                $rotateLang = $editData['meta']['currentLangId'];
                        }
 
                                // Tabs sheets
-                       if (is_array($dataStructArray['sheets']))       {
+                       if (is_array($dataStructArray['sheets'])) {
                                $tabsToTraverse = array_keys($dataStructArray['sheets']);
                        } else {
                                $tabsToTraverse = array($sheet);
                        }
 
-                       foreach ($rotateLang as $lKey)  {
-                               if (!$langChildren && !$langDisabled)   {
-                                       $item.= '<strong>'.$this->getLanguageIcon($table,$row,'v'.$lKey).$lKey.':</strong>';
+                       foreach ($rotateLang as $lKey) {
+                               if (!$langChildren && !$langDisabled) {
+                                       $item .= '<strong>' . $this->getLanguageIcon($table, $row, 'v' . $lKey) . $lKey . ':</strong>';
                                }
 
                                $tabParts = array();
-                               foreach ($tabsToTraverse as $sheet)     {
-                                       list ($dataStruct, $sheet) = t3lib_div::resolveSheetDefInDS($dataStructArray,$sheet);
+                               foreach ($tabsToTraverse as $sheet) {
+                                       list ($dataStruct, $sheet) = t3lib_div::resolveSheetDefInDS($dataStructArray, $sheet);
 
                                                // Render sheet:
-                                       if (is_array($dataStruct['ROOT']) && is_array($dataStruct['ROOT']['el']))               {
-                                               $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!!!)
+                                       if (is_array($dataStruct['ROOT']) && is_array($dataStruct['ROOT']['el'])) {
+                                               $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!!!)
                                                $PA['_lang'] = $lang;
-                                               $PA['_cshFile'] = ((isset($dataStruct['ROOT']['TCEforms']) && isset($dataStruct['ROOT']['TCEforms']['cshFile'])) ? $dataStruct['ROOT']['TCEforms']['cshFile'] : '');
+                                                       // Assemble key for loading the correct CSH file
+                                               $dsPointerFields = t3lib_div::trimExplode(',', $GLOBALS['TCA'][$table]['columns'][$field]['config']['ds_pointerField'], TRUE);
+                                               $PA['_cshKey'] = $table . '.' . $field;
+                                               foreach ($dsPointerFields as $key) {
+                                                       $PA['_cshKey'] .= '.' . $row[$key];
+                                               }
 
+                                                       // Push the sheet level tab to DynNestedStack
+                                               if (is_array($dataStructArray['sheets'])) {
+                                                       $tabIdentString = $GLOBALS['TBE_TEMPLATE']->getDynTabMenuId('TCEFORMS:flexform:' . $PA['itemFormElName'] . $PA['_lang']);
+                                                       $this->pushToDynNestedStack('tab', $tabIdentString . '-' . (count($tabParts) + 1));
+                                               }
                                                        // Render flexform:
                                                $tRows = $this->getSingleField_typeFlex_draw(
-                                                                       $dataStruct['ROOT']['el'],
-                                                                       $editData['data'][$sheet][$lang],
-                                                                       $table,
-                                                                       $field,
-                                                                       $row,
-                                                                       $PA,
-                                                                       '[data]['.$sheet.']['.$lang.']'
-                                                               );
-                                               #$sheetContent= '<table border="0" cellpadding="1" cellspacing="1" class="typo3-TCEforms-flexForm">'.implode('',$tRows).'</table>';
-                                               $sheetContent = '<div class="typo3-TCEforms-flexForm">'.$tRows.'</div>';
+                                                       $dataStruct['ROOT']['el'],
+                                                       $editData['data'][$sheet][$lang],
+                                                       $table,
+                                                       $field,
+                                                       $row,
+                                                       $PA,
+                                                       '[data][' . $sheet . '][' . $lang . ']'
+                                               );
+                                               $sheetContent = '<div class="typo3-TCEforms-flexForm">' . $tRows . '</div>';
 
-                       #                       $item = '<div style=" position:absolute;">'.$item.'</div>';
-                                               //visibility:hidden;
-                                       } else $sheetContent='Data Structure ERROR: No ROOT element found for sheet "'.$sheet.'".';
+
+                                                       // Pop the sheet level tab from DynNestedStack
+                                               if (is_array($dataStructArray['sheets'])) {
+                                                       $this->popFromDynNestedStack('tab', $tabIdentString . '-' . (count($tabParts) + 1));
+                                               }
+                                       } else {
+                                               $sheetContent = 'Data Structure ERROR: No ROOT element found for sheet "' . $sheet . '".';
+                                       }
 
                                                // Add to tab:
                                        $tabParts[] = array(
@@ -2568,14 +2641,16 @@ class t3lib_TCEforms    {
                                        );
                                }
 
-                               if (is_array($dataStructArray['sheets']))       {
+                               if (is_array($dataStructArray['sheets'])) {
                                        $dividersToTabsBehaviour = (isset($GLOBALS['TCA'][$table]['ctrl']['dividers2tabs']) ? $GLOBALS['TCA'][$table]['ctrl']['dividers2tabs'] : 1);
-                                       $item.= $this->getDynTabMenu($tabParts, 'TCEFORMS:flexform:'.$PA['itemFormElName'].$PA['_lang'], $dividersToTabsBehaviour);
+                                       $item .= $this->getDynTabMenu($tabParts, 'TCEFORMS:flexform:' . $PA['itemFormElName'] . $PA['_lang'], $dividersToTabsBehaviour);
                                } else {
-                                       $item.= $sheetContent;
+                                       $item .= $sheetContent;
                                }
                        }
-               } else $item='Data Structure ERROR: '.$dataStructArray;
+               } else {
+                       $item = 'Data Structure ERROR: ' . $dataStructArray;
+               }
 
                return $item;
        }
@@ -2589,13 +2664,13 @@ class t3lib_TCEforms    {
         * @param       [type]          $multi: ...
         * @return      string          HTML for menu
         */
-       function getSingleField_typeFlex_langMenu($languages,$elName,$selectedLanguage,$multi=1)        {
-               $opt=array();
-               foreach($languages as $lArr)    {
-                       $opt[]='<option value="'.htmlspecialchars($lArr['ISOcode']).'"'.(in_array($lArr['ISOcode'],$selectedLanguage)?' selected="selected"':'').'>'.htmlspecialchars($lArr['title']).'</option>';
+       function getSingleField_typeFlex_langMenu($languages, $elName, $selectedLanguage, $multi = 1) {
+               $opt = array();
+               foreach ($languages as $lArr) {
+                       $opt[] = '<option value="' . htmlspecialchars($lArr['ISOcode']) . '"' . (in_array($lArr['ISOcode'], $selectedLanguage) ? ' selected="selected"' : '') . '>' . htmlspecialchars($lArr['title']) . '</option>';
                }
 
-               $output = '<select id="' . uniqid('tceforms-multiselect-') . ' class="tceforms-select tceforms-multiselect tceforms-flexlangmenu" name="'.$elName.'[]"'.($multi ? ' multiple="multiple" size="'.count($languages).'"' : '').'>'.implode('',$opt).'</select>';
+               $output = '<select id="' . uniqid('tceforms-multiselect-') . ' class="tceforms-select tceforms-multiselect tceforms-flexlangmenu" name="' . $elName . '[]"' . ($multi ? ' multiple="multiple" size="' . count($languages) . '"' : '') . '>' . implode('', $opt) . '</select>';
 
                return $output;
        }
@@ -2608,24 +2683,24 @@ class t3lib_TCEforms    {
         * @param       string          Current sheet key
         * @return      string          HTML for menu
         */
-       function getSingleField_typeFlex_sheetMenu($sArr,$elName,$sheetKey)     {
+       function getSingleField_typeFlex_sheetMenu($sArr, $elName, $sheetKey) {
 
-               $tCells =array();
-               $pct = round(100/count($sArr));
-               foreach($sArr as $sKey => $sheetCfg)    {
-                       if ($GLOBALS['BE_USER']->jsConfirmation(1))     {
-                               $onClick = 'if (confirm(TBE_EDITOR.labels.onChangeAlert) && TBE_EDITOR.checkSubmit(-1)){'.$this->elName($elName).".value='".$sKey."'; TBE_EDITOR.submitForm()};";
+               $tCells = array();
+               $pct = round(100 / count($sArr));
+               foreach ($sArr as $sKey => $sheetCfg) {
+                       if ($GLOBALS['BE_USER']->jsConfirmation(1)) {
+                               $onClick = 'if (confirm(TBE_EDITOR.labels.onChangeAlert) && TBE_EDITOR.checkSubmit(-1)){' . $this->elName($elName) . ".value='" . $sKey . "'; TBE_EDITOR.submitForm()};";
                        } else {
-                               $onClick = 'if(TBE_EDITOR.checkSubmit(-1)){ '.$this->elName($elName).".value='".$sKey."'; TBE_EDITOR.submitForm();}";
+                               $onClick = 'if(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>';
+                       $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" class="typo3-TCEforms-flexForm-sheetMenu"><tr>'.implode('',$tCells).'</tr></table>';
+               return '<table border="0" cellpadding="0" cellspacing="2" class="typo3-TCEforms-flexForm-sheetMenu"><tr>' . implode('', $tCells) . '</tr></table>';
        }
 
        /**
@@ -2643,32 +2718,32 @@ class t3lib_TCEforms    {
         * @param       boolean         Defines whether the next flexform level is open or closed. Comes from _TOGGLE pseudo field in FlexForm xml.
         * @return      string          HTMl code for form.
         */
-       function getSingleField_typeFlex_draw($dataStruct,$editData,$table,$field,$row,&$PA,$formPrefix='',$level=0,$idPrefix='ID',$toggleClosed=FALSE) {
+       function getSingleField_typeFlex_draw($dataStruct, $editData, $table, $field, $row, &$PA, $formPrefix = '', $level = 0, $idPrefix = 'ID', $toggleClosed = FALSE) {
 
                $output = '';
                $mayRestructureFlexforms = $GLOBALS['BE_USER']->checkLanguageAccess(0);
 
                        // Data Structure array must be ... and array of course...
-               if (is_array($dataStruct))      {
-                       foreach($dataStruct as $key => $value)  {       // Traversing fields in structure:
-                               if (is_array($value))   {       // The value of each entry must be an array.
+               if (is_array($dataStruct)) {
+                       foreach ($dataStruct as $key => $value) { // Traversing fields in structure:
+                               if (is_array($value)) { // The value of each entry must be an array.
 
                                                // ********************
                                                // Making the row:
                                                // ********************
                                                // Title of field:
-                                       $theTitle = htmlspecialchars(t3lib_div::fixed_lgd_cs($this->sL($value['tx_templavoila']['title']),30));
+                                       $theTitle = htmlspecialchars(t3lib_div::fixed_lgd_cs($this->sL($value['tx_templavoila']['title']), 30));
 
                                                // If it's a "section" or "container":
-                                       if ($value['type']=='array')    {
+                                       if ($value['type'] == 'array') {
 
                                                        // Creating IDs for form fields:
                                                        // It's important that the IDs "cascade" - otherwise we can't dynamically expand the flex form because this relies on simple string substitution of the first parts of the id values.
-                                               $thisId = t3lib_div::shortMd5(uniqid('id',true));       // This is a suffix used for forms on this level
-                                               $idTagPrefix = $idPrefix.'-'.$thisId;   // $idPrefix is the prefix for elements on lower levels in the hierarchy and we combine this with the thisId value to form a new ID on this level.
+                                               $thisId = t3lib_div::shortMd5(uniqid('id', TRUE)); // This is a suffix used for forms on this level
+                                               $idTagPrefix = $idPrefix . '-' . $thisId; // $idPrefix is the prefix for elements on lower levels in the hierarchy and we combine this with the thisId value to form a new ID on this level.
 
                                                        // If it's a "section" containing other elements:
-                                               if ($value['section'])  {
+                                               if ($value['section']) {
 
                                                                // Load script.aculo.us if flexform sections can be moved by drag'n'drop:
                                                        $GLOBALS['SOBE']->doc->getPageRenderer()->loadScriptaculous();
@@ -2677,24 +2752,24 @@ class t3lib_TCEforms    {
 
                                                                // Render elements in data array for section:
                                                        $tRows = array();
-                                                       $cc=0;
-                                                       if (is_array($editData[$key]['el']))    {
-                                                               foreach ($editData[$key]['el'] as $k3 => $v3)   {
-                                                                       $cc=$k3;
-                                                                       if (is_array($v3))      {
+                                                       $cc = 0;
+                                                       if (is_array($editData[$key]['el'])) {
+                                                               foreach ($editData[$key]['el'] as $k3 => $v3) {
+                                                                       $cc = $k3;
+                                                                       if (is_array($v3)) {
                                                                                $theType = key($v3);
                                                                                $theDat = $v3[$theType];
                                                                                $newSectionEl = $value['el'][$theType];
-                                                                               if (is_array($newSectionEl))    {
-                                                                                       $tRows[]= $this->getSingleField_typeFlex_draw(
+                                                                               if (is_array($newSectionEl)) {
+                                                                                       $tRows[] = $this->getSingleField_typeFlex_draw(
                                                                                                array($theType => $newSectionEl),
                                                                                                array($theType => $theDat),
                                                                                                $table,
                                                                                                $field,
                                                                                                $row,
                                                                                                $PA,
-                                                                                               $formPrefix.'['.$key.'][el]['.$cc.']',
-                                                                                               $level+1,
+                                                                                               $formPrefix . '[' . $key . '][el][' . $cc . ']',
+                                                                                               $level + 1,
                                                                                                $idTagPrefix,
                                                                                                $v3['_TOGGLE']
                                                                                        );
@@ -2711,7 +2786,7 @@ class t3lib_TCEforms      {
 
                                                                // Traversing possible types of new content in the section:
                                                        $newElementsLinks = array();
-                                                       foreach($value['el'] as $nnKey => $nCfg)        {
+                                                       foreach ($value['el'] as $nnKey => $nCfg) {
                                                                $additionalJS_post_saved = $this->additionalJS_post;
                                                                $this->additionalJS_post = array();
                                                                $additionalJS_submit_saved = $this->additionalJS_submit;
@@ -2723,8 +2798,8 @@ class t3lib_TCEforms      {
                                                                        $field,
                                                                        $row,
                                                                        $PA,
-                                                                       $formPrefix.'['.$key.'][el]['.$idTagPrefix.'-form]',
-                                                                       $level+1,
+                                                                       $formPrefix . '[' . $key . '][el][' . $idTagPrefix . '-form]',
+                                                                       $level + 1,
                                                                        $idTagPrefix
                                                                );
 
@@ -2732,18 +2807,18 @@ class t3lib_TCEforms    {
                                                                $var = uniqid('idvar');
                                                                $replace = 'replace(/' . $idTagPrefix . '-/g,"' . $idTagPrefix . '-"+' . $var . '+"-")';
                                                                $onClickInsert = 'var ' . $var . ' = "' . 'idx"+(new Date()).getTime();';
-                                                               // Do not replace $isTagPrefix in setActionStatus() because it needs section id!
-                                                               $onClickInsert .= 'new Insertion.Bottom($("'.$idTagPrefix.'"), unescape("'.rawurlencode($newElementTemplate).'").' . $replace . '); setActionStatus("'.$idTagPrefix.'");';
+                                                                       // Do not replace $isTagPrefix in setActionStatus() because it needs section id!
+                                                               $onClickInsert .= 'new Insertion.Bottom($("' . $idTagPrefix . '"), unescape("' . rawurlencode($newElementTemplate) . '").' . $replace . '); setActionStatus("' . $idTagPrefix . '");';
                                                                $onClickInsert .= 'eval(unescape("' . rawurlencode(implode(';', $this->additionalJS_post)) . '").' . $replace . ');';
                                                                $onClickInsert .= 'TBE_EDITOR.addActionChecks("submit", unescape("' . rawurlencode(implode(';', $this->additionalJS_submit)) . '").' . $replace . ');';
                                                                $onClickInsert .= 'return false;';
-                                                               // Kasper's comment (kept for history): Maybe there is a better way to do this than store the HTML for the new element in rawurlencoded format - maybe it even breaks with certain charsets? But for now this works...
+                                                                       // Kasper's comment (kept for history): Maybe there is a better way to do this than store the HTML for the new element in rawurlencoded format - maybe it even breaks with certain charsets? But for now this works...
                                                                $this->additionalJS_post = $additionalJS_post_saved;
                                                                $this->additionalJS_submit = $additionalJS_submit_saved;
                                                                $new = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:cm.new', 1);
-                                                               $newElementsLinks[]= '<a href="#" onclick="'.htmlspecialchars($onClickInsert).'">' .
-                                                                       t3lib_iconWorks::getSpriteIcon('actions-document-new') .
-                                                                       htmlspecialchars(t3lib_div::fixed_lgd_cs($this->sL($nCfg['tx_templavoila']['title']),30)) . '</a>';
+                                                               $newElementsLinks[] = '<a href="#" onclick="' . htmlspecialchars($onClickInsert) . '">' .
+                                                                                                         t3lib_iconWorks::getSpriteIcon('actions-document-new') .
+                                                                                                         htmlspecialchars(t3lib_div::fixed_lgd_cs($this->sL($nCfg['tx_templavoila']['title']), 30)) . '</a>';
                                                        }
 
                                                                // Reverting internal variables we don't want to change:
@@ -2751,82 +2826,88 @@ class t3lib_TCEforms    {
 
                                                                // Adding the sections:
                                                        $toggleAll = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.toggleall', 1);
-                                                       $output.= '
+                                                       $output .= '
                                                        <div class="t3-form-field-toggle-flexsection">
                                                                <a href="#" onclick="' . htmlspecialchars('flexFormToggleSubs("' . $idTagPrefix . '"); return false;') . '">'
-                                                                       . t3lib_iconWorks::getSpriteIcon('actions-move-right', array('title' => $toggleAll)) . $toggleAll . '
+                                                                          . t3lib_iconWorks::getSpriteIcon('actions-move-right', array('title' => $toggleAll)) . $toggleAll . '
                                                                </a>
                                                        </div>
 
                                                        <div id="' . $idTagPrefix . '" class="t3-form-field-container-flexsection">' . implode('', $tRows) . '</div>';
-                                                       $output.= $mayRestructureFlexforms ? '<div class="t3-form-field-add-flexsection"><strong>' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.addnew', 1) . ':</strong> '.implode(' | ',$newElementsLinks).'</div>' : '';
+                                                       $output .= $mayRestructureFlexforms ? '<div class="t3-form-field-add-flexsection"><strong>' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.addnew', 1) . ':</strong> ' . implode(' | ', $newElementsLinks) . '</div>' : '';
                                                } else {
-                                                       // It is a container
+                                                               // It is a container
 
                                                        $toggleIcon_open = t3lib_iconWorks::getSpriteIcon('actions-move-down');
                                                        $toggleIcon_close = t3lib_iconWorks::getSpriteIcon('actions-move-right');
 
                                                                // Create on-click actions.
-                                                       //$onClickCopy = 'new Insertion.After($("'.$idTagPrefix.'"), getOuterHTML("'.$idTagPrefix.'").replace(/'.$idTagPrefix.'-/g,"'.$idTagPrefix.'-copy"+Math.floor(Math.random()*100000+1)+"-")); return false;';    // Copied elements doesn't work (well) in Safari while they do in Firefox and MSIE! UPDATE: It turned out that copying doesn't work for any browser, simply because the data from the copied form never gets submitted to the server for some reason! So I decided to simply disable copying for now. If it's requested by customers we can look to enable it again and fix the issue. There is one un-fixable problem though; Copying an element like this will violate integrity if files are attached inside that element because the file reference doesn't get an absolute path prefixed to it which would be required to have TCEmain generate a new copy of the file.
-                                                       $onClickRemove = 'if (confirm("Are you sure?")){/*###REMOVE###*/;$("'.$idTagPrefix.'").hide();setActionStatus("'.$idPrefix.'");} return false;';
-                                                       $onClickToggle = 'flexFormToggle("'.$idTagPrefix.'"); return false;';
+                                                               //$onClickCopy = 'new Insertion.After($("'.$idTagPrefix.'"), getOuterHTML("'.$idTagPrefix.'").replace(/'.$idTagPrefix.'-/g,"'.$idTagPrefix.'-copy"+Math.floor(Math.random()*100000+1)+"-")); return false;';    // Copied elements doesn't work (well) in Safari while they do in Firefox and MSIE! UPDATE: It turned out that copying doesn't work for any browser, simply because the data from the copied form never gets submitted to the server for some reason! So I decided to simply disable copying for now. If it's requested by customers we can look to enable it again and fix the issue. There is one un-fixable problem though; Copying an element like this will violate integrity if files are attached inside that element because the file reference doesn't get an absolute path prefixed to it which would be required to have TCEmain generate a new copy of the file.
+                                                       $onClickRemove = 'if (confirm("Are you sure?")){/*###REMOVE###*/;$("' . $idTagPrefix . '").hide();setActionStatus("' . $idPrefix . '");} return false;';
+                                                       $onClickToggle = 'flexFormToggle("' . $idTagPrefix . '"); return false;';
 
-                                                       $onMove = 'flexFormSortable("'.$idPrefix.'")';
+                                                       $onMove = 'flexFormSortable("' . $idPrefix . '")';
                                                                // Notice: Creating "new" elements after others seemed to be too difficult to do and since moving new elements created in the bottom is now so easy with drag'n'drop I didn't see the need.
 
 
                                                                // Putting together header of a section. Sections can be removed, copied, opened/closed, moved up and down:
                                                                // I didn't know how to make something right-aligned without a table, so I put it in a table. can be made into <div>'s if someone like to.
                                                                // Notice: The fact that I make a "Sortable.create" right onmousedown is that if we initialize this when rendering the form in PHP new and copied elements will not be possible to move as a sortable. But this way a new sortable is initialized everytime someone tries to move and it will always work.
-                                                       $ctrlHeader= '
+                                                       $ctrlHeader = '
                                                                <table class="t3-form-field-header-flexsection" onmousedown="' . ($mayRestructureFlexforms ? htmlspecialchars($onMove) : '') . '">
                                                                <tr>
                                                                        <td>
-                                                                               <a href="#" onclick="'.htmlspecialchars($onClickToggle).'" id="'.$idTagPrefix.'-toggle">
-                                                                                       '.($toggleClosed?$toggleIcon_close:$toggleIcon_open).'
+                                                                               <a href="#" onclick="' . htmlspecialchars($onClickToggle) . '" id="' . $idTagPrefix . '-toggle">
+                                                                                       ' . ($toggleClosed ? $toggleIcon_close : $toggleIcon_open) . '
                                                                                </a>
-                                                                               <strong>'.$theTitle.'</strong> <em><span id="'.$idTagPrefix.'-preview"></span></em>
+                                                                               <strong>' . $theTitle . '</strong> <em><span id="' . $idTagPrefix . '-preview"></span></em>
                                                                        </td>
-                                                                       <td align="right">'.
-                                                                               ($mayRestructureFlexforms ? t3lib_iconWorks::getSpriteIcon('actions-move-move', array('title' => 'Drag to Move')) : '').
-                                                                               ($mayRestructureFlexforms ? '<a href="#" onclick="'.htmlspecialchars($onClickRemove).'">'.t3lib_iconWorks::getSpriteIcon('actions-edit-delete', array('title' => 'Delete')) : '').
-                                                                       '</td>
+                                                                       <td align="right">' .
+                                                                            &nbs