<div id="custom_fields_configuration">
    [{if isset($g_list)}]
        [{$g_list}]

        <script type="text/javascript">
            var urlParts = document.location.href.parseQuery(),
                $body = $('body'),
                $id;

            if ($body) {
                $id = $body.down('[name="id"]');

                if ($id) {
                    $id.setValue(null);
                }
            }

            delete urlParts['[{$smarty.const.C__GET__ID}]'];

            window.history.replaceState(null, document.title, '?' + Object.toQueryString(urlParts));
        </script>
    [{else}]
    <table class="contentTable">
        <tr>
            <td class="key">[{isys type="f_label" name="category_title" ident="LC__UNIVERSAL__CATEGORY_TITLE"}]</td>
            <td class="value">[{isys type="f_text" id="category_title" name="category_title" p_bNoTranslation=true}]</td>
        </tr>
        <tr>
            <td class="key" style="vertical-align:top;">[{isys type="f_label" name="object_types" ident="LC_UNIVERSAL__OBJECT_TYPES"}]</td>
            <td class="value">[{isys type="f_dialog_list" name="object_types" p_bSort=false}]</td>
        </tr>
        <tr>
            <td class="key" style="vertical-align:top;">[{isys type="f_label" name="object_types" ident="LC__CMDB__CUSTOM_CATEGORIES__LIST_CATEGORY"}]</td>
            <td class="value">[{isys type="f_dialog" name="multivalued"}]</td>
        </tr>
        [{* Constant should not be editable for non existing entries. *}]
        <tr>
            <td class="key" style="vertical-align:top;">[{isys type="f_label" name="object_types" ident="LC__CMDB__CUSTOM_CATEGORIES__CONSTANT"}]</td>
            <td class="value">
                <div class="input-group input-size-normal ml20">
                    <div class="input-group-addon input-group-addon-unstyled"><code>C__CATG__CUSTOM_FIELDS_</code></div>
                    [{isys type="f_text" name="category_constant" disableInputGroup=true p_bInfoIconSpacer=0}]
                </div>
            </td>
        </tr>
    </table>

    <div class="p10">
        <p class="mb10"><img src="[{$dir_images}]icons/silk/information.png" class="vam" /> <span class="vam">[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__DESCRIPTION"}]</span></p>

        <ul id="custom_fields_configuration_list_header" class="border" style="border-bottom: none;">
            <li class="p5">
                <div class="label-a text-bold ml15">[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_TITLE"}]</div>
                <div class="label-b text-bold ml15">[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_TYPE"}]</div>
                <div class="label-c text-bold ml15">[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_ADDITIONAL"}]</div>
                <div class="label-d text-bold ml15 showInList" title="[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__SHOW_IN_LIST"}]"><img src="[{$dir_images}]icons/silk/table.png" /></div>
                <div class="label-e text-bold ml15">[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_ACTION"}]</div>
                <div class="label-f text-bold ml15">[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_HANDLING"}]</div>
                <div class="label-g text-bold ml15">[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_INLINE"}]</div>
                <br class="cb" />
            </li>
        </ul>

        <ul id="custom_fields_configuration_list" class="border" style="border-top: none;"></ul>

        <a href="javascript:window.add_custom_field('', '', '', '', '', 1, false, 0, -1, 'visible', 0);" class="btn mt5" id="add_field_button"><img class="mr5" src="[{$dir_images}]icons/plus-green.gif" /><span>[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__ADD_NEW_FIELD"}]</span></a>

        [{if is_array($category_config) && count($category_config) && $valueCount > 0}]
            <p class="box-yellow p10 mt10"><img src="[{$dir_images}]icons/silk/error.png" class="vam" /> [{isys type="lang" ident="LC__CMDB__CUSTOM_CATEGORIES__CHANGE_NOTE"}]</p>
        [{/if}]

        [{if $entryCount}]
            <p class="mt10"><h3 class="border-bottom">[{isys type="lang" ident="LC__LICENCE_OVERVIEW__STATISTIC"}]</h3></p>
            <p>[{isys type="lang" ident="LC__CMDB__CUSTOM_CATEGORIES__ENTRY_COUNT"}]: <strong>[{$entryCount}]</strong></p>
            <p>[{isys type="lang" ident="LC__CMDB__CUSTOM_CATEGORIES__VALUE_COUNT"}]: <strong>[{$valueCount}]</strong></p>
        [{/if}]

        [{if $apiExample}]
            <p class="mt20">
                <a class="btn mt5 show-api-info">
                    <img class="mr5" src="[{$dir_images}]icons/silk/brick.png" /> <span>[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__SHOW_TECHNICAL_INFO"}]</span>
                </a>

                <div class="api-info" style="display:none;">
                    <div>
                        <div class="fl">
                            <h3 class="mt10">Configuration:</h3>
                            <pre class="box-lightgrey mt10 p10">[{json_encode($apiExampleConfig, JSON_PRETTY_PRINT)}]</pre>
                        </div>

                        <div class="ml10 fl">
                            <h3 class="mt10">Structure Info:</h3>
                            <pre class="box-lightgrey mt10 p10">{
    "Field Key / Identifier": {
        "type": "Field Type",
        "popup": "Popup Type",
        "title": "Title",
        "identifier": "Group ID",
        "show_in_list": 0/1
    }
}</pre>
                        </div>
                    </div>

                <br class="cb"/>

                <h3 class="mt10">API-Examples:</h3>
                <pre class="box-lightgrey mt10 p10">[{json_encode($apiExample.read, JSON_PRETTY_PRINT)}]</pre>
                <pre class="box-lightgrey mt10 p10">[{json_encode($apiExample.create, JSON_PRETTY_PRINT)}]</pre>
                </div>
            </p>
        [{/if}]
    </div>
</div>

<style type="text/css">
    #custom_fields_configuration .label-a {
        width: 290px;
        float: left;
    }

    #custom_fields_configuration .label-b {
        width: 136px;
        float: left;
    }

    #custom_fields_configuration .label-c {
        width: 135px;
        float: left;
    }

    #custom_fields_configuration .label-d {
        width: 16px;
        float: left;
    }

    #custom_fields_configuration .label-e {
        width: 78px;
        float: left;
    }

    #custom_fields_configuration .label-f {
        width: 135px;
        float: left;
    }

    #custom_fields_configuration .label-g {
        float: left;
    }

    #custom_fields_configuration_list,
    #custom_fields_configuration_list_header {
        margin: 0;
        padding: 0;
        list-style: none;
    }

    #custom_fields_configuration_list_header li {
        background: url("[{$dir_images}]gradient.png") repeat-x scroll 0 0 #DDDDDD;
    }

    #custom_fields_configuration_list li {
        position: relative;
        background: #eee;
        border-top: 1px solid #888888;
    }

    #custom_fields_configuration_list li div.handle {
        width: 10px;
        height: 21px;
        background: url('[{$dir_images}]icons/hatch.gif');
        cursor: ns-resize;
        position: absolute;
    }

    #custom_fields_configuration pre {
        font-size: 13px;
        line-height: 16px;
    }
</style>

<script type="text/javascript" language="javascript">
    "use strict";

    var url = document.location.href.parseQuery(),
        id = parseInt('[{$id}]'),
        $id_field = $N('id')[0],
        $categoryTitle = $('category_title'),
        $categoryConstant = $('category_constant');

    var changeCatConstant = true;
    if ($categoryConstant.value) {
        changeCatConstant = false;
    }

    if ($id_field) {
        $id_field.setValue(id || null);
    }

    url['[{$smarty.const.C__GET__ID}]'] = '[{$id}]';
    url['[{$smarty.const.C__GET__SETTINGS_PAGE}]'] = '[{$smarty.const.C__CUSTOM_FIELDS__CONFIG}]';
    url['[{$smarty.const.C__CMDB__GET__EDITMODE}]'] = 1;

    window.pushState({}, '', '?' + Object.toQueryString(url));

    if ($categoryTitle && $categoryConstant) {
        $categoryTitle.on('change', function() {
            if (changeCatConstant) {
                $categoryConstant.setValue($categoryTitle.getValue()).simulate('change');
            }
        });

        $categoryConstant.on('change', function() {
            $categoryConstant.setValue($categoryConstant.getValue().toUpperCase().replace(/(\s|-)+/g, '_').replace(/_{2,}/g, '_').replace(/[^a-z0-9_]/gi, ''));
        });
    }

    var custom_field_container = $('custom_fields_configuration_list'),
        $custom_field_header = $('custom_fields_configuration_list_header'),
        field_options = JSON.parse('[{$propertyTypes|json_encode|escape:"javascript"}]'),
        relationTypes = JSON.parse('[{$relation_types|json_encode|escape:"javascript"}]');

    Position.includeScrollOffsets = true;

    var $relationTypeTemplate = new Element('select', {className: 'ml15 input input-mini hide'});

    for(var relationTypeId in relationTypes) {
        if(!relationTypes.hasOwnProperty(relationTypeId)){
            continue;
        }

        $relationTypeTemplate
            .insert(new Element('option', {value: relationTypes[relationTypeId].id})
                .update(relationTypes[relationTypeId].title));
    }

    var $visibilitySelectorTemplate = new Element('select').writeAttribute('class', 'ml15 input input-mini')
        .insert(new Element('option', {value: 'visible'})
            .update('[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_HANDLING__STANDARD"}]'))
        .insert(new Element('option', {value: 'readonly'})
            .update('[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_HANDLING__API_ONLY"}]'))
        .insert(new Element('option', {value: 'hidden'})
            .update('[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_HANDLING__HIDDEN"}]')).setValue('visible')


    /**
     * Function for en- or disabling the additional input-field.
     */
    window.change_field_type = function (ev) {
        var $typeSelect      = ev.findElement('select'),
            $identifierField = $typeSelect.next('[name^="field_dialog_identifier"]').removeClassName('hide').enable(),
            $defaultField    = $typeSelect.next('[name^="field_dialog_default"]').removeClassName('hide').enable(),
            $relationField   = $typeSelect.next('[name^="field_relation"]').removeClassName('hide').enable(),
            $visibilityField = $typeSelect.next('[name^="field_visibility"]'),
            typeValue        = $typeSelect.getValue().split(',');

        if (['f_text', 'f_popup', 'f_password', 'f_link', 'f_time', 'f_textarea'].indexOf(typeValue[0]) === -1) {
            $visibilityField.setValue('visible').writeAttribute('readonly', 'readonly').writeAttribute('disabled', 'disabled');
        } else {
            $visibilityField
                .writeAttribute('readonly', null)
                .writeAttribute('disabled', null);
        }

        if (typeValue[0] === 'f_popup') {
            if (typeValue[1] === 'dialog_plus' || typeValue[1] === 'checkboxes') {
                $identifierField
                    .writeAttribute('readonly', null)
                    .writeAttribute('placeholder', '[{isys type="lang" p_bHtmlEncode=false ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_IDENTIFIER"}]');
                $defaultField
                    .disable()
                    .addClassName('hide');
                $relationField
                    .disable()
                    .addClassName('hide');
                return;
            } else if (typeValue[1] === 'browser_object') {
                if ((typeValue.length === 3 || typeValue.length === 4) && parseInt(typeValue[2]) === 1) {
                    $identifierField
                        .addClassName('hide')
                        .writeAttribute('readonly', 'readonly')
                        .writeAttribute('placeholder', null);
                    $defaultField
                        .disable()
                        .addClassName('hide');
                    return;
                }
            } else if (typeValue[1] === 'report_browser') {
                $identifierField
                    .writeAttribute('readonly', null)
                    .writeAttribute('placeholder', '[{isys type="lang" p_bHtmlEncode=false ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_IDENTIFIER"}]');
                $defaultField
                    .disable()
                    .addClassName('hide');
                $relationField
                    .disable()
                    .addClassName('hide');
                return;
            }

            var tempValue = $defaultField.getValue();

            if (typeValue[1] === 'date-datetime') {
                buildPropertyTypeExtra($defaultField, 'calendar');
                $defaultField.setValue(tempValue);

                $identifierField
                    .disable()
                    .addClassName('hide');
                $defaultField
                    .writeAttribute('readonly', null);
                $relationField
                    .disable()
                    .addClassName('hide');

                return;
            } else {
                buildPropertyTypeExtra($defaultField, '');
                $defaultField.setValue(tempValue);
            }
        } else if (typeValue[0] === 'f_dialog' && typeValue[1] === 'yes-no') {
            $identifierField
                .disable()
                .addClassName('hide');
            $defaultField
                .writeAttribute('readonly', null);
            $relationField
                .disable()
                .addClassName('hide');
            return;
        }

        $identifierField
            .disable()
            .writeAttribute('readonly', 'readonly')
            .writeAttribute('placeholder', null);

        $defaultField
            .disable()
            .addClassName('hide');

        $relationField
            .disable()
            .addClassName('hide');
    };

    /**
     * Function for adding a new field to the custom category.
     *
     * @param  p_key
     * @param  p_title
     * @param  p_type
     * @param  p_popup
     * @param  p_identifier
     * @param  p_show_in_list
     * @param  disable
     * @param  p_multiselection
     */
    window.add_custom_field = function (p_key, p_title, p_type, p_popup, p_identifier, p_show_in_list, disable, p_multiselection, defaultValue, visibility, displayInline) {
        if (typeof p_title === 'undefined') p_title = '';

        // The "custom" prefix is necessary because the integers alone can cause problems when serializing on 32/64 bit machines.
        var i = (p_key) ? p_key : (new Date()).getTime() + Math.floor((10 - 3) * Math.random()) + 5,
            i2,
            custom_title,
            option,
            custom_select,
            custom_show_in_list,
            custom_optional,
            $extraField,
            custom_optional_relation_ele;

        if (p_type.blank()) {
            p_type = 'f_text';
        }

        custom_show_in_list = new Element('label')
            .writeAttribute('id', 'field_show_in_list_' + i)
            .writeAttribute('class', 'ml15 showInList');

        custom_select = new Element('select')
            .writeAttribute('name', 'field_type[' + i + ']')
            .writeAttribute('id', i)
            .writeAttribute('class', 'input input-mini fieldType');

        custom_optional = new Element('input')
            .writeAttribute('type', 'text')
            .writeAttribute('id', 'identifier_' + i)
            .writeAttribute('name', 'field_dialog_identifier[' + i + ']')
            .writeAttribute('value', p_identifier)
            .writeAttribute('class', 'input input-mini ml15')
            .writeAttribute('disabled', 'disabled')
            .writeAttribute('readonly', 'readonly');

        // @see ID-5886 Currently used for "yes-no" fields. Could be expanded to do more!
        $extraField = new Element('select')
            .writeAttribute('id', 'default_' + i)
            .writeAttribute('name', 'field_dialog_default[' + i + ']')
            .writeAttribute('class', 'input input-mini ml15 hide')
            .writeAttribute('disabled', 'disabled')
            .writeAttribute('readonly', 'readonly');

        buildPropertyTypeExtra($extraField, p_popup);

        $extraField.setValue(defaultValue);

        if (p_type === 'html') {
            custom_title = new Element('textarea')
                .writeAttribute('cols', 10)
                .writeAttribute('rows', 10)
                .writeAttribute('name', 'field_title[' + i + ']')
                .writeAttribute('placeholder', 'HTML Content..')
                .writeAttribute('id', 'input_' + i)
                .writeAttribute('class', 'input input-small ml15 mr15')
                .update(p_title);
        } else if (p_type === 'script') {
            custom_title = new Element('textarea')
                .writeAttribute('cols', 10)
                .writeAttribute('rows', 10)
                .writeAttribute('name', 'field_title[' + i + ']')
                .writeAttribute('placeholder', 'Javascript..')
                .writeAttribute('id', 'input_' + i)
                .writeAttribute('class', 'input input-small ml15 mr15')
                .update(p_title);
        } else {
            custom_title = new Element('input')
                .writeAttribute('type', 'text')
                .writeAttribute('name', 'field_title[' + i + ']')
                .writeAttribute('id', 'input_' + i)
                .writeAttribute('value', p_title)
                .writeAttribute('class', 'input input-small ml15 mr15');
        }

        custom_optional_relation_ele = $relationTypeTemplate.clone(true)
            .writeAttribute('name', 'field_relation[' + i + ']')
            .writeAttribute('id', 'field_relation_id_' + i);

        var propertyTypes = field_options.clone();

        if ($F('multivalued') == 0) {
            // We configure a SINGLE VALUE category.
            custom_show_in_list.hide();
            propertyTypes = propertyTypes.filter(function(property) {
                return property.availableSingleValue
            });
        } else {
            // We configure a MULTI VALUE category.
            propertyTypes = propertyTypes.filter(function(property) {
                return property.availableMultiValue
            });
        }

        // Sort the field types.
        propertyTypes.sort(function(a, b) {
            return a.title.localeCompare(b.title);
        });

        for (i2 in propertyTypes) {
            if (propertyTypes.hasOwnProperty(i2)) {
                option = new Element('option', {value: propertyTypes[i2].configValue}).update(propertyTypes[i2].title);

                if (p_type === propertyTypes[i2].value && (propertyTypes[i2].popup == undefined || propertyTypes[i2].popup == p_popup)) {
                    if (p_popup === 'browser_object') {
                        if (p_identifier != '' && propertyTypes[i2].relation == 1) {
                            if (p_multiselection > 0) {
                                if (typeof propertyTypes[i2].multiselection !== 'undefined') {
                                    option.writeAttribute('selected', 'selected'); // does not work in all other browsers except for FF
                                }
                            } else {
                                if (typeof propertyTypes[i2].multiselection === 'undefined') {
                                    option.writeAttribute('selected', 'selected'); // does not work in all other browsers except for FF
                                }
                            }

                            for (var l = 0; custom_optional_relation_ele.options.length; l++) {
                                if (typeof custom_optional_relation_ele.options[l] === 'undefined') {
                                    custom_optional.value = null;
                                    break;
                                } else if (custom_optional_relation_ele.options[l].value == p_identifier) {
                                    custom_optional_relation_ele.options[l].selected = "selected";
                                    break;
                                }
                            }
                        } else if (p_identifier !== '' && propertyTypes[i2].relation === 0) {
                            /* do nothing */
                        } else if (p_identifier === '' && propertyTypes[i2].relation === 0) {
                            if (p_multiselection > 0) {
                                if (typeof propertyTypes[i2].multiselection !== 'undefined') {
                                    option.writeAttribute('selected', 'selected'); // does not work in all other browsers except for FF
                                }
                            } else {
                                if (typeof propertyTypes[i2].multiselection === 'undefined') {
                                    option.writeAttribute('selected', 'selected'); // does not work in all other browsers except for FF
                                }
                            }

                            p_identifier = '';
                        }
                    } else {
                        if (p_multiselection > 0) {
                            if (typeof propertyTypes[i2].multiselection !== 'undefined') {
                                option.writeAttribute('selected', 'selected');
                            }
                        } else if (typeof propertyTypes[i2].multiselection === 'undefined') {
                            option.writeAttribute('selected', 'selected');
                        }
                    }
                }

                custom_select.insert(option);
            }
        }

        var show_in_list_attributes = {type:'checkbox', value:'1', name:'field_show_in_list[' + i + ']'};

        if (p_show_in_list && p_show_in_list == 1) {
            show_in_list_attributes.checked = 'checked';
        }

        custom_show_in_list.insert(new Element('input', show_in_list_attributes));

        custom_select.setValue(p_type);     // does not work in FF but in all other Browsers
        custom_select.on('change', window.change_field_type);

        var visibilitySelector = $visibilitySelectorTemplate.clone(true)
            .writeAttribute('name', 'field_visibility[' + i + ']')
            .writeAttribute('id', 'field_visibility_id_' + i).setValue(visibility ? visibility : 'visible');

        var $inlineCheckbox = new Element('label', {
            id: 'show_inline_' + i,
            className: 'ml15 showInline',
        })
            .update(new Element('input', {
                name: 'field_show_inline[' + i + ']',
                type: 'checkbox',
                value: 1,
                checked: displayInline == 1 ? true : false
            }));

        var $row = new Element('li', {id: 'custom_' + i, className:'p5 border-top'})
            .insert(new Element('div', {className:'handle'}))
            .insert(custom_title)
            .insert(custom_select)
            .insert(custom_optional)
            .insert($extraField)
            .insert(custom_optional_relation_ele)
            .insert(custom_show_in_list)
            .insert(new Element('button')
                .writeAttribute('class', 'btn remove ml15 text-red')
                .writeAttribute('type', 'button')
                .update(new Element('img')
                    .writeAttribute('class', 'mr5')
                    .writeAttribute('src', '[{$dir_images}]icons/silk/cross.png'))
                .insert(new Element('span').update('[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__FIELD_REMOVE"}]'))
            )
            .insert(visibilitySelector)
            .insert($inlineCheckbox);

        custom_field_container.insert($row);

        custom_select.simulate('change');

        if (disable && disable === true)
        {
            custom_select
                .addClassName('disabled')
                .writeAttribute('title', '[{isys type="lang" ident="LC__CMDB__CUSTOM_CATEGORIES__CHANGE_FIELD_TYPE_MESSAGE" p_bHtmlEncode=false}]')
                .select('option')
                .invoke('writeAttribute', 'disabled', 'disabled');
        }

        window.set_observer();
        resetInlineCheckboxes();

        $('custom_fields_configuration_list').fire('configurationList:updated');

        // Add focus to the last field.
        try {
            custom_field_container.down('input[name^="field_title"]:last').focus();
        } catch (e) {
            // Do nothing...
        }
    };

    function resetInlineCheckboxes() {
        var predecessorAllowsInline = false;

        custom_field_container.select('li').forEach(function($li) {
            var fieldType = $li.down('.fieldType').getValue(),
                propertyConfig = field_options.find(function(prop) { return prop.configValue === fieldType });

            if (propertyConfig.allowInline && predecessorAllowsInline) {
                $li.down('.showInline input').enable();
            } else {
                $li.down('.showInline input').setValue(0).disable();
            }

            predecessorAllowsInline = propertyConfig.allowInline;
        });
    }

    /**
     * Function for (re-)setting the necessary observers.
     */
    window.set_observer = function () {
        Sortable.destroy(custom_field_container);

        Sortable.create(custom_field_container, {
            tag:'li',
            handle:'handle',
            dragOnEnd: function () {
                resetInlineCheckboxes();
            }
        });
    };

    [{foreach $category_config as $key => $config}]
    window.add_custom_field(
        '[{$key}]',
        '[{$config.title}]',
        '[{$config.type|default:'f_text'}]',
        '[{$config.popup|default:''}]',
        '[{$config.identifier|default:''}]',
        '[{$config.show_in_list|default:1}]',
        true,
        '[{$config.multiselection|default:0}]',
        '[{$config.default|default:-1}]',
        '[{$config.visibility|default:'visible'}]',
        '[{$config.show_inline|default:0}]'
    );
    [{/foreach}]

    (function (){
        'use strict';

        var $multivalue = $('multivalued'),
            $custom_fields_list = $('custom_fields_configuration_list');

        $custom_fields_list.select('select').invoke('simulate', 'change');

        $custom_fields_list.on('change', '.fieldType', function(ev, $el) {
            var textarea = false,
                input = false;

            if (['script', 'html', 'hr'].indexOf($el.getValue()) >= 0) {
                $el.next('label.showInList').down('input')
                    .writeAttribute('disabled', 'disabled')
                    .removeAttribute('checked');
            } else {
                $el.next('label.showInList').down('input')
                    .removeAttribute('disabled');
            }

            // Switching textareas and input fields for HTML and SCRIPT elements.
            if (['html', 'script'].indexOf($el.getValue()) >= 0) {
                input = $el.previous('input');

                if (input) {
                    textarea = new Element('textarea', {
                        rows:'10',
                        name:input.getAttribute('name'),
                        id:input.getAttribute('id'),
                        className:'input input-small ml15 mr15'
                    }).update(input.value);

                    input.insert({after:textarea}).remove();
                } else {
                    textarea = $el.previous('textarea');
                }

                textarea.setAttribute('placeholder', $el.down('option:selected').innerHTML + '..');
            } else {
                textarea = $el.previous('textarea');

                if (textarea)
                {
                    textarea
                        .insert({
                            after: new Element('input', {
                                type:      'text',
                                name:      textarea.getAttribute('name'),
                                id:        textarea.getAttribute('id'),
                                value:     textarea.innerHTML.unescapeHTML(),
                                className: 'input input-small ml15 mr15'
                            })
                        })
                        .remove();
                }
            }

            resetInlineCheckboxes();
        });

        // Handle multivalue changes
        $multivalue.on('change', function() {
            var isSingleValue = $multivalue.getValue() == 0;

            $custom_field_header.down('.showInList')[isSingleValue ? 'hide' : 'show']();
            $custom_fields_list.select('.showInList').invoke(isSingleValue ? 'hide' : 'show');
        });

        $custom_fields_list.on('click', 'button.remove', function (ev, $el) {
            $el.up('li').remove();

            $custom_fields_list.fire('configurationList:updated');
        });

        $custom_fields_list.on('configurationList:updated', function () {
            if ($custom_fields_list.select('li').length > 0) {
                isys_glob_enable_save();
            } else {
                isys_glob_disable_save();
            }
        });

        $multivalue.simulate('change');

        $custom_fields_list.fire('configurationList:updated');

        $$('a.show-api-info').invoke('on', 'click', function() {
            $$('div.api-info').invoke('toggle');
        });
    })();

    function buildPropertyTypeExtra($select, type) {
        if (type === 'calendar') {
            $select
                .update(new Element('option', {value:  '1'})
                    .update('[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__CALENDAR_WITH_TIME"}]'))
                .insert(new Element('option', {value: '-1'})
                    .update('[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__CALENDAR_WITHOUT_TIME"}]'));
        } else {
            $select
                .update(new Element('option', {value: '-1'})
                    .update('[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__DEFAULT_NONE"}]'))
                .insert(new Element('option', {value: '1'})
                    .update('[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__DEFAULT_YES"}]'))
                .insert(new Element('option', {value: '0'})
                    .update('[{isys type="lang" ident="LC__SYSTEM__CUSTOM_CATEGORIES__DEFAULT_NO"}]'));
        }
    }
</script>
[{/if}]
