<div class="hide">
	[{isys type="f_dialog" name="cmdb-validation-rules-template"}]
</div>

<div id="cmdb-validation" class="m10">
	<div class="border fl mr10 mb5" style="width:300px;">
		<div class="toggle-header p5">
			<button type="button" class="btn btn-secondary window-toggle mr5" title="[{isys type="lang" ident="LC__UNIVERSAL__TOGGLE_VIEW"}]" data-tooltip="1">
                <img src="[{$dir_images}]axialis/user-interface/angle-right-small.svg" alt="" />
            </button>
            <h2>[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__ADD_CATEGORY_VALIDATION"}]</h2>
		</div>
		<div class="p20 hide border-top">
			[{isys type="f_dialog" name="cmdb-validation-category-selector" chosen=true p_bInfoIconSpacer=0 disableInputGroup=true}]

			<button type="button" id="cmdb-validation-category-adder" class="mt5 btn btn-block">
				<img src="[{$dir_images}]axialis/basic/symbol-add.svg" /><span>[{isys type="lang" ident="LC__UNIVERSAL__BUTTON_ADD"}]</span>
			</button>
		</div>
	</div>

	<div class="border fl mr10 mb5" style="width:300px;">
		<div class="toggle-header p5">
            <button type="button" class="btn btn-secondary window-toggle mr5" title="[{isys type="lang" ident="LC__UNIVERSAL__TOGGLE_VIEW"}]" data-tooltip="1">
                <img src="[{$dir_images}]axialis/user-interface/angle-right-small.svg" alt="" />
            </button>
            <h2>[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__CACHE_REFRESH"}]</h2>
		</div>

		<div class="p20 hide border-top">
			<p>[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__CACHE_REFRESH_DESCRIPTION"}]</p>
			<button type="button" id="cmdb-validation-cache-button" class="mt10 btn btn-block">
				<img src="[{$dir_images}]axialis/basic/symbol-update.svg" /><span>[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__CACHE_BUTTON"}]</span>
			</button>
			<p class="p5 mt5" style="display:none;"></p>
		</div>
	</div>

	<div class="border fl" style="width:300px;">
		<div class="toggle-header p5">
            <button type="button" class="btn btn-secondary window-toggle mr5" title="[{isys type="lang" ident="LC__UNIVERSAL__TOGGLE_VIEW"}]" data-tooltip="1">
                <img src="[{$dir_images}]axialis/user-interface/angle-right-small.svg" alt="" />
            </button>
            <h2>[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__REGEX"}]</h2>
		</div>

		<div class="p20 hide border-top">
			<p>[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__REGEX_DESCRIPTION" p_bHtmlEncode=false}]</p>

			[{isys type="f_text" name="cmdb-validation-regex-pattern" p_strClass="input input-block mt10 mb5" p_strValue="^(.*)\$" p_strPlaceholder="LC__SETTINGS__CMDB__VALIDATION__REGEX_PATTERN" p_bInfoIconSpacer=0 disableInputGroup=true}]
			[{isys type="f_text" name="cmdb-validation-regex-search" p_strClass="input input-block mb5" p_strPlaceholder="LC__SETTINGS__CMDB__VALIDATION__REGEX_SEARCH" p_bInfoIconSpacer=0 disableInputGroup=true}]

			<p id="cmdb-validation-regex-result" class="p5 box-neutral-400">[{isys type="lang" ident="LC__UNIVERSAL__WAITING"}]</p>

			<button type="button" id="cmdb-validation-regex-button" class="mt5 btn btn-block">
				<img src="[{$dir_images}]axialis/basic/symbol-ok.svg" /><span>[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__REGEX_CHECK"}]</span>
			</button>
		</div>
	</div>

	<br class="cb" />

	<p class="mt5 p5 box-blue display-flex align-items-center"><img src="[{$dir_images}]axialis/basic/button-info.svg" class="mr5" /><span>[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__REGEX_INFORMATION"}]</span></p>

	<div id="cmdb-validation-list"></div>
</div>

<style type="text/css">

	#cmdb-validation div.chosen-container {
		width:100%;
	}

	#cmdb-validation .toggle-header {
        padding:5px;
        display: flex;
        align-items: center;
    }

	#cmdb-validation div.property-label {
		width: 250px;
		height: 50px;
		display: block;
		float: left;
		position: relative;
	}

	#cmdb-validation div.property-label img {
		position: absolute;
		right: 10px;
		top: -1px;
	}

	#cmdb-validation-regex-pattern,
	#cmdb-validation-regex-search {
		box-sizing: border-box;
	}

	#cmdb-validation input.regex-field,
	#cmdb-validation-regex-pattern {
		font-family: Courier New,Lucida Console,Monospace,Monaco,sans-serif,serif;;
	}
</style>

<script type="text/javascript">
	(function () {
		"use strict";

		var $category_select = $('cmdb-validation-category-selector'),
			$category_add = $('cmdb-validation-category-adder'),
			$configuration_list = $('cmdb-validation-list'),
			$cache_button = $('cmdb-validation-cache-button'),
			$rule_template = $('cmdb-validation-rules-template'),
			$save_button = $('navbar_item_C__NAVMODE__SAVE').writeAttribute('onclick', false),
			category_configuration = {},
			ajax_counter = 0;

		var display_rules = function (category) {
			var $category = $(category),
				$content = $category.down('.attribute-container').update(),
				cat_data = category_configuration[category],
				unique_obj_disabled = ! cat_data.multivalue,
				property,
				locked,
				$rule_dialog;

			for (property in cat_data.properties) {
				if (cat_data.properties.hasOwnProperty(property)) {
					// We don't want to display "HTML" or "HR" properties of custom categories:
					if (category.substr(0, 1) === 'c' && (property.substr(0, 5) === 'hr_c_' || property.substr(0, 7) === 'html_c_')) {
						continue;
					}

					locked = cat_data.locked_properties.in_array(property);
					$rule_dialog = $rule_template.clone(true)
						.writeAttribute('disabled', locked)
						.writeAttribute('id', category + '-' + property + '-rule');

					$content
						.insert(new Element('div', {'data-property':property, style:'min-height:50px;'})
							.insert(new Element('div', {className:'property-label'})
								.update(new Element('strong').update(cat_data.properties[property]))
								.insert(new Element('img', {src:'[{$dir_images}]icons/silk/information.png', title:'[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__LOCKED_PROPERTY" p_bHtmlEncode=false}]', className:'vam mouse-help ' + (locked ? '' : 'hide')})))
							.insert(new Element('div', {className:'fl'})
								.insert(new Element('button', {type:'button', className:'btn btn-small mandatory'})
                                    .update(new Element('img', { src: window.dir_images + 'axialis/user-interface/button-toggle-off.svg' }))
                                    .insert(new Element('span').update('[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__BUTTON__MANDATORY"}]')))
								.insert(new Element('button', {type:'button', className:'btn btn-small unique-object ml5'})
                                    .update(new Element('img', { src: window.dir_images + 'axialis/user-interface/button-toggle-off.svg' }))
                                    .insert(new Element('span').update('[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__BUTTON__UNIQUE_OBJ"}]')))
								.insert(new Element('button', {type:'button', className:'btn btn-small unique-object-type ml5'})
                                    .update(new Element('img', { src: window.dir_images + 'axialis/user-interface/button-toggle-off.svg' }))
                                    .insert(new Element('span').update('[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__BUTTON__UNIQUE_OBJTYPE"}]')))
								.insert(new Element('button', {type:'button', className:'btn btn-small unique-global ml5'})
                                    .update(new Element('img', { src: window.dir_images + 'axialis/user-interface/button-toggle-off.svg' }))
                                    .insert(new Element('span').update('[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__BUTTON__UNIQUE_GLOBAL"}]')))
								.insert(new Element('br'))
								.insert(new Element('label', {className:'display-block' + (locked?' opacity-30':'')}).update('[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__ATTRIBUTE_NEEDS_TO"}]').insert($rule_dialog))
								.insert(new Element('label', {className:'display-block mt10' + (locked?' opacity-30':'')}).update('[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__REGEX_LABEL"}]').insert(new Element('input', {id:category + '-' + property + '-parameter', className:'input input-small regex-field ml5', type:'text', disabled:locked}).setValue('(.*)')).hide())
								.insert(new Element('br'))
								.insert(new Element('div', {className:'textarea-selection'})
									.update(new Element('label', {className:'display-block'})
										.update(new Element('input', {type:'checkbox', className:'checkbox mr5', name:category + '-' + property + '-as-select'}))
										.insert('[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__TEXTAREA_AS_DROPDOWN"}]'))
									.insert(new Element('textarea', {id:category + '-' + property + '-values', className:'input value-field mb5', style:'height:100px; resize:vertical;', disabled:locked})).hide()))
							.insert(new Element('br', {className:'cb'})))
						.insert(new Element('hr', {className:'cb', style:'margin:10px 0;'}));
				}
			}

			// Go ahead and hide all "unique per object" buttons, because they're all disabled and only confuse the user. @see  ID-1237
			if (unique_obj_disabled) {
				$content.select('button.unique-object').invoke('hide');
			}

			process_preselection(category);

			if (ajax_counter <= 0) {
				$category.down('.btn-secondary').simulate('click');
				$content.show();
			}

			$content.down('hr:last-child').remove();
		};

		var update_property_rules = function (category, property) {
			var $property_div = $(category).down('div[data-property="' + property + '"]'),
				$buttons = $property_div.select('button.pressed'),
				rule = $property_div.down('.rule-selector').getValue(),
				regex = $property_div.down('.regex-field').getValue(),
				i;

			if (! category_configuration[category].rules.hasOwnProperty('config')) {
				category_configuration[category].rules.config = {};
			}

			if (Object.isArray(category_configuration[category].rules.config)) {
				category_configuration[category].rules.config = {};
			}

			if (! category_configuration[category].rules.config.hasOwnProperty(property)) {
				category_configuration[category].rules.config[property] = {check:null};
			}

			category_configuration[category].rules.config[property].check = {mandatory:false, unique_obj:false, unique_objtype:false, unique_global:false, validation:[]};

			for (i in $buttons) {
				if ($buttons.hasOwnProperty(i)) {
					if ($buttons[i].hasClassName('mandatory')) {
						category_configuration[category].rules.config[property].check.mandatory = true;
					} else if ($buttons[i].hasClassName('unique-object')) {
						category_configuration[category].rules.config[property].check.unique_obj = true;
					} else if ($buttons[i].hasClassName('unique-object-type')) {
						category_configuration[category].rules.config[property].check.unique_objtype = true;
					} else if ($buttons[i].hasClassName('unique-global')) {
						category_configuration[category].rules.config[property].check.unique_global = true;
					}
				}
			}

			if (rule != '-1') {
				category_configuration[category].rules.config[property].check.validation[0] = rule;
				category_configuration[category].rules.config[property].check.validation[1] = [];

				if (rule === 'FILTER_VALIDATE_REGEXP') {
					category_configuration[category].rules.config[property].check.validation[1] = {options: {regexp: regex}};
				} else if (rule === 'VALIDATE_BY_TEXTFIELD') {
					category_configuration[category].rules.config[property].check.validation[1] = {
						value: $property_div.down('textarea').getValue(),
						'as-select': $property_div.down('input.checkbox').checked
					};
				}
			}
		};

		var process_preselection = function (category) {
			var $category = $(category),
				$properties = $category.select('div[data-property]'),
				cat_data = category_configuration[category],
				checks,
				i,
				property;

			for (i in $properties) {
				if ($properties.hasOwnProperty(i)) {
					property = $properties[i].readAttribute('data-property');

					if (cat_data.rules.config.hasOwnProperty(property)) {
						if (cat_data.rules.config[property].hasOwnProperty('check')) {
							checks = cat_data.rules.config[property].check;

							if (checks.hasOwnProperty('mandatory') && checks.mandatory) {
								$properties[i].down('button.mandatory').addClassName('pressed')
                                    .down('img').writeAttribute('src', window.dir_images + 'axialis/user-interface/button-toggle-on.svg');
							}

							if (checks.hasOwnProperty('unique_obj') && checks.unique_obj) {
								$properties[i].down('button.unique-object').addClassName('pressed')
                                    .down('img').writeAttribute('src', window.dir_images + 'axialis/user-interface/button-toggle-on.svg');
							}

							if (checks.hasOwnProperty('unique_objtype') && checks.unique_objtype) {
								$properties[i].down('button.unique-object-type').addClassName('pressed')
                                    .down('img').writeAttribute('src', window.dir_images + 'axialis/user-interface/button-toggle-on.svg');
							}

							if (checks.hasOwnProperty('unique_global') && checks.unique_global) {
								$properties[i].down('button.unique-global').addClassName('pressed')
                                    .down('img').writeAttribute('src', window.dir_images + 'axialis/user-interface/button-toggle-on.svg');
							}

							if (checks.hasOwnProperty('validation') && Object.isArray(checks.validation) && checks.validation.length == 2) {
								$(category + '-' + property + '-rule').setValue(checks.validation[0]);

								if (checks.validation[0] == 'FILTER_VALIDATE_REGEXP') {
									$(category + '-' + property + '-parameter').setValue(checks.validation[1].options.regexp).up('label').show();
								} else if (checks.validation[0] == 'VALIDATE_BY_TEXTFIELD') {
									$(category + '-' + property + '-values').setValue(checks.validation[1]['value']).up('.textarea-selection').show();

									if (checks.validation[1]['as-select']) {
										$(category + '-' + property + '-values').previous('label.display-block').down('input').setValue('1');
									}
								}
							}
						}
					}
				}
			}
		};

		// Set the global observers.
		$category_add.on('click', function () {
			var value = $category_select.getValue(),
				title = $category_select.down('option:selected').innerHTML,
				cat_type = value.substr(0, 1),
				cat_id = value.substr(2),
                key = cat_type + '-' + cat_id;

			switch (cat_type) {
				case 'g': cat_type = '[{$smarty.const.C__CMDB__CATEGORY__TYPE_GLOBAL}]'; break;
				case 's': cat_type = '[{$smarty.const.C__CMDB__CATEGORY__TYPE_SPECIFIC}]'; break;
				case 'c': cat_type = '[{$smarty.const.C__CMDB__CATEGORY__TYPE_CUSTOM}]'; break;
			}

			if ($configuration_list.down('div#' + key)) {
				$configuration_list.down('div#' + key).highlight();
				idoit.Notify.info('[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__CATEGORY_HAS_ALREADY_BEEN_SELECTED"}]', {life:5});
			} else {
				// Load the properties (and possible configuration) via Ajax.
				new Ajax.Request('?call=validate_field&ajax=1&func=get_validation_by_category', {
					method:'post',
					parameters: {
						cat_type:cat_type,
						cat_id:cat_id
					},
					onSuccess:function (transport) {
						ajax_counter --;
						var json = transport.responseJSON;

						if (! is_json_response(transport, true)) {
							return;
						}

						category_configuration[key] = json.data;

						$configuration_list
							.insert(new Element('div', { id: key, className: 'border mt10 category-container' })
								.update(new Element('div', { className: 'toggle-header bg-neutral-200' })
                                    .update(new Element('button', { type: 'button', className: 'btn btn-secondary mr5', title: '[{isys type="lang" ident="LC__UNIVERSAL__TOGGLE_VIEW"}]', 'data-tooltip': 1 })
                                        .update(new Element('img', { src: window.dir_images + 'axialis/user-interface/angle-right-small.svg', alt: '' })))
                                    .insert(new Element('h2').insert(title))
                                    .insert(new Element('button', { type: 'button', className: 'btn btn-small close ml-auto', title: '[{isys type="lang" ident="LC_UNIVERSAL__DELETE"}]', 'data-tooltip': 1})
                                        .update(new Element('img', { src: '[{$dir_images}]axialis/industry-manufacturing/waste-bin.svg', alt: '' }))))
								.insert(new Element('div', { className: 'attribute-container border-top hide p5' })
									.update(new Element('img', { src: '[{$dir_images}]ajax-loading.gif', className: 'vam mr5' }))
									.insert(new Element('span', { className: 'vam' }).update('[{isys type="lang" ident="LC__UNIVERSAL__LOADING"}]'))));

						display_rules(key);

                        delay(function () {
                            $('body').fire('update:tooltips');
                        }, 250);
					}
				});
			}
		});

		// Remove a category configuration.
		$configuration_list.on('click', 'button.close', function (ev) {
			var category = ev.findElement('button').up('.category-container').remove().id;

			delete category_configuration[category];

            $('body').fire('update:tooltips')
		});

		// Toggle the unique and mandatory buttons.
		$configuration_list.on('click', '.attribute-container button', function (ev) {
			var $button = ev.findElement('button'),
                $property_div = $button.toggleClassName('pressed').up('div[data-property]'),
				category = $property_div.up('.category-container').readAttribute('id'),
				property = $property_div.readAttribute('data-property');

            $button.down('img').writeAttribute('src', window.dir_images + 'axialis/user-interface/button-toggle-' + ($button.hasClassName('pressed') ? 'on' : 'off') + '.svg')

			update_property_rules(category, property);
		});

		// Toggle the "regular expression" input.
		$configuration_list.on('change', 'select.rule-selector', function (ev) {
			var $select = ev.findElement('select'),
				value = $select.getValue(),
				category = $select.up('.category-container').readAttribute('id'),
				property = $select.up('div[data-property]').readAttribute('data-property');

			if (value === 'FILTER_VALIDATE_REGEXP') {
				$select.up('label').next('label').show();
			} else {
				$select.up('label').next('label').hide();
			}

			if (value === 'VALIDATE_BY_TEXTFIELD') {
				$select.up('label').next('div.textarea-selection').show();
			} else {
				$select.up('label').next('div.textarea-selection').hide();
			}

			update_property_rules(category, property);
		});

		// Toggle the unique and mandatory buttons.
		$configuration_list.on('change', 'textarea.value-field,input.checkbox', function (ev) {
			var $property_div = ev.findElement('div[data-property]'),
				category = $property_div.up('.category-container').readAttribute('id'),
				property = $property_div.readAttribute('data-property');

			update_property_rules(category, property);
		});

		// If the regular expression is changed, we update call the "update_property_rules" function.
		$configuration_list.on('change', 'input.regex-field', function (ev) {
			var $input = ev.findElement('input').removeClassName('box-red'),
				value = $input.getValue(),
				$property_div = $input.up('div[data-property]'),
				property = $property_div.readAttribute('data-property'),
				category = $property_div.up('.category-container').readAttribute('id');

			try {
				new RegExp(value).test('test');
				update_property_rules(category, property);
			} catch (e) {
				$input.addClassName('box-red');
				idoit.Notify.error('[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__REGEX_SYNTAX_ERROR"}]');
			}
		});

		// Show and hide the category configurations.
		$configuration_list.on('click', '.toggle-header .btn-secondary', function (ev) {
			var $button = ev.findElement('button'),
				$container = $button.up('.category-container').down('.attribute-container').toggleClassName('hide');

			if ($container.hasClassName('hide')) {
				$button.down('img').writeAttribute('src', window.dir_images + 'axialis/user-interface/angle-right-small.svg');
			} else {
				$button.down('img').writeAttribute('src', window.dir_images + 'axialis/user-interface/angle-down-small.svg');
			}
		});

		// Refresh the validation cache.
		$cache_button.on('click', function () {
			$cache_button.down('img').addClassName('animation-rotate').writeAttribute('src', window.dir_images + 'axialis/user-interface/loading.svg');

			new Ajax.Request('?call=validate_field&ajax=1&func=reset_validation_cache', {
				method: 'post',
				onSuccess: function (transport) {
					var json = transport.responseJSON,
						$message = $cache_button.next('p').removeClassName('box-red').removeClassName('box-green');

					$cache_button.down('img').removeClassName('animation-rotate').writeAttribute('src', '[{$dir_images}]axialis/basic/symbol-update.svg');

					if (json.success) {
						$message.addClassName('box-green')
							.update(new Element('span', {className: 'vam'}).update(json.data))
							.insert({top: new Element('img', {src: '[{$dir_images}]axialis/basic/symbol-ok.svg', className: 'mr5 vam'})});
					} else {
						$message.addClassName('box-red')
							.update(new Element('span', {className: 'vam'}).update(json.message))
							.insert({top: new Element('img', {src: '[{$dir_images}]axialis/basic/symbol-cancel.svg', className: 'mr5 vam'})});
					}

					$message.show();
				}});
		});

		// The save-logic
		$save_button.on('click', function () {
            let updateHiddenFields = { };

            [{if !empty($visibilityConfig)}]
            const $visibilityConfig = JSON.parse('[{$visibilityConfig|json_encode|escape:"javascript"}]');

            let categoryConstant,
                validationRules,
                foundItem,
                categoryProperties,
                hiddenFields = [];

            for(const index in category_configuration) {
                // @see ID-9194
                if (!category_configuration.hasOwnProperty(index)) {
                    continue;
                }

                categoryConstant = category_configuration[index].categoryConstant;
                validationRules = category_configuration[index].rules.config;
                categoryProperties = category_configuration[index].properties;

                for(const propertyKey in validationRules) {
                    // @see ID-9194
                    if (!validationRules.hasOwnProperty(propertyKey)) {
                        continue;
                    }

                    if (validationRules[propertyKey].check.mandatory) {
                        foundItem = $visibilityConfig.find((item) => {
                            return item.propertyKey === propertyKey
                                       && item.categoryConstant === categoryConstant
                                       && !item.isNotHideable
                                       && (item.isHidden || item.hideInOverview);
                        });

                        if (foundItem){
                            if (!updateHiddenFields[categoryConstant]){
                                updateHiddenFields[categoryConstant] = [];
                            }

                            updateHiddenFields[categoryConstant].push(foundItem.propertyKey);
                            hiddenFields.push(category_configuration[index].categoryTitle + ': ' + categoryProperties[foundItem.propertyKey]);
                        }
                    }
                }
            }

            if (hiddenFields.length) {
                let list = "\n\n";
                list += '- ' + hiddenFields.join("\n- ") + "\n\n";

                if (!confirm('[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__ATTRIBUTES_ARE_HIDDEN" p_bHtmlEncode=false}]'.replace('%s', list))) {
                    return;
                }
            }
            [{/if}]

			new Ajax.Request('?call=validate_field&ajax=1&func=save_validation_configuration', {
				method: 'post',
				parameters: {
					configuration:JSON.stringify(category_configuration),
                    updateAttributeVisibility: JSON.stringify(updateHiddenFields)
				},
				onSuccess: function (transport) {
					var json = transport.responseJSON;

					if (! is_json_response(transport, true)) {
						return;
					}

					if (json.success) {
						idoit.Notify.success('[{isys type="lang" ident="LC__INFOBOX__DATA_WAS_SAVED"}]');
					} else {
						idoit.Notify.error(json.message, {sticky:true});
					}
				}
			});
		});

		var check_regex = function () {
			var $pattern = $('cmdb-validation-regex-pattern').removeClassName('box-red'),
				$search = $('cmdb-validation-regex-search'),
				$result = $('cmdb-validation-regex-result').removeClassName('box-neutral-400').removeClassName('box-red').removeClassName('box-green'),
				regex = $pattern.getValue().strip(),
				regex_result;

			/*
			// LF: Remove this code because the test would otherwise not represent the later validation ("^...$" will not be added on purpose).
			if (regex.substr(0, 1) !== '^') {
				regex = '^' + regex;
			}

			if (regex.substr(-1, 1) !== '$') {
				regex += '$';
			}
			*/

			try {
				regex_result = new RegExp(regex).exec($search.getValue().strip());

				if (regex_result) {
					$result.addClassName('box-green').update('[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__REGEX_CHECK_SUCCESS"}]');
				} else {
					$result.addClassName('box-red').update('[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__REGEX_CHECK_FAILURE"}]');
				}
			} catch (e) {
				$pattern.addClassName('box-red');
				$result.addClassName('box-red').update(e);
				idoit.Notify.error('[{isys type="lang" ident="LC__SETTINGS__CMDB__VALIDATION__REGEX_SYNTAX_ERROR"}]');
			}
		};

		$('cmdb-validation-regex-pattern', 'cmdb-validation-regex-search')
			.invoke('observe', 'blur', check_regex)
			.invoke('observe', 'keydown',function (ev) {
				if (ev.keyCode == Event.KEY_RETURN) {
					ev.preventDefault();

					check_regex();
				}
			});

		$('cmdb-validation-regex-button').observe('click', check_regex);

		$('cmdb-validation').select('button.window-toggle').invoke('on', 'click', function (ev) {
            var $button = ev.findElement('button'),
				$container = $button.up('.toggle-header').next('div');

			if ($container.hasClassName('hide')) {
				$button.down('img').writeAttribute('src', window.dir_images + 'axialis/user-interface/angle-down-small.svg');
                $container.removeClassName('hide');
			} else {
				$button.down('img').writeAttribute('src', window.dir_images + 'axialis/user-interface/angle-right-small.svg');
				$container.addClassName('hide');
			}
		});

		// Finally we load the configured validation rules.
		[{foreach $configured_categories as $l_category}]
		ajax_counter ++;
		$category_select.setValue('[{$l_category}]');
		$category_add.simulate('click');
		[{/foreach}]

		$category_select.setValue('g:isys_cmdb_dao_category_g_global');
	})();
</script>
