[{isys_group name="tom.content.table"}]
[{if $options.tableConfigURL}]
	<a href="[{$options.tableConfigURL}]" class="mainTableConfigLink" id="mainTableListConfig">
		<img src="[{$dir_images}]icons/silk/table_edit.png" title="[{isys type="lang" ident="LC__CMDB__LIST_CONFIGURE"}]" />
	</a>
[{/if}]

[{if $options.resizeColumns && $options.resizeColumnAjaxURL}]
	<span id="[{$unique}]-column-resetter" class="mainTableConfigLink">
		<img src="[{$dir_images}]icons/silk/table.png" title="[{isys type="lang" ident="LC__MODULE__CMDB__RESTORE_DEFAULT_LIST_WIDTH"}]" />
	</span>
[{/if}]

[{if $options.filter && $options.filterColumns}]
	<div class="input-group mainTableFilterInput search">
		[{assign var="defaultValue" value=$options.filterDefaultColumn}]
		[{assign var="defaultValueField" value=$options.filterDefaultColumn.field}]
		<input id="[{$defaultValueField}]" class="input" type="text" name="tableFilter[[{$options.filterDefaultColumn.field}]]" value="[{if array_key_exists($defaultValue.field, $options.filterDefaultValues)}][{$options.filterDefaultValues.$defaultValueField}][{/if}]" autofocus="autofocus" />
		<div class="input-group-addon input-group-addon-clickable" id="filter-expand-button" title="[{isys type="lang" ident="LC__CMDB__OBJECT_LIST__FILTER_EXPAND"}]">
			<img src="[{$dir_images}]icons/silk/bullet_arrow_down.png" />
		</div>
		<div class="input-group-addon input-group-addon-clickable" id="filter-reset" title="[{isys type="lang" ident="LC__UNIVERSAL__RESET"}]">
			<img src="[{$dir_images}]icons/silk/cross.png" />
		</div>
		<div class="input-group-addon input-group-addon-clickable" id="[{$unique}]-filter-button" title="[{isys type="lang" ident="LC__CMDB__OBJECT_LIST__FILTER_TOOLTIP"}]">
			<img src="[{$dir_images}]icons/silk/zoom.png" />
		</div>
	</div>
	<div class="mainTableFilterInput text-right" style="width:auto;">
		<span class="mr5">[{isys type="lang" ident="LC_UNIVERSAL__FILTER"}]</span><strong>[{$options.filterDefaultColumn.title}]</strong>
	</div>
[{/if}]

	<div id="mainTableRowsPerPage" class="input-group mainTableFilterInput" style="width: 150px;">
		<div class="input-group-addon input-group-addon-unstyled">[{isys type="lang" ident="LC__CMDB__LIST_SHOW"}]</div>
		[{isys type="f_dialog" name="`$unique`-rows-per-page"}]
		<div class="input-group-addon input-group-addon-unstyled">/ [{$rows}] [{isys type="lang" ident="LC__UNIVERSAL__ENTRIES"}]</div>
	</div>

	<div id="[{$unique}]-pager" class="mainTablePager p5">
		[{$pager}]
	</div>

	<div id="advanced-filters" class="hide">

		<table>
		[{foreach from=$options.filterColumns item="filterLabel" key="field"}]

			[{if is_array($filterLabel)}]
			<tr>
				<td>
					<label for="tableFilter[[{$field}]]">CMDB-Status</label>
				</td>
				<td>
					<select name="tableFilter[[{$field}]]" class="input input-block">
						<option value="-1">[{isys_tenantsettings::get('gui.empty_value', '-')}]</option>
						[{foreach from=$filterLabel item="statusValue" key="statusName"}]
						[{if array_key_exists($field, $options.filterDefaultValues) && $options.filterDefaultValues.$field == $statusValue}]
						<option value="[{$statusValue}]" selected="selected">[{$statusName}]</option>
						[{else}]
						<option value="[{$statusValue}]">[{$statusName}]</option>
						[{/if}]
						[{/foreach}]
					</select>
				</td>
			</tr>
			[{else}]
			<tr>
				<td>
					<label for="tableFilter[[{$field}]]">[{$filterLabel}]</label>
				</td>
				<td>
					<input class="input input-block" type="text" name="tableFilter[[{$field}]]" value="[{if array_key_exists($field, $options.filterDefaultValues)}][{$options.filterDefaultValues.$field}][{/if}]" />
				</td>
			</tr>
			[{/if}]
		[{/foreach}]
			<tr>
				<td></td>
				<td>
					<button type="button" id="advanced-filters-clear" class="btn">
						<img src="[{$dir_images}]icons/silk/cross.png" />
						<span>[{isys type="lang" ident="LC__UNIVERSAL__RESET"}]</span>
					</button>

					<button type="button" id="advanced-filters-filter" class="btn">
						<img src="[{$dir_images}]icons/silk/zoom.png" />
						<span>[{isys type="lang" ident="LC_UNIVERSAL__FILTER"}]</span>
					</button>
				</td>
			</tr>
		</table>

	</div>

[{if count($data)}]
	<table id="[{$unique}]" class="mainTable border-top" style="table-layout: fixed;">
		<colgroup>
			[{if $options.enableCheckboxes}]
				<col />
			[{/if}]
			[{foreach $header as $field}]
				<col />
			[{/foreach}]
		</colgroup>
		<thead>
		<tr>
			[{if $options.enableCheckboxes}]
				<th class="no-drag">
					<span>
						<label class="mainTableCheckbox"><input type="checkbox" title="[{isys type="lang" ident="LC__MODULE__CMDB__LIST_CHECK_ALL_CURRENT_PAGE"}]" name="table_id_all[]" value="0" /></label>
					</span>
				</th>
			[{/if}]
			[{foreach $header as $fieldTitle => $field}]
				<th>
					[{if $options.order}]<img src="[{$dir_images}]icons/silk/bullet_arrow_up.png" class="sort-arrow opacity-30 hide">[{/if}]
					<span class="overflowable" title="[{$fieldTitle}]">[{$field}]</span>
				</th>
			[{/foreach}]
		</tr>
		</thead>
		<tbody class="mainTableHover">
		[{foreach $data as $row}]
			<tr data-id="[{$row.__id__}]">
				[{foreach $row as $key => $col}]
					[{if $options.enableCheckboxes && $key == '__id__'}]
						<td>
							[{if $options.dragDrop}]<div class="drag-handle"></div>[{/if}]
							<label class="mainTableCheckbox"><input type="checkbox" name="table_ids[]" value="[{$col}]" /></label>
						</td>
					[{else}]
						<td><span class="overflowable">[{$col}]</span></td>
					[{/if}]
				[{/foreach}]
			</tr>
		[{/foreach}]
		</tbody>
	</table>
[{else}]
	<div class="m5 p5 box-blue">
		<img src="[{$dir_images}]icons/silk/information.png" class="vam mr5" /><span class="vam">[{isys type="lang" ident="LC__CMDB__FILTER__NOTHING_FOUND_STD"}]</span>
	</div>
[{/if}]
	<script type="application/javascript">
		var advancedFilter      = false,
			$defaultFilterInput = $$('.mainTableFilterInput.search');

		// In case the elements do not exist (may happen if "filter" is set to false).
		if ($defaultFilterInput && $defaultFilterInput[0])
		{
			$defaultFilterInput = $defaultFilterInput[0].down('.input');
		}
		else
		{
			// Create a dummy element to prevent JS errors.
			$defaultFilterInput = new Element('input');
		}

		(function () {
			'use strict';

			var $table                = $('[{$unique}]'),
			    columnSizes           = '[{$options.columnSizes|json_encode|escape:"javascript"}]'.evalJSON(),
			    $columnResetButton    = $('[{$unique}]-column-resetter'),
			    $rowsPerPage          = $('[{$unique}]-rows-per-page'),
			    $filterButton         = $('[{$unique}]-filter-button'),
			    $pager                = $('[{$unique}]-pager'),
			    $filterField          = $('[{$defaultValueField}]'),
			    $filterExpandButton   = $('filter-expand-button'),
			    $filterResetButton    = $('filter-reset'),
			    $advancedFilter       = $('advanced-filters'),
			    $advancedFilterButton = $('advanced-filters-filter'),
			    $advancedFilterClear  = $('advanced-filters-clear'),
				$replacePlaceholder   = new ReplacePlaceholders([{$options.replacerOptions}]),
				i;

			advancedFilter = advanceFilterActive();

			if (!window.tableCache || typeof window.tableCache !== 'object')
			{
				// Define the tableCache.
				window.tableCache = {"[{$pagerCurrentUrl}]": $replacePlaceholder.replacePlaceholders($('main_content').innerHTML.trim())};
			}

			if (!Object.isArray(columnSizes))
			{
				columnSizes = [];
			}

			if ($table)
			{
				var tableComp = new TableComponent($table, {
					dragDrop:               [{if $options.dragDrop}]true[{else}]false[{/if}],
					dragDropBoxContent:     '<img src="' + window.dir_images + 'icons/silk/database_copy.png" class="mr5"><span>%count% [{isys type="lang" ident="LC__CMDB__OBJECT_LIST__DRAG_OBJECTS"}]</span>',
					checkboxes:             [{if $options.enableCheckboxes}]true[{else}]false[{/if}],
					resizeColumns:          [{if $options.resizeColumns}]true[{else}]false[{/if}],
					resizeColumnAjaxURL:    '[{$options.resizeColumnAjaxURL}]',
					columnSizes:            columnSizes,
					order:                  [{if $options.order}]true[{else}]false[{/if}],
					orderColumns:           '[{$options.orderColumns|json_encode|escape:"javascript"}]'.evalJSON(),
					currentOrderColumn:     '[{$smarty.get.orderBy|default:$options.orderDefaultColumn}]',
					currentOrderDirection:  '[{$smarty.get.orderByDir|default:$options.orderDefaultDirection}]',
					orderAscendingMessage:  '[{isys type="lang" ident="LC__CMDB__LIST_ORDER_ASCENDING"}]',
					orderDescendingMessage: '[{isys type="lang" ident="LC__CMDB__LIST_ORDER_DESCENDING"}]',
					rowClick:               [{if $options.rowClick}]true[{else}]false[{/if}],
					rowClickUrl:            '[{$options.rowClickURL}]',
					keyboardCommands:       [{if $options.keyboardCommands}]true[{else}]false[{/if}],
					loadingMessage:         '[{isys type="lang" ident="LC__UNIVERSAL__LOADING"}]',
					quickInfoActive:        !![{isys_usersettings::get('gui.quickinfo.active', 1)}],
					quickInfoDelay:         [{isys_usersettings::get('gui.quickinfo.delay', 0.5)}],
					replacerOptions:        [{$options.replacerOptions}]
				});
			}

			if ($columnResetButton && tableComp)
			{
				$columnResetButton.on('click', function () {
					tableComp.resetColumns();
				})
			}

			if ($rowsPerPage)
			{
				$rowsPerPage.on('change', function () {
                    var urlQueryParams = document.location.href.parseQuery();   // @See ID-4728
					urlQueryParams.rowsPerPage = $rowsPerPage.getValue();
					delete urlQueryParams['[{\idoit\Component\Table\Table::CURRENT_PAGE}]'];

					document.location.href = window.www_dir + '?' + Object.toQueryString(urlQueryParams);
				});
			}

			if ($filterButton && $filterExpandButton)
			{
				var cachedBackend = new Autocompleter.Cache(
						function (searchString, suggest, options) {
							new Ajax.Request(www_dir + '?viewMode=1001&objTypeID=[{$smarty.get.objTypeID}]', {
								method:     'get',
								parameters: {
									'tableFilter[[{$defaultValueField}]]': ($filterField ? $filterField.getValue() : ''),
									suggestion:                            1,
									rand:                                  (new Date()).getTime()
								},
								onSuccess:  function (response) {
									suggest(response.responseJSON);
								}
							});
						}, {
							minChars:    3,
							choices:     125,
							fuzzySearch: true
						}
				);

				idoit.cachedLookup = cachedBackend.lookup.bind(cachedBackend);

				var rnd        = Math.floor(Math.random() * 9999),
				    el_choices = 'theChoices' + rnd;

				$('body').insert(new Element('div', {id: el_choices, className: 'autocomplete global-search'}));

				if ($filterField) {
					[{if isys_usersettings::get('gui.objectlist.autocomplete_search', 1)}]
					var _completer = new Autocompleter.Json(
	                    $filterField, el_choices, idoit.cachedLookup, {
								frequency:         .15,
								choices:           85,
								// Do NOT use translations that contain "... {<number>} ...". That breaks JS because of window.replaceTablePlaceholders();
								searchPlaceHolder: '[{isys type="lang" ident="LC__MODULE__SEARCH__TITLE"}]',
								updateElement:     function (li) {
									// override default behaviour
									var link = li.getAttribute('data-link'), search = li.getAttribute('data-search');

									if (link)
									{
										document.location.href = encodeURI(link);
										this.selectedItem = li;
									}

									if (search == '1')
									{
										$filterButton.simulate('click');
										return true;
									}
								}
							}
					);
					[{/if}]
				}

				$filterExpandButton.on('click', function () {
					$advancedFilter.toggleClassName('hide');

					if ($advancedFilter.hasClassName('hide')) {
						$filterExpandButton.down('img').writeAttribute('src', window.dir_images + 'icons/silk/bullet_arrow_down.png');
					} else {
						$filterExpandButton.down('img').writeAttribute('src', window.dir_images + 'icons/silk/bullet_arrow_up.png');

						$advancedFilter.down('input').focus();
					}
				});

				$filterButton.on('click', function (event) {
					document.location.href = window.www_dir + '?' + Object.toQueryString(retrieveUrlPartsFiltered());
				});
			}

			if ($pager)
			{
				$pager.on('click', '.dots', function () {
					var page = prompt('[{isys type="lang" ident="LC__UNIVERSAL__JUMP_TO_PAGE"}]', '1');

					if (page === null)
					{
						// User clicked "cancel" - do nothing.
						return;
					}

					page = parseInt(page);

					if (isNaN(page))
					{
						idoit.Notify.warning('[{isys type="lang" ident="LC__CMDB__OBJECT_LIST__INVALID_PAGE_NUMBER"}]', {life: 5});
						return;
					}

					if (page < 1)
					{
						idoit.Notify.warning('[{isys type="lang" ident="LC__CMDB__OBJECT_LIST__PAGE_NUMBER_DOES_NOT_EXIST"}]'.replace('%pages%', '[{$options.pages}]'), {life: 5});
						return;
					}

					if (page > parseInt('[{$options.pages}]'))
					{
						idoit.Notify.warning('[{isys type="lang" ident="LC__CMDB__OBJECT_LIST__PAGE_NUMBER_DOES_NOT_EXIST"}]'.replace('%pages%', '[{$options.pages}]'), {life: 5});
						return;
					}

					$pager.fire('pager:loadAndDisplayPage', {url: ('[{$pagerUrl}]'.replace('%25page%25', page))});
				});

				$pager.on('click', 'a', function (ev) {
					var $page = ev.findElement('a'),
					    url   = $page.readAttribute('href');

					// Prevent the click on the link (opening in a new tab still works)!
					ev.preventDefault();

					// Setting the URL.
					window.pushState({}, '', url);

					// Display a loading sign.
					$page.update(new Element('img', {src: window.dir_images + 'ajax-loading.gif'}));

					// If the URL has already been cached simply display it!
					$pager.fire('pager:loadAndDisplayPage', {url: url});
				});

				$pager.on('pager:loadAndDisplayPage', function (ev) {
					var url = ev.memo.url;

					$pager.fire('pager:loadPage', {
						url:      url,
						callback: function () {
							$('main_content').update(window.tableCache[url]);
						}
					});
				});

				$pager.on('pager:loadPage', function (ev) {
					var url      = ev.memo.url,
					    callback = ev.memo.callback;

					// If the URL has already been cached simply display it!
					if (!window.tableCache.hasOwnProperty(url))
					{
						// Ajax pagination.
						new Ajax.Request(url + '&[{$smarty.const.C__GET__AJAX_CALL}]=category&[{$smarty.const.C__GET__AJAX}]=1', {
							method:     'get',
							onComplete: function (xhr) {
								window.tableCache[url] = $replacePlaceholder.replacePlaceholders(xhr.responseText.trim());

								if (Object.isFunction(callback))
								{
									callback();
								}
							}
						});
					}
					else
					{
						if (Object.isFunction(callback))
						{
							callback();
						}
					}
				});

				[{if $pagerNextUrl}]
				// Preload the next page.
				if (!window.tableCache.hasOwnProperty('[{$pagerNextUrl}]'))
				{
					$pager.fire('pager:loadPage', {url: '[{$pagerNextUrl}]'});
				}
				[{/if}]
			}

			function displayAdvancedFilter()
			{
				var $mainSearchField = $$('.mainTableFilterInput.search');

				if ($mainSearchField && $mainSearchField[0])
				{
					$mainSearchField = $mainSearchField[0];
				}
				else
				{
					$mainSearchField = false;
				}

				if (advancedFilter)
				{
					var $labels = $advancedFilter.select('label'),
					    $inputs = $advancedFilter.select('.input'),
						searchString = [],
						label,
						$valueElement;

					for (i in $labels) {
						if ($labels.hasOwnProperty(i)) {
							label = ($labels[i].textContent || $labels[i].innerText || $labels[i].innerHTML);
							$valueElement = $inputs[i];

							if ($valueElement.tagName.toLowerCase() == 'input' && !$valueElement.getValue().blank())
							{
								searchString.push(label + ' = "' + $valueElement.getValue() + '"');
							}
							else if ($valueElement.tagName.toLowerCase() == 'select' && $valueElement.getValue() != -1)
							{
								$valueElement = $inputs[i].down(':selected');

								searchString.push(label + ' = "' + ($valueElement.textContent || $valueElement.innerText || $valueElement.innerHTML) + '"');
							}
						}
					}

					$defaultFilterInput.writeAttribute('readonly', 'readonly').setValue(searchString.join(' [{isys type="lang" ident="LC__UNIVERSAL__AND"}] '));

					if ($filterButton)
					{
						$filterButton.hide();
					}

					if ($mainSearchField)
					{
						$mainSearchField.setStyle({width:'60%'}).next().hide();
					}
				}
				else
				{
					$defaultFilterInput.writeAttribute('readonly', null);

					if ($filterButton)
					{
						$filterButton.show();
					}

					if ($mainSearchField)
					{
						$mainSearchField.setStyle({width:null}).next().show();
					}
				}
			}

			if ($defaultFilterInput) {
				$defaultFilterInput.on('keyup', function () {
					var $defaultFilterInputRef = $advancedFilter.down('.input[name="' + $defaultFilterInput.readAttribute('name') + '"]');

					if ($defaultFilterInputRef)
					{
						$defaultFilterInputRef.setValue($defaultFilterInput.getValue());
					}
				});
			}

			function processAdvanceFilters (ev)
			{
				var tmpAdvanceFilter = !!advancedFilter,
					$defaultFilterInputRef = $advancedFilter.down('.input[name="' + $defaultFilterInput.readAttribute('name') + '"]'),
				    $input = ev.findElement('.input');

				advancedFilter = advanceFilterActive();

				if (advancedFilter != tmpAdvanceFilter)
				{
					// When removing the last "advanced filter" character, we empty the default search input.
					if ($defaultFilterInputRef && !$defaultFilterInputRef.getValue().blank()) {
						$defaultFilterInput.setValue($defaultFilterInputRef.getValue());
					} else {
						$defaultFilterInput.setValue('');
					}
				}
				else if (!advancedFilter)
				{
					if ($input.readAttribute('name') == 'tableFilter[[{$options.filterDefaultColumn.field}]]')
					{
						$defaultFilterInput.setValue($input.getValue());
					}
				}

				displayAdvancedFilter();
			}

			function processFilter (ev) {
                if (ev.keyCode === 13)
                {
                    ev.preventDefault();

                    $filterButton.simulate('click');
                }
			}

			function clearAdvanceFilters ()
			{
				advancedFilter = false;

				$advancedFilter.select('input.input').invoke('setValue', '');
				$advancedFilter.select('select.input').invoke('setValue', -1);

				$defaultFilterInput.setValue('');

				displayAdvancedFilter();

				$filterButton.simulate('click');
			}

			$advancedFilter.on('keyup', 'input.input', processAdvanceFilters);
			$advancedFilter.on('change', 'select.input', processAdvanceFilters);
            $advancedFilter.on('keydown', 'input.input', processFilter);

            if ($filterField) {
                $filterField.on('keydown', processFilter);
            }

			$advancedFilterButton.on('click', function () {
				$filterButton.simulate('click');
			});

			$filterResetButton.on('click', clearAdvanceFilters);
			$advancedFilterClear.on('click', clearAdvanceFilters);

			$(document).on('keydown', function (event) {
				if (event.keyCode == 88 && event.altKey)
				{
					clearAdvanceFilters();
				}
			});

			function advanceFilterActive () {
				// Find out if any advanced filter field is filled:
				return $advancedFilter.select('.input:not([name*="[{$options.filterDefaultColumn.field}]"])')
		            .invoke('getValue')
		            .filter(function(val) {
						return !(val.blank() || val == -1);
					}).length > 0;
			}

            function retrieveUrlPartsFiltered() {
                var urlParts = document.location.href.parseQuery(),
                    $filterFields,
                    i;

                if (advancedFilter)
                {
                    // If we use the "advanced filters", we only want to include these to our query.
                    $filterFields = $advancedFilter.select('.input');
                }
                else
                {
                    // If we use the default filter field only include that one.
                    $filterFields = [$defaultFilterInput];
                }

                // Now we remove all "tableFilter*" parameters from the URL.
                for (i in urlParts)
                {
                    if (urlParts.hasOwnProperty(i))
                    {
                        if (i.indexOf('tableFilter[') > -1)
                        {
                            delete urlParts[i];
                        }
                    }
                }

                // And freshly add all specific filter fields, that are not empty.
                for (i in $filterFields)
                {
                    if ($filterFields.hasOwnProperty(i))
                    {
                        if ($filterFields[i].tagName.toLowerCase() == 'input' && !$filterFields[i].getValue().blank())
                        {
                            urlParts[$filterFields[i].readAttribute('name')] = $filterFields[i].getValue();
                        }
                        else if ($filterFields[i].tagName.toLowerCase() == 'select' && !$filterFields[i].getValue().blank() && $filterFields[i].getValue() != -1)
                        {
                            urlParts[$filterFields[i].readAttribute('name')] = $filterFields[i].getValue();
                        }
                    }
                }

                // Remove the "current page".
                delete urlParts['[{\idoit\Component\Table\Table::CURRENT_PAGE}]'];

                // This is necessary for the "memorize filter" feature.
                urlParts.filtered = 1;

                return urlParts;
            }

			displayAdvancedFilter();
		})();
	</script>
[{/isys_group}]
