<?php

Lib::loadClass('ViewAjax');

class TableAjax extends ViewAjax {

	private $_cnf = '';// Column
	private $_htmlID = '';
	private $_dataSource = null;
	private $_rowFunctions = array();
	private $_pageSizes = array();
	private $_filterInit = null;
	private $_forceFilterInit = null;
	private $_showProcesInit = true;

	public function __construct($tblAcl) {
		$this->_tbl = $tblAcl->getName();
		$this->_acl = $tblAcl;
		$this->_zasobID = $tblAcl->getID();
		Lib::loadClass('Data_Source');
		$this->_dataSource = new Data_Source($tblAcl->getDB());
		$this->_dataSource->setTable($tblAcl->getName());
		$realFieldList = $tblAcl->getRealFieldList();
		$this->_dataSource->setCols($realFieldList);
		$this->_dataSource->setColTypes($tblAcl->getTypes());
		$this->_dataSource->setVirtualCols($tblAcl->getVirtualFieldList());
		$this->_dataSource->setFieldGroupWrite('A_ADM_COMPANY', $tblAcl->hasFieldType('A_ADM_COMPANY'));
		$this->_dataSource->setFieldGroupRead('A_CLASSIFIED', $tblAcl->hasFieldType('A_CLASSIFIED'));
		$this->_dataSource->setAccessFltrAllowed(!$tblAcl->hasSuperAccessPerms());

		$adminFields = array('A_RECORD_CREATE_DATE', 'A_RECORD_CREATE_AUTHOR', 'A_RECORD_UPDATE_DATE', 'A_RECORD_UPDATE_AUTHOR');
		foreach ($adminFields as $vAdmFld) {
			if (!in_array($vAdmFld, $realFieldList) && $tblAcl->hasFieldType($vAdmFld)) {
				$this->_dataSource->addCol($vAdmFld);
			}
		}

		$this->_pageSizes = array(10, 20, 50, 100);// default page sizes
		$this->_filterInit = new stdClass();

		$hash = V::get('_hash', '', $_GET);
		if ($hash) {
			$this->_htmlID = $hash;
			$this->_readState();
		} else {
			$this->_htmlID = $this->generateHtmlID();
			$this->_readState();
		}
	}

	public function showProcesInit($bool = true) {
		$this->_showProcesInit = $bool;
	}

	private function _hasStateFilterInit() {
		return array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache']) && array_key_exists('_filterInit', $_SESSION['TableAjax_Cache'][$this->_htmlID]);
	}

	// TODO: read state from cache by key $this->_htmlID
	// TODO: load filters and state: table, edit, add, etc.
	// TODO: save this data in Workspace 1, 2, 3, etc.
	// TODO: default filters in VIEWTABLE_AJAX
	//   $tbl->setLabel($zasobObj->OPIS);
	//   $tbl->setFilterInit($filterInit);
	//   $tbl->addRowFunction('edit');
	//   $tbl->addRowFunction('hist');
	//   $tbl->addRowFunction('files');
	//   $tbl->addRowFunction('cp');
	private function _readState() {
		if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
			$_SESSION['TableAjax_Cache'] = array();
		}
		//trigger_error("F." . __FUNCTION__ . " (" . (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) . ")", E_USER_NOTICE);
		//trigger_error("F." . __FUNCTION__ . " (".basename($_SERVER['SCRIPT_FILENAME'])."::_filterInit: " . json_encode($_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit']) . ")", E_USER_NOTICE);
		if (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
			foreach ($_SESSION['TableAjax_Cache'][$this->_htmlID] as $k => $v) {
				//trigger_error("F." . __FUNCTION__ . " key: ({$k})", E_USER_NOTICE);
				switch ($k) {
					case '_label':
						$this->_label = $v;
						break;
					case '_filterInit':
						$this->_filterInit = $v;
						break;
					case '_rowFunctions':
						$this->_rowFunctions = $v;
						break;
					default:
						
				}
			}
		}
	}

	protected function _saveState($key = null) {
		if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
			$_SESSION['TableAjax_Cache'] = array();
		}

		if (!array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
			$_SESSION['TableAjax_Cache'][$this->_htmlID] = array();
		}

		if (!$key) {
			$_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
			$_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
			$_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
		} else if ($key == '_label') {
			$_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
		} else if ($key == '_filterInit') {
			$_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
		} else if ($key == '_rowFunctions') {
			$_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
		}
	}

	public function setPageSizes($pageSizes) {
		$this->_pageSizes = $pageSizes;
	}

	public function setFilterInit($filterInit) {
		if ($this->_hasStateFilterInit()) {
			return;
		}
		$this->_filterInit = (object)$filterInit;
		$this->_saveState();
	}

	/**
	 * @param array $forceFilterInit
	 */
	public function setForceFilterInit($forceFilterInit) {
		$this->_forceFilterInit = (object)$forceFilterInit;
	}

	private function setFilters($filterInit) {
		$this->_filterInit = (object)$filterInit;
		$this->_saveState();
	}

	public function addRowFunction($funName, $funParams = array()) {
		$defaultRowFunction = array();
		//$defaultRowFunction['edit'] = '<a href="#EDIT/{0}" class="ico-pencil" title="Edytuj rekord"></a>';
		//$defaultRowFunction['hist'] = '<a href="#HIST/{0}" class="ico-book" title="Historia"></a>';
		//$defaultRowFunction['files'] = '<a href="#FILES/{0}" class="ico-folder-open" title="Pliki"></a>';
		//$defaultRowFunction['cp'] = '<a href="#" class="ico-plus-sign" title="Kopiuj rekord" onclick="return tableAjaxCopy({0});"></a>';

		$defaultRowFunction['edit'] = array('href'=>'#EDIT/{0}', 'ico'=>'ico-pencil', 'title'=>'Edytuj rekord');
		$defaultRowFunction['hist'] = array('href'=>'#HIST/{0}', 'ico'=>'ico-book', 'title'=>'Historia');
		$defaultRowFunction['files'] = array('href'=>'#FILES/{0}', 'ico'=>'ico-folder-open', 'title'=>'Pliki');
		$defaultRowFunction['cp'] = array('href'=>'#', 'ico'=>'ico-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');

		if (array_key_exists($funName, $defaultRowFunction)) {
			$this->_rowFunctions[$funName] = $defaultRowFunction[$funName];
		}
		else {
			$this->_rowFunctions[$funName] = $funParams;
		}
		$this->_saveState('_rowFunctions');
	}

	private function _parseRowFunctions($recordID = null, $pomin = array(), $showLabel = false) {
		$rowFunctions = array();
		foreach ($this->_rowFunctions as $kFunName => $vParams) {
			if (in_array($kFunName, $pomin)) continue;

			//$rowFunctionsOut .= str_replace('{0}', $recordID, $vUrl);
			$attrs = array();
			// $defaultRowFunction['cp'] = (object)array('href'=>'#', 'ico'=>'ico-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');
			$label = '';
			$ico = '';
			foreach ($vParams as $kParamName => $v) {
				if ($kParamName == 'ico') {
					if ($showLabel) {
						$ico = '<span class="' . $v . '"></span>';
					} else {
						$attrs[] = 'class="' . $v . '"';
					}
					continue;
				}

				$attr = $v;

				if ($recordID > 0) {
					$attr = str_replace('{0}', $recordID, $attr);
				}

				if ($showLabel && $kParamName == 'title') {
					$label = $attr;
				}

				$attr = $kParamName . '="' . $attr . '"';

				$attrs[] = $attr;
			}
			$rowFunctions[$kFunName] = '<a ' . implode(' ', $attrs) . '>' . "{$ico}{$label} " . '</a>';
		}
		return $rowFunctions;
	}

	private function _showRowFunctions($recordID = null, $pomin = array(), $showLabel = false) {
		$rowFunctionsOut = $this->_parseRowFunctions($recordID, $pomin, $showLabel);
		$rowFunctionsOut = implode('', $rowFunctionsOut);
		return $rowFunctionsOut;
	}

	private function _showRowFunctionsJson($recordID = null, $pomin = array(), $showLabel = false) {
		$rowFunctions = $this->_parseRowFunctions($recordID, $pomin, $showLabel);
		$rowFunctions = (object)$rowFunctions;
		return $rowFunctions;
	}

	private function getProcesInitSelected() {
		$userAcl = User::getAcl();
		return $userAcl->getPermsProcesId();
	}

	private function _fetchConnectedProcesInitList() {
		$pInitList = array();// [proces_init_id] => label (DESC)
		if (!$this->_showProcesInit) {
			return $pInitList;
		}
		$userAcl = User::getAcl();
		$pInitListRaw = $userAcl->getProcesInitList($this->_zasobID);
		if (empty($pInitListRaw)) {
			return $pInitList;
		}
		$db = DB::getDB();
		$sql = "select p.`ID`, p.`DESC`
			from `CRM_PROCES` as p
			where p.`ID` in(" . implode(",", array_values($pInitListRaw)) . ")
				and p.`TYPE`='PROCES_INIT'
		";
		$res = $db->query($sql);
		while ($r = $db->fetch($res)) {
			$pInitList[$r->ID] = $r->DESC;
		}
		return $pInitList;
	}

	public function allowTreeView() {
		if ($this->_tbl == 'CRM_LISTA_ZASOBOW') return true;
		if ($this->_tbl == 'CRM_PROCES') return true;
		return false;
	}

	public function render() {
		$pInitList = $this->_fetchConnectedProcesInitList();
		$pInitListSelected = $this->getProcesInitSelected();

		ob_start();
		?>

		<style type="text/css">
.AjaxTable{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0;}

.AjaxTableCont {position:relative; margin:10px 0; width:100%; overflow-x:auto; border:none;}
.AjaxTable *,
.AjaxTableCont .foot * {font-size:12px !important;}
.AjaxTable.table {white-space:nowrap; width:auto;}
.AjaxTable p {margin:0;}
.AjaxTable td, .AjaxTable th {line-height:18px;}
.AjaxTable i {margin: 0 0 0 2px;opacity: 0.5;}
.AjaxTable span.filter {background-color:#999;}
.AjaxTable .indeterminate {opacity: 0.4;-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=40)";filter:alpha(opacity=40);}
.AjaxTable .columnpicker li, .AjaxTable .actions li {padding-left:5px;}
.AjaxTableCont .btn-toolbar {margin:2px 0 0 0;}
.AjaxTableCont .btn-toolbar .btn-group {vertical-align:top;}
.AjaxTable input[type=checkbox] {margin:0;padding:0;height:13px;}
.AjaxTable input[type=text].filter {margin:0;padding:0;box-shadow:none;width:100%;background:#eee;float:left;color:#000;}
.AjaxTable input[type=text].filter {border-width:2px 0;border-color:#eee;border-style:solid;}
.AjaxTable input[type=text].filter-active {border-color:#00ACCC;}
.AjaxTable .date-wrap {width:100%;min-width:115px;}
.AjaxTable .dateWrap .add-on {margin:0;padding:0;background:none;border:none;float:right;cursor:pointer;}
.AjaxTableCont .dropdown-menu {max-height:250px;padding:0 20px 0 0;overflow:auto;}
.AjaxTable .actions a {padding:0;margin:0;}
.AjaxTableCont .text-right {text-align:right}
.AjaxTableCont .breadcrumb em {color:#bbb;}

.AjaxTable-loading .foot .foot-info {padding-left:20px; background:url(./icon/loading.gif) no-repeat left top;}
.AjaxTable-loading .head-info {background:url(./icon/loading.gif) no-repeat left top; background-position:0 6px;}
.AjaxTable-loading .loading-info,
.AjaxTableCont .inlineEditBox .loading-info {display:block; padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;}
.AjaxTableCont .loading-info {display:none;}
.AjaxTableCont .inlineEditBox .loading-info {display:block;}
.AjaxTable .stickyCol2 input[type=text].filter {width:50px;}
.AjaxTableCont .table {margin-bottom:0px;}
.AjaxTableCont .foot {margin:10px;}
.AjaxTableCont .stickyCol1 a:hover { }
.AjaxTableTaskCnt {padding:0 10px 10px 10px;}

.AjaxTable .tbl-short-txt{max-width:140px; overflow:hidden;}
.AjaxTable .tbl-short-txt span{display:block; height:18px;}
.AjaxTable .tooltip-inner{white-space:normal;}
.AjaxTable thead .sort .ta-ordering {cursor:pointer;}
.AjaxTable thead .sort .ta-ordering span {margin:0 14px 0 0; padding:0 14px 0 0; background-repeat:no-repeat; background-position:right top;}
.AjaxTable thead .sort .ta-ordering-down span {background-image:url(stuff/twitter-bootstrap/img/ordering-down.png);}
.AjaxTable thead .sort .ta-ordering-up span {background-image:url(stuff/twitter-bootstrap/img/ordering-up.png);}
.AjaxTable thead .sort .ta-ordering {position:relative;}

.AjaxTable thead .sort th .hover-show:hover{background-color:#000; background-image:url(stuff/twitter-bootstrap/img/glyphicons-halflings-white.png);}
.AjaxTable thead .sort th .hover-show{display:none;}
.AjaxTable thead .sort th:hover .hover-show{display:inline;}

.AjaxTable thead .sort .ta-ordering .remove-cell {position:absolute; top:6px; right:2px; display:none;}
.AjaxTable thead .sort .ta-ordering:hover .remove-cell {display:block;}

.AjaxTableCont .foot .foot-info { float:left; padding:0 20px; }
 .AjaxTableCont .foot .foot-info p { line-height:16px; margin:5px 0; }
 .AjaxTableCont .pagination { margin:0; }
 .AjaxTableCont .pagination a { line-height:16px; }

.AjaxTableCont .AjaxTableEdit-label { display:block; margin:0 0 3px 0; font-size:12px !important; line-height:16px !important; }
.AjaxTableCont .AjaxTableEdit-label code { padding:0; white-space:nowrap; background-color:transparent; border:none; color:#777; font-size:10px !important; line-height:14px !important; }
.AjaxTableCont .AjaxTableEdit .show-last-value .btn-appendBack,
.AjaxTableCont .AjaxFrmHorizontalEdit .show-last-value .btn-appendBack {display:none;}
.AjaxTableHist em {color:silver;}

.TableAjax-SpecialFilter {margin:0;padding:4px 4px 4px 127px;}
.TableAjax-SpecialFilter .btn-group {margin:0 4px;padding:0;}

/* overwrite bootstrap table border */
.AjaxTable,    .AjaxTableEdit,
.AjaxTable td, .AjaxTableEdit td,
.AjaxTable th, .AjaxTableEdit th { border-color:#999; }

/*  */
.AjaxTable .cell-A_STATUS-NORMAL { background:#aeffae; color:#000; text-align:center; }
.AjaxTable .cell-A_STATUS-WAITING { background:#ffd2ff; color:#000; text-align:center; }
.AjaxTable .cell-A_STATUS-MONITOR { background:#cccaff; color:#000; text-align:center; }
.AjaxTable .cell-A_STATUS-WARNING { background:#ffbaba; color:#000; text-align:center; }
.AjaxTable .cell-A_STATUS-DELETED { background:#e0e0e0; color:#808080; text-align:center; }
.AjaxTable .cell-A_STATUS-OFF_SOFT { background:#fce3b7; color:#808080; text-align:center; }
.AjaxTable .cell-A_STATUS-OFF_HARD { background:#eee; color:#808080; text-align:center; }

.AjaxTableCont .valign-btns-bottom a { vertical-align:text-bottom; font-weight:normal; font-size:12px; line-height:14px; }
		</style>

		<div class="AjaxTableCont">
			<ul class="breadcrumb">
				<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>
				<?php if (!empty($pInitList)) : ?>
					<div class="btn-group pull-right">
						<a class="btn btn-mini btn-info dropdown-toggle" data-toggle="dropdown" href="#" title="Uruchom filtr procesu powiązanego z tabelą <?php echo $this->getLabel(); ?>">
							Filtr procesu
							<span class="caret"></span>
						</a>
						<ul class="dropdown-menu pull-left">
							<?php foreach ($pInitList as $kId => $vLabel) : ?>
								<?php if ($pInitListSelected && $pInitListSelected == $kId) : ?>
								<li class="disabled">
								<?php else : ?>
								<li>
								<?php endif; ?>
									<a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=<?php echo $kId; ?>&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="<?php echo htmlspecialchars("{{$kId}} {$vLabel}"); ?>"><?php echo "{{$kId}} " . V::strShortUtf8($vLabel, 50); ?></a>
								</li>
							<?php endforeach; ?>
						</ul>
					</div>
				<?php endif; ?>
				<?php if ($this->_tbl == 'IN7_MK_BAZA_DYSTRYBUCJI') : ?>
					<a class="pull-right" style="padding:0 20px 0 0;" href="<?php echo "index.php?MENU_INIT=TREEJS&ZASOB_ID={$this->_zasobID}"; ?>"><i class="icon-eye-open"></i> Drzewo</a>
				<?php elseif ($this->allowTreeView()) : ?>
					<a class="pull-right" style="padding:0 20px 0 0;" href="<?php echo "index.php?MENU_INIT=VIEWTREE_AJAX&ZASOB_ID={$this->_zasobID}"; ?>"><i class="icon-eye-open"></i> Drzewo</a>
				<?php endif; ?>
			</ul>
			<div id="<?php echo $this->_htmlID; ?>"></div>
		</div>
		<script>
(function ($, undefined) {
	var TableAjax = function () {
		var priv = {}; //private api
		var publ = {}; //public api

		priv.options = {};
		var defaults = {
			url: '',  //webservice url
			urlData: '', //webservice params
			urlPost: false, //use POST instead of GET
			debug: false, //prints debug info to console
			filter: false, //show filter row
			filterInit: false,// init filters data
			forceFilterInit: false,
			columnPicker: false, //show columnpicker
			checkboxes: false, //show body checkboxes
			actions: '', //holds action links
			pageSize: 10, //current pagesize
			pageSizes: [10, 20, 30, 40, 50, 'All'], //available pagesizes
			hidePagerOnEmpty: false, //removes pager if no rows
			types: { //type specific options
				string: {},
				number: {},
				bool: {},
				date: {}
			},
			rowFunctions: false,
			tblFunctions: false,
			specialFilterFunctions: false,
			filtersClean: false,
			router: false,
			longDesc: false
		};

		var _cont; // container holding table
		var _table; // the table
		var _head; // table header
		var _headSort; // table header sorting row
		var _headFilter; // table header columns filter row
		var _headSpecialFilter; // table header special filter row
		var _body; // table body
		var _foot; // table footer
		var _inlineEditBox; // inline edit box with form
		var _popoverCell; // inline popover cell
		var _popoverCellCurrent; // inline popover cell
		var _popoverCellAjaxXhr;

		var _data; //columns and rows
		var _currPage = 1; // current page
		var _pageSize; // current pagesize
		var _totalPages; // total pages
		var _currSortCol; // current sorting column
		var _currSortFlip = false; // current sorting direction
		var _currDpOp; // clicked datepicker operator
		var _filterCols = {}; // array with current filters
		var _filterFields = {}; // array with filter DOM elements
		var _specialFilters = {}; // array with current special filters
		var _filterTimeout; // timer for delayed filtering
		var _uniqueCol; // reference to column with the unique property
		var _uniqueCols = {}; // array with checked rows
		var _checkToggleChecked = false; // check-all toggle state

		var _tableWidth;

		/*
		 initialize the plugin.
		 */
		priv.init = function () {
			_cont = priv.options.id;
			priv.options.types.string = ((priv.options.types || {}).string || {});
			priv.options.types.number = ((priv.options.types || {}).number || {});
			priv.options.types.bool = ((priv.options.types || {}).bool || {});
			priv.options.types.date = ((priv.options.types || {}).date || {});

			if (priv.options.specialFilterFunctions && priv.options.filterInit) {
				$.map(priv.options.specialFilterFunctions, function(groupObj, groupName) {
					var fltrName = 'sf_' + groupName;
					if (fltrName in priv.options.filterInit) {
						_specialFilters[groupName] = priv.options.filterInit[fltrName];
					}
				});
			}

			//try call webservice for data
			priv.update(priv.options.router);

			if (typeof priv.options.router == "function") {
				$(window).bind('hashchange', function() {
					//console.log('hashchange: location.hash: ' + location.hash);
					priv.options.router.apply(this);
				});
			}
		};

		/*
		 creates the table with all its parts and handlers.
		 note that only the parts we need is created.
		 (yeah, the function is huge)
		 */
		priv.createTable = function () {
			//create table itself
			if (!_table) {
				_head = _body = _foot = undefined;
				_table = $('<table class="AjaxTable table table-striped table-hover table-bordered table-condensed"></table>').appendTo(_cont);
			}

			//create the header which will later hold both sorting and filtering
			if (!_head) {
				_table.find('thead').remove();
				_headSort = _headFilter = _headSpecialFilter = undefined;
				_head = $('<thead></thead>').prependTo(_table);
			}

			// TODO: test colgroup
			//_table.find('colgroup').remove();
			//$('<colgroup><col span="1" style="background-color:red"><col span="10" style="width:200px;overlow-x:auto"></colgroup>').prependTo(_table);

			//sort the columns in index order
			var colsSorted = Object.keys(_data.cols).sort(function (a, b) {
				return _data.cols[a].index - _data.cols[b].index;
			});

			//create the header sorting row
			if (!_headSort) {
				_head.find('.sort i').tooltip('hide');
				_head.find('.sort').remove();
				_headSort = $('<tr class="sort"></tr>').prependTo(_head);

				//create the functions column
				if (priv.options.rowFunctions || priv.options.filtersClean) {
					var headCell = $('<th class="text-right head-info stickyCol1"></th>').appendTo(_headSort);
					$.map(priv.options.tblFunctions, function(funObj, funName){
						var funHtml = $('<a></a>');
						funHtml.attr('href', funObj.href || '#');
						if (funObj.title) funHtml.attr('title', funObj.title);
						if (funObj.icon) funHtml.attr('class', 'ico-' + funObj.icon);
						if (funObj.method) funHtml.on('click', priv[funObj.method]);
						funHtml.appendTo(headCell);
					});
				}

				//create the checkall toggle
				if (_uniqueCol && priv.options.checkboxes) {
					var checked = _checkToggleChecked ? 'checked' : '';
					var headCell = $('<th></th>').appendTo(_headSort);
					var elem = $('<input {0} class="checkToggle" type="checkbox" />'.f(checked)).appendTo(headCell);
					elem.on('change', priv.checkToggleChanged);
				}

				//create the sortable headers
				for (var i = 0; i < colsSorted.length; i++) {
					var column = colsSorted[i];
					var props = _data.cols[column];
					if (!props.hidden) {
						var headCell = $('<th class="ta-ordering"></th>').appendTo(_headSort);
						if (i == 1) headCell.addClass('stickyCol2');

						if (false) {// TODO: old way
							var link = $('<a class="pull-left" href="#">{0}</a>'.f(props.friendly || column));
							link.on('click', {column: column}, priv.columnClicked).appendTo(headCell);

							if (props.tooltip) {
								$('<i class="icon-info-sign"></i>').tooltip({
									title: props.tooltip.trim(),
									html: true,
									container: 'body',
									placement: "top",
									delay: {
										show: 500,
										hide: 100
									}
								}).appendTo(link);
							}

							//Add sort arrow
							if (column == _currSortCol) {
								if (_currSortFlip) $('<i class="icon-chevron-down pull-right"></i>').appendTo(headCell);
								else $('<i class="icon-chevron-up pull-right"></i>').appendTo(headCell);
							}

							//Add hide btn
							if (column != 'ID') {
								var hideColBtn = $('<i class="icon-remove pull-right hover-show"></i>');
								hideColBtn.on('click', {column: column},  priv.columnHideClicked);
								hideColBtn.appendTo(headCell);
							}
						}

						if (props.type != 'special') {
							headCell.on('click', {column: column}, priv.columnClicked);
						}
						var colTitle = column;
						if (props._tsRetId) {
							colTitle = 'Kliknij na pole i przejdź do powiązanych rekordów (' + colTitle + ')';
						}

						if (props.friendly) {
							var headCnt = $('<span class="pull-left" title="{1}">{0}</span>'.f(props.friendly, colTitle));
						} else {
							var headCnt = $('<span class="pull-left" title="{1}">{0}</span>'.f(column, colTitle));
						}
						headCnt.appendTo(headCell);

						//Add sort arrow
						if (column == _currSortCol) {
							if (_currSortFlip) headCell.addClass('ta-ordering-down');
							else headCell.addClass('ta-ordering-up');
						}

						if (column != 'ID') {
							var hideColBtn = $('<i class="icon-remove remove-cell"></i>');
							hideColBtn.on('click', {column: column},  priv.columnHideClicked);
							hideColBtn.appendTo(headCell);
						}

					}
				}
			}

			//create the header filtering row
			if (!_headFilter && priv.options.filter) {
				_head.find(".filter").remove();
				_headFilter = $('<tr class="filter"></tr>').appendTo(_head);
				var headCell;
				var elem;
				var placeHolder = '';
				var tooltip = '';

				//create the functions column
				if (priv.options.rowFunctions || priv.options.filtersClean) {
					var headCell = $('<th class="text-right stickyCol1"></th>').appendTo(_headFilter);
					if (priv.options.filtersClean) {
						var elem = $('<a href="#" title="Kasuj filtry" class="ico-remove">&nbsp;</a>').appendTo(headCell);
						elem.on('click', priv.filtersClean);
					}
				}

				//create the filter checkbox
				if (_uniqueCol && priv.options.checkboxes) {
					tooltip = priv.options.types.bool.filterTooltip || 'Toggle between:<br/>indeterminate,<br/>checked,<br/>unchecked';
					headCell = $('<th></th>').appendTo(_headFilter);
					elem = $('<input class="filter indeterminate" checked type="checkbox" />').appendTo(headCell);
					$.map(_filterCols, function (colProps, col) {
						if (col == "unique") {
							if (colProps.filter) elem.prop('checked', true).removeClass('indeterminate');
							else if (!colProps.filter) elem.prop('checked', false).removeClass('indeterminate');
							else if (colProps.filter == '') elem.addClass('indeterminate');
						}
					});

					if (tooltip) {
						elem.tooltip({
							title: tooltip.trim(),
							html: true,
							container: 'body',
							trigger: 'hover',
							placement: 'top',
							delay: {
								show: 500,
								hide: 100
							}
						});
					}
					elem.on('click', {column: "unique"}, priv.filterChanged);
				}

				//create the column filters
				for (var i = 0; i < colsSorted.length; i++) {
					var column = colsSorted[i];
					var props = _data.cols[column];
					tooltip = props.filterTooltip === true ? undefined : props.filterTooltip === false ? '' : props.filterTooltip;
					placeHolder = props.placeHolder === true ? undefined : props.placeHolder === false ? '' : props.placeHolder;

					if (!props.hidden) {
						headCell = $('<th></th>').appendTo(_headFilter);
						if (i == 1) headCell.addClass('stickyCol2');

						// @mark MarkTableAjaxFilterColType
						switch (props.type || 'string') {
								case "number":
										if (placeHolder == undefined) placeHolder = priv.options.types.number.placeHolder;
										placeHolder = (placeHolder === true || placeHolder == undefined) ? '10..20 =50' : placeHolder === false ? '' : placeHolder;
										if (tooltip == undefined) tooltip = priv.options.types.number.filterTooltip;
										tooltip = (tooltip === true || tooltip == undefined) ? 'Values 10 to 20:<br/>10..20<br/>Values exactly 50:<br/>=50' : tooltip === false ? '' : tooltip;
										elem = $('<input placeholder="{0}" class="filter" type="text" />'.f(placeHolder));
										elem.on('keyup', {column: column}, priv.filterChanged);
										break;
								case "date":
										if (placeHolder == undefined) placeHolder = priv.options.types.date.placeHolder;
										placeHolder = (placeHolder === true || placeHolder == undefined) ? '-7..0' : placeHolder === false ? '' : placeHolder;
										if (tooltip == undefined) tooltip = priv.options.types.date.filterTooltip;
										tooltip = (tooltip === true || tooltip == undefined) ? 'Today:<br/>0..1<br/>A week today excluded:<br/>-7..0' : tooltip === false ? '' : tooltip;
										elem = $('<div><input placeholder="{0}" class="filter" type="text" /></div>'.f(placeHolder));

										if (priv.options.types.date.datePicker === true || priv.options.types.date.datePicker == undefined)
										{
												if ($().datepicker)
												{
														elem.addClass('date-wrap');
														var today = 0;//new priv.ext.XDate(false).setHours(0, 0, 0, 0).toString('yyyy-MM-dd');
														var dp = $('<div style="float:right" class="date" data-date="{0}" data-date-format="{1}" />'.f(today, 'yyyy-mm-dd')).appendTo(elem);
														$('<input style="display:none" type="text"  />').appendTo(dp);
														$('<span class="add-on"><i class="icon-chevron-right"></i></span>').on('click', {op: "l"}, priv.dpOpChanged).appendTo(dp);
														$('<span class="add-on"><i class="icon-chevron-left"></i></span>').on('click', {op: "r"}, priv.dpOpChanged).appendTo(dp);
														dp.datepicker({weekStart:1});
														dp.on('changeDate', {column: column, input: $('input.filter', elem)}, priv.dpClicked);
												}
												else
												if (priv.options.debug) console.log('datepicker plugin not found');
										}
										elem.on('keyup', 'input.filter', {column: column}, priv.filterChanged);
										break;
								case "bool":
										if (tooltip == undefined) tooltip = priv.options.types.bool.filterTooltip;
										tooltip = (tooltip === true || tooltip == undefined) ? 'Toggle between:<br/>indeterminate,<br/>checked,<br/>unchecked' : tooltip === false ? '' : tooltip;
										elem = $('<input class="filter indeterminate" checked type="checkbox" />');
										elem.on('click', {column: column}, priv.filterChanged);
										break;
								case "string":
										if (placeHolder == undefined) placeHolder = priv.options.types.string.placeHolder;
										placeHolder = (placeHolder === true || placeHolder == undefined) ? '%' : placeHolder === false ? '' : placeHolder;
										if (tooltip == undefined) tooltip = priv.options.types.string.filterTooltip;
										tooltip = (tooltip === true || tooltip == undefined) ? 'Find str: str<br/>Find all but str: !str<br/>Find str inside: %str%' : tooltip === false ? '' : tooltip;
										elem = $('<input placeholder="{0}" class="filter" type="text" size="8" />'.f(placeHolder));
										elem.on('keyup', {column: column}, priv.filterChanged);
										break;
								case "special":
										elem = $('<div>&nbsp;</div>');
										break;
								case "none":
										elem = $('<div>&nbsp;</div>');
										break;
						}

						if (false) {// tooltip OFF - (tooltip)
							elem.tooltip({
								title: tooltip.trim(),
								html: true,
								container: 'body',
								trigger: 'focus',
								placement: 'top',
								delay: {
									show: 500,
									hide: 100
								}
							});
						}

						if (elem && props.filter) {
							$.map(_filterCols, function (colProps, col) {
								if (col == column) {
									if (colProps.col.type == 'bool') {
										if (colProps.filter) elem.prop('checked', true).removeClass('indeterminate');
										else if (!colProps.filter) elem.prop('checked', false).removeClass('indeterminate');
										else if (colProps.filter == '') elem.addClass('indeterminate');
									}
									else elem.val(colProps.filter);
								}
							});
							if (priv.options.forceFilterInit && undefined !== priv.options.forceFilterInit[column]) {
								elem.prop('disabled', true);
							}
							elem.appendTo(headCell);

							_filterFields[column] = elem;
						}
					}
				}
			}

			//create the header special filters row
			if (!_headSpecialFilter && priv.options.specialFilterFunctions) {
				//create the functions column
				if (priv.options.specialFilterFunctions) {
					jQuery(_cont).prev('.TableAjax-SpecialFilter').remove();
					var _headSpecialFilter = $('<div class="btn-toolbar TableAjax-SpecialFilter"></div>').insertBefore(_cont);
					$.map(priv.options.specialFilterFunctions, function(groupObj, groupName) {
						var btnHtml, btnSelected, groupHtml = $('<div class="btn-group"></div>');
						// _specialFilters[e.data.group] = e.data.value;
						if (groupName in _specialFilters) {
							btnSelected = _specialFilters[groupName];
						}
						if (groupObj.icon) {
							$('<button class="btn btn-mini" title="' + groupName + '"><i class="' + groupObj.icon + '"></i></button>').appendTo(groupHtml);
						}
						$.map(groupObj.btns, function(btnObj, btnName) {
							btnHtml = $('<button class="btn btn-mini' + ((btnSelected && btnSelected == btnObj.value)? ' active' : '') + '">' + btnName + '</button>').appendTo(groupHtml);
							btnHtml.on('click', {group: groupName, value: btnObj.value}, priv.specialFilterChanged);
						});
						btnHtml = $('<button class="btn btn-mini' + ((!btnSelected)? ' disabled' : '') + '" title="Kasuj filtr"><i class="icon-remove"></i></button>').appendTo(groupHtml);
						btnHtml.on('click', {group: groupName, value: ''}, priv.specialFilterChanged);
						groupHtml.appendTo(_headSpecialFilter);
					});
				}
			}

			//create the body
			if (!_body) {
				_table.find('tbody').remove();
				_body = $('<tbody></tbody>').insertAfter(_head);
				_body.on('change', '.unique', priv.rowChecked);
				//_body.on('click', 'td', priv.rowClicked);
				//_body.on('dbclick', 'td', priv.rowDBClicked);

				//find out what rows to show next...
				var rowsAdded = 0;
				_data.toRow = _data.fromRow + priv.options.pageSize;
				if (_data.toRow > _data.total)
						_data.toRow = _data.total;

				//slice out the chunk of data we need and create rows
				//$.each(_data.rows.slice(_data.fromRow, _data.toRow), function (index, props) {
				$.each(_data.rows, function (index, props) {
					var row = $('<tr></tr>').appendTo(_body);

					if (priv.options.rowFunctions || priv.options.filtersClean) {
						var cell = $('<td class="text-right stickyCol1"></td>').appendTo(row);
						var cellID = _uniqueCol || 'ID';
						cellID = (cellID in props)? props[cellID] : null;
						$.map(priv.options.rowFunctions, function(funObj, funName){
							$(funObj.f(cellID)).appendTo(cell);
						});
					}

					//create checkbox
					if (_uniqueCol && priv.options.checkboxes) {
						var check = _uniqueCols[props[_uniqueCol]] != undefined ? 'checked' : '';
						var checkable = props['checkable'] === false ? 'disabled' : '';
						var cell = $('<td></td>').appendTo(row);
						$('<input class="unique" {0} {1} type="checkbox" />'.f(check, checkable)).appendTo(cell);
					}

					//create cells
					for (var i = 0; i < colsSorted.length; i++) {
						var key = colsSorted[i];
						var val = props[key];
						if (!_data.cols[key]) return;
						if (_data.cols[key].unique) row.data('unique', val);

						var cellID = _uniqueCol || 'ID';
						cellID = (cellID in props)? props[cellID] : null;

						if (!_data.cols[key].hidden) {
							var cell = $('<td></td>').appendTo(row);
							cell.on('dblclick', {id:cellID, col:key}, priv.rowDblClicked);
							var cellCnt = $('<span></span>').appendTo(cell);
							if (i == 1) cell.addClass('stickyCol2');
							cell.data('column', key);
							if (val === undefined) continue;

							var format = props[key + 'Format'] || _data.cols[key].format || '{0}';
							var showTooltip = true;

							switch (_data.cols[key].type) {
								case "string":
									cellCnt.html(format.f(val));
									break;
								case "number":
									val = Number(val);
									var forceDecimals = !isNaN(_data.cols[key].decimals);
									if (forceDecimals) cellCnt.html(format.f(val.toFixed(_data.cols[key].decimals)));
									else {
										(val || 0) % 1 === 0
											? cellCnt.html(format.f(val))
											: cellCnt.html(format.f(val.toFixed(priv.options.types.number.decimals || 2)));
								}
									break;
								case "date":
									cellCnt.html(format.f(val));
									break;
								case "bool":
									$('<input type="checkbox" {0} disabled />'.f(val ? "checked" : "")).appendTo(cellCnt);
									break;
								case "special":
									cellCnt.html(format.f(val));
									break;
							}

							if (_data.cols[key]._tsRetId) {
								showTooltip = false;
								if (_data.cols[key]._tsRetId > 0) {
									cellCnt.on('click', {id:cellID, col:key, friendly:_data.cols[key].friendly, value:format.f(val)}, priv.popoverCell);
								}
							}

							if (i > 1 && priv.options.longDesc) {
								cell.addClass('tbl-short-txt');
								if (showTooltip) {
									cellCnt.tooltip({title: cellCnt.text(), placement: 'left'});
								}
							}
						}
					}
					rowsAdded++;

					//enough rows created?
					if (rowsAdded >= priv.options.pageSize) {
						_data.toRow = _data.fromRow + rowsAdded;
						return false;
					}
				});

				if (_currPage == 1) {
					_pageSize = rowsAdded;
					_totalPages = Math.round(Math.ceil(_data.total / _pageSize));
				}

				//pad with empty rows if we're at last page.
				if (_currPage == _totalPages) {
					while (rowsAdded < _pageSize) {
						var row = $('<tr></tr>').appendTo(_body);

						if (_uniqueCol && priv.options.checkboxes) {
							var cell = $('<td></td>').appendTo(row);
							$('<input disabled type="checkbox" />').appendTo(cell);
						}

						if (priv.options.rowFunctions || priv.options.filtersClean) {
							$('<td class="text-right stickyCol1">&nbsp;</td>').appendTo(row);
						}

						var i = 0;
						$.each(_data.cols, function (column, props) {
							i++;
							if (props.hidden) return;

							if (i == 1) {
								$('<td class="stickyCol2">&nbsp;</td>').appendTo(row);
							} else {
								$('<td>&nbsp;</td>').appendTo(row);
							}
						});
						rowsAdded++;
					}
				}
			}

			//create the footer
			if (!_foot) {
				_table.find('tfoot').remove();
				_foot = $('<tfoot></tfoot>').insertAfter(_body);

				//var footRow = $('<tr></tr>').appendTo(_foot);
				//var footCell = $('<td colspan="999"></td>').appendTo(footRow);

				// TODO: test load footer after table
				$(_cont).next('.foot').remove();
				_foot = $('<div class="foot"></div>').insertAfter(_cont);

				//create summary
				if (_data.total > 0) {
					$('<div class="foot-info"><p>Wiersze od {0} do {1} z {2}</p></div>'.f(_data.fromRow + 1, Math.min(_data.toRow, _data.total), _data.total)).appendTo(_foot);
				} else {
					$('<div><p>Brak wierszy pasujących do kryteriów wyszukiwania</p></div>').appendTo(_foot);
					_totalPages = 0;
				}

				//create the pager.
				var lowerPage = _currPage - 2;
				var upperPage = _currPage + 2;
				if (upperPage > _totalPages) {
					var diff = upperPage - _totalPages;
					upperPage = _totalPages;
					lowerPage -= diff;
				}
				if (lowerPage < 1) lowerPage = 1;
				if (upperPage < 5) upperPage = 5;

				var footToolbar = $('<div class="btn-toolbar"></div>').appendTo(_foot);
				var footDiv = $('<div class="btn-group"></div>').appendTo(footToolbar);
				var footPagerDiv = $('<div class="pagination"></div>').appendTo(footDiv);
				var footPagerUl = $('<ul></ul>').appendTo(footPagerDiv);

				$('<li class="{0}"><a href="#">&lt;&lt;</a></li>'.f(_currPage == 1 ? 'disabled' : ''))
					.on('click', {pageIndex: 1}, priv.pageChanged).appendTo(footPagerUl);
				$('<li class="{0}"><a href="#">&lt;</a></li>'.f(_currPage == 1 ? 'disabled' : ''))
					.on('click', {pageIndex: _currPage - 1}, priv.pageChanged).appendTo(footPagerUl);

				for (var i = lowerPage; i <= upperPage; i++) {
					var link;
					if (i != _currPage) link = $('<li class="{1}"><a href="#">{0}</a></li>'.f(i, i > _totalPages ? 'disabled' : ''));
					if (i == _currPage) link = $('<li class="active"><a href="#">{0}</a></li>'.f(i));

					if (link) {
						link.on('click', {pageIndex: i}, priv.pageChanged);
						link.appendTo(footPagerUl);
					}
				}
				$('<li class="{0}"><a href="#">&gt;</a></li>'.f(_currPage == _totalPages ? 'disabled' : ''))
					.on('click', {pageIndex: _currPage + 1}, priv.pageChanged).appendTo(footPagerUl);
				$('<li class="{0}"><a href="#">&gt;&gt;</a></li>'.f(_currPage == _totalPages ? 'disabled' : ''))
					.on('click', {pageIndex: _totalPages}, priv.pageChanged).appendTo(footPagerUl);

				//create pagesize dropdown
				if (priv.options.pageSizes.length) {
					var div = $('<div class="btn-group dropup pagesize"></div>').appendTo(footToolbar);
					var btn = $('<button class="btn btn-small dropdown-toggle" data-toggle="dropdown" href="#">Liczba wierszy&nbsp;</button>').appendTo(div);
					var span = $('<span class="caret"></span>').appendTo(btn);
					var ul = $('<ul class="dropdown-menu">').appendTo(div);

					$.each(priv.options.pageSizes, function (index, val) {
						var li = $('<li></li>').appendTo(ul);
						$('<a href="#">{0}</a>'.f(val)).appendTo(li);
					});
					div.on('click', 'a', priv.pageSizeChanged);
				}

				//create columnpicker dropdown
				if (priv.options.columnPicker) {
					var div = $('<div class="btn-group dropup columnpicker"></div>').appendTo(footToolbar);
					var btn = $('<button class="btn btn-small dropdown-toggle" data-toggle="dropdown" href="#">Kolumny&nbsp;</button>').appendTo(div);
					var span = $('<span class="caret"></span>').appendTo(btn);
					var ul = $('<ul class="dropdown-menu">').appendTo(div);

					$.each(_data.cols, function (col, props) {
						if (props.type != "unique" && col != 'ID') {
							var li = $('<li></li>').appendTo(ul);
							$('<input {0} type="checkbox" title="{1}" value="{1}" >&nbsp;{2}</input>'.f((props.hidden) ? '' : 'checked', col, props.friendly || col)).appendTo(li);
						}
					});
					div.on('click', 'input', priv.columnPickerClicked);
				}

				if (priv.options.rowFunctions) {
					$.map(priv.options.tblFunctions, function(funObj, funName){
						var div = $('<div class="btn-group"></div>').appendTo(footToolbar);
						var funHtml = $('<button class="btn btn-small"></button>');
						if (funObj.title) funHtml.attr('title', funObj.title);
						if (funObj.method) funHtml.on('click', priv[funObj.method]);
						else if (funObj.href) funHtml.on('click', {hash:funObj.href}, priv.routeChanged);

						var funIconHtml = $('<i></i>');
						if (funObj.icon) funIconHtml.attr('class', 'icon-' + funObj.icon);
						funIconHtml.prependTo(funHtml);

						funHtml.addClass('btn');
						funHtml.appendTo(div);
					});
				}

				//create actions dropdown
				if (priv.options.actions) {
					var div = $('<div class="btn-group dropup actions"></div>').appendTo(footToolbar);
					var btn = $('<button class="btn dropdown-toggle" data-toggle="dropdown" href="#"><i class="icon-list"></i>&nbsp;</button>').appendTo(div);
					var span = $('<span class="caret"></span>').appendTo(btn);
					var ul = $('<ul class="dropdown-menu">').appendTo(div);

					if (priv.options.actions.filter) {
						var li = $('<li></li>').appendTo(ul);
						$('<input {0} type="checkbox" >&nbsp;Filter</input>'.f(priv.options.filter ? 'checked' : '')).appendTo(li);
						li.on('click', 'input', function (e) {
							priv.options.filter = !priv.options.filter;
							_head = undefined;
							priv.createTable();
						});
					}
					if (priv.options.actions.columnPicker) {
						var li = $('<li></li>').appendTo(ul);
						$('<input {0} type="checkbox" >&nbsp;ColumnPicker</input>'.f(priv.options.columnPicker ? 'checked' : '')).appendTo(li);
						li.on('click', 'input', function (e) {
							priv.options.columnPicker = !priv.options.columnPicker;
							_foot = undefined;
							priv.createTable();
						});
					}
					if (priv.options.actions.custom) {
						$.each(priv.options.actions.custom, function (index, val) {
							var li = $('<li></li>').appendTo(ul);
							$(val).appendTo(li);
						});
					}
				}
			}

			var stickyCol1Width = 55;
			var stickyCol2Width = 50;
			if (undefined === _tableWidth) {
				_tableWidth = true;
				var contW = jQuery(_cont).width();
//console.log('_cont.width: ' + jQuery(_cont).width());
				var th1 = _table.find('.stickyCol1:first');
				var th2 = th1.next();
				var th1W = th1.innerWidth();
				var th2W = 50 + 2 * 5;//th2.innerWidth();
				var colsW = stickyCol1Width + 2 * 5 + 1 + stickyCol2Width + 2 * 5 + 1;
//console.log('thF.width: ' + th1W + '; ' +  th2W + '; colsW: ' + colsW);
				//jQuery(_cont).width(contW - colsW);
				jQuery(_cont).css({width:'' + (contW - colsW) + 'px', marginLeft:'' + colsW + 'px', overflowX:'scroll', overflowY:'visible', paddingBottom:'1px'});
//console.log('_cont.width new: ' + jQuery(_cont).width());
			}
			_table.find('.stickyCol1').css({position:'absolute',
				left:'0',
				top:'auto',
				width:'' + stickyCol1Width + 'px',
			});
			_table.find('.stickyCol2').css({position:'absolute',
				left:'' + (stickyCol1Width + 2 * 5 + 1) + 'px',
				top:'auto',
				width:'' + stickyCol2Width + 'px', 
				borderRight: '1px solid silver'
			});

			if (_data.total == 0 && priv.options.hidePagerOnEmpty) {
				$('.btn-toolbar', _foot).remove();
			}
			if (priv.options.debug) console.log('table created L.<?php echo __LINE__; ?>');
			if (typeof priv.options.tableCreated == 'function') {
				priv.options.tableCreated.call(_table.get(0), {table: _table.get(0)});
			}

			if (!_inlineEditBox) {
				$(_foot).next('.inlineEditBox').remove();
				_inlineEditBox = $('<div class="inlineEditBox modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>').insertAfter(_foot);
				var frmInlineEdit = $('<form style="margin:0;padding:0;"></form>').appendTo(_inlineEditBox);
				var iebHead = $('<div class="modal-header">').appendTo(frmInlineEdit);
				$('<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="icon-remove"></i></button>').appendTo(iebHead);
				$('<h3 id="myModalLabel">Edytuj</h3>').appendTo(iebHead);
				var iebBody = $('<div class="modal-body"></div>').appendTo(frmInlineEdit);
				$('<input type="hidden" name="ID" value="">').appendTo(iebBody);
				$('<input type="hidden" name="col" value="">').appendTo(iebBody);
				$('<div class="inlineEditBox-cnt"></div>').appendTo(iebBody);
				var iebFoot = $('<div class="modal-footer"></div>').appendTo(frmInlineEdit);
				$('<button class="btn" data-dismiss="modal" aria-hidden="true">Zamknij</button>').appendTo(iebFoot);
				var iebBtnSave = $('<input type="submit" value="Zapisz" class="btn btn-primary btn-save">').appendTo(iebFoot);

				frmInlineEdit.on('submit', function() {
					var data = _inlineEditBox.find('form').serialize();
					_inlineEditBox.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
					jQuery.ajax({
						url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT_INLINE_SAVE',
						type: 'POST',
						dataType: 'text',
						data: data,
						async: true,
						success: function (data) {
							//console.log('_inlineEditBox submit ajax data:', data);
							_inlineEditBox.find('.inlineEditBox-cnt').html(data);
							_inlineEditBox.find('.btn-save').hide();
							publ.loadPage(_currPage);
						},
						error: function (jhr, textStatus, errorThrown) {
							console.log('_inlineEditBox submit ajax error');
						}
					});

					return false;
				});
			}

			if (!_popoverCell) {
				$(_foot).next('.popoverCell').remove();
				_popoverCell = $('<div class="popoverCell" style="display:none"></div>').insertAfter(_foot);
			}

		};

		/*
		 calls the webservice(if defined).
		 used only inside priv.init
		 */
		priv.update = function (callback, skipCols, resetChecked) {
			if (!priv.options.url) {
				if (priv.options.debug) console.log('no url found L.<?php echo __LINE__; ?>');
				return;
			}

			if (priv.options.debug) console.log('requesting data from url:{0} data:{1} L.<?php echo __LINE__; ?>'.f(priv.options.url, JSON.stringify(priv.options.urlData) || ''));

			var initUrlAdd = '',
				reqData = {},
				filtersInitSet = false;
			if (priv.options.filterInit) {
				$.map(priv.options.filterInit, function (fltrProps, fltr) {
					switch (fltr) {
						case 'currSortCol':
							_currSortCol = fltrProps;
							initUrlAdd += '&currSortCol=' + fltrProps;
							break;
						case 'currSortFlip':
							_currSortFlip = (fltrProps == 'desc')? true : false;
							initUrlAdd += '&currSortFlip=' + fltrProps;
							break;
						default:
							if (fltr.substr(0, 3) == 'sf_') {
								reqData[fltr] = fltrProps;
								filtersInitSet = true;
							}
							else if (fltr.substr(0, 2) == 'f_') {
								reqData[fltr] = fltrProps;
								filtersInitSet = true;
							}
					}
				});
			}
			if (priv.options.forceFilterInit) {
				$.map(priv.options.forceFilterInit, function (fltrProps, fltr) {
					reqData['f_' + fltr] = fltrProps;
					filtersInitSet = true;
				});
			}

			$.ajax({
				url: priv.options.url + initUrlAdd,
				type: priv.options.urlPost ? 'POST' : 'GET',
				dataType: 'json',
				contentType: "application/json; charset=utf-8",
				data: reqData,
				async: true,
				success: function (data) {
					if (priv.options.debug) console.log('request finished L.<?php echo __LINE__; ?>');

					//assign the new data
					if (data.d && data.d.cols)
						priv.setData(data.d, skipCols, resetChecked);
					else
						priv.setData(data, skipCols, resetChecked);

					// set initial filters
					if (filtersInitSet && _data && _data.cols) {
						$.map(reqData, function(fltrValue, fltr){
							var colName = null;
							if (fltr.substr(0, 3) == 'sf_') {
								colName = fltr.substr(3);
							}
							else if (fltr.substr(0, 2) == 'f_') {
								colName = fltr.substr(2);
							}

							if (colName && _data.cols[colName]) {
								//add the filter to the filter array
								_filterCols[colName] = {
									filter: fltrValue,
									col: _data.cols[colName]
								};
							}
						});
					}

					//assign the new data
					if (data.d && data.d.cols)
						priv.setData(data.d, skipCols, resetChecked);
					else
						priv.setData(data, skipCols, resetChecked);

					if (typeof callback == "function")
						callback.call(this);
				},
				error: function (err) {
					//console.log('request error: {0}'.f(JSON.stringify(err)));
					if (typeof callback == "function")
						callback.call(this);
				}
			});
		};

		/*
		 assigns the new data.
		 */
		priv.setData = function (pData, skipCols, resetChecked) {
			var data = $.extend(true, {}, pData);
			data.fromRow = _data && _data.fromRow || 0;
			data.toRow = _data && _data.toRow || 0;

			//use previous column definitions?
			skipCols = skipCols || false;
			if (skipCols) data.cols = _data.cols;
			//else _filterCols = {};

			_data = data;
			_data.rowsOrg = _data.rows;

			//we might have more/less data now. Recalculate stuff.
			if (_currPage > 1) {
				_data.toRow = Math.min(_data.total, _data.toRow);
				_data.fromRow = _data.toRow - _pageSize;
				_data.fromRow = Math.max(_data.fromRow, 0);
				_currPage = Math.ceil(_data.fromRow / _pageSize) + 1;
				_totalPages = Math.ceil(_data.total / _pageSize);
			} else {
				_data.fromRow = 0;
				if (priv.options.pageSize != -1)
					_data.toRow = _data.fromRow + priv.options.pageSize;
				_data.toRow = Math.max(_data.toRow, _data.total);
			}

			//wash the new data a bit
			_uniqueCol = "";
			$.each(_data.cols, function (col, props) {
				//set sorting
				if (!_currSortCol && props.sortOrder) {
					_currSortCol = col;
					_currSortFlip = props.sortOrder != "asc";
				}

				//default to string type if missing
				if (!props.type) _data.cols[col].type = "string";

				//if several unique columns is defined, use the first.
				if (props.unique) {
					if (!_uniqueCol) _uniqueCol = col;
					else props.unique = false;
				}

				//if index property is missing, create one
				if (!props.index) _data.cols[col].index = new Number(0);//priv.ext.XDate();
				props.column = col;

				//set any initial filter
				if (!skipCols) {
					if (props.filter == undefined) props.filter = true;
					if (props.filter && typeof props.type != "bool" && typeof props.filter != "boolean") {
						_filterCols[col] = _filterCols[col] || {
							filter: String(props.filter),
							col: props
						};
					}
				}
			});

			//keep any previously checked rows around?
			if (resetChecked === true || resetChecked === undefined)
				_uniqueCols = {};
			else {
				for (var key in _uniqueCols)
					_uniqueCols[key] = priv.getRow(key);
			}

			if (_uniqueCol) {
				//create a unique column definition
				_data.cols["unique"] = {
					column: "unique",
					type: "unique",
					index: -1,
					hidden: true
				};

				//add rows that needs to be pre-checked
				$.each(_data.rows, function (index, row) {
					if (row["checked"] === true)
						_uniqueCols[row[_uniqueCol]] = row;
				});
			}

			if (!skipCols) {
				_head = undefined;
			}
			_body = undefined;
			_foot = undefined;
			priv.createTable();
		};

		/**
		 * Filters the data.
		 */
		priv.filter = function () {
			if (!priv.options.filter) return;
			if (Object.keys(_filterCols).length == 0) return;

			publ.loadPage(0);
		};

		/*
		 sorts the data on the current sorting column
		 */
		priv.sort = function () {
			if (!_data.cols[_currSortCol]) _currSortCol = "";
			if (!_currSortCol) return;

			publ.loadPage(0);
		};

		/*
		 helper that returns the underlying data by the unique value
		 */
		priv.getRow = function (unique) {
			var row;
			$.each(_data.rowsOrg, function (i, r) {
				if (r[_uniqueCol] == unique) {
					row = r;
					return false;
				}
			});
			return row;
		};

		/*
		 when: typing a filter
		 what: triggers filtering on the value
		 */
		priv.filterChanged = function (e) {
			//clear old timer if we're typing fast enough
			if (_filterTimeout) {
				clearTimeout(_filterTimeout);
				if (priv.options.debug) console.log('filtering cancelled');
			}

			var filter = this.value
				, fltr = $(this)
				, col = _data.cols[e.data.column]
				, timeout = 300;

			if (this.value) {
				if (!fltr.hasClass('filter-active')) {
					fltr.addClass('filter-active');
				}
			} else {
				if (fltr.hasClass('filter-active')) {
					fltr.removeClass('filter-active');
				}
			}

			//boolean filters needs some special care
			if (col.type == "bool" || col.type == "unique") {
				timeout = 0;
				var elem = $(this);
				var cssClass = 'indeterminate';
				if (elem.hasClass(cssClass)) {
					e.preventDefault();
					elem.removeClass(cssClass);
					filter = true;
				} else {
					if (!elem.is(':checked')) {
						filter = false;
					} else {
						elem.addClass(cssClass);
						filter = '';
					}
				}
			}

			//add the filter to the filter array
			_filterCols[col.column] = {
				filter: filter,
				col: col
			};

			//wait a few deciseconds before filtering
			_filterTimeout = setTimeout(function () {
				_filterTimeout = undefined;
				priv.filter();
			}, timeout);
		};

		priv.filtersClean = function (e) {
			if (_filterTimeout) {
				clearTimeout(_filterTimeout);
				if (priv.options.debug) console.log('filtering cancelled - filtersClean');
			}

			var filtersActive = false;
			$.map(_filterCols, function (colProps, col) {
				if (colProps.filter.length > 0) {
					filtersActive = true;
					colProps.filter = '';
				}
			});

			if (filtersActive) {
				// TODO: dont remove value from forceFilterInit fields - no field names in search fields?
				var elems = _head.find('tr.filter').find('input');
				_head.find('tr.filter').find('input').val('').prop('disabled', false);
				priv.filter();
			}
			return false;
		},

		/**
		 * Filters the data by specialFilter.
		 * when: click on special filter
		 * what: triggers filtering on the value
		 */
		priv.specialFilterChanged = function (e) {
			console.log('specialFilterChanged...');
			console.log(e.data);
			_specialFilters[e.data.group] = e.data.value;

			publ.loadPage(0);
		};

		priv.longTextChanged = function(e) {
			priv.options.longDesc = !priv.options.longDesc;
			_body.find('td').each(function(ind, el){
				var $el = jQuery(el);
				if (!$el.attr('class') || $el.attr('class') == 'tbl-short-txt') {
					//console.log(el.attr('class') + ': ' + el.text());
					if (el.firstChild && el.firstChild.nodeName == 'SPAN') {
						if (priv.options.longDesc) {
							$el.addClass('tbl-short-txt');
							var $elSpan = jQuery(el.firstChild);
							$elSpan.tooltip({title: $elSpan.text(), placement: 'left'});
						} else {
							$el.removeClass('tbl-short-txt');
						}
					}
				}
			});
			return false;
		},

		/*
		 when: changing page in pager
		 what: triggers table to be created with new page
		 */
		priv.pageChanged = function (e) {
			e.preventDefault();
			if (e.data.pageIndex < 1 || e.data.pageIndex > _totalPages) return;

			//set the new page
			_currPage = e.data.pageIndex;
			if (priv.options.debug) console.log('paging to index:{0} L.<?php echo __LINE__; ?>'.f(_currPage));

			//find out what rows to create
			_data.fromRow = ((_currPage - 1) * _pageSize);
			_data.toRow = _data.fromRow + _pageSize;
			if (_data.toRow > _data.rows.length) _data.toRow = _data.rows.length;

			//trigger callback
			if (typeof priv.options.pageChanged == 'function') {
				priv.options.pageChanged.call(e.target, {
					event: e,
					page: _currPage
				});
			}

			_body = undefined;
			_foot = undefined;
			priv.createTable();
		};

		/*
		 when: changing pagesize in pagesize dropdown
		 what: triggers table to be created with new pagesize
		 */
		priv.pageSizeChanged = function (e) {
			e.preventDefault();
			var val = $(this).text().toLowerCase();
			if (priv.options.debug) console.log('pagesize changed to:{0}'.f(val));

			//set the new pagesize
			if (val == "all") priv.options.pageSize = _data.rows.length;
			else priv.options.pageSize = parseInt(val);

			//revert to first page, as its gets messy otherwise.
			_currPage = 1;
			_data.fromRow = 0;
			_data.toRow = _data.fromRow + priv.options.pageSize;
			if (_data.toRow > _data.rows.length) _data.toRow = _data.rows.length;

			//trigger callback
			if (typeof priv.options.pageSizeChanged == 'function') {
				priv.options.pageSizeChanged.call(e.target, {
					event: e,
					pageSize: priv.options.pageSize
				});
			}

			_body = undefined;
			_foot = undefined;
			priv.createTable();
		};

		/*
		 when: clicking a column
		 what: triggers table to be sorted by the column
		 */
		priv.columnClicked = function (e) {
			e.preventDefault();
			if (priv.options.debug) console.log('col:{0} clicked'.f(e.data.column));

			//set the new sorting column
			if (_currSortCol == e.data.column) _currSortFlip = !_currSortFlip;
			_currSortCol = e.data.column;

			//trigger callback
			if (typeof priv.options.columnClicked == 'function') {
				priv.options.columnClicked.call(e.target, {
					event: e,
					column: _data.cols[_currSortCol],
					descending: _currSortFlip
				});
			}

			_headSort = undefined;
			_body = undefined;
			priv.sort();
		};

		priv.saveHiddenCols = function() {
			var reqData = {};

			$.each(_data.cols, function (col, props) {
				if (props.type != "unique" && col != 'unique' && col != 'ID') {
					reqData[col] = (props.hidden)? 'HIDE' : 'SHOW';
				}
			});

			$.ajax({
				url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIDDEN_COLS_SAVE',
				type: 'POST',
				dataType: 'text',
				data: reqData,
				async: true,
				success: function (data) {
					//console.log('hidden cols saved');
				},
				error: function (err) {
					console.log('request error: {0}'.f(JSON.stringify(err)));
				}
			});
		};

		/*
		 when: clicking a column in columnpicker
		 what: triggers table to show/hide the column
		 */
		priv.columnPickerClicked = function (e) {
			e.stopPropagation();

			var column = $(this).val();

			//toggle column visibility
			_data.cols[column].hidden = !_data.cols[column].hidden;

			priv.saveHiddenCols();

			//_data.cols[column].index = new priv.ext.XDate();
			_head = undefined;
			_body = undefined;
			priv.createTable();
		};

		priv.columnHideClicked = function (e) {
			e.stopPropagation();

			var column;
			if (e.data && e.data.column) {
				column = e.data.column;
			} else {
				return;
			}

			//toggle column visibility
			_data.cols[column].hidden = !_data.cols[column].hidden;

			priv.saveHiddenCols();

			//_data.cols[column].index = new priv.ext.XDate();
			_head = undefined;
			_body = undefined;
			_foot = undefined;
			priv.createTable();
		};

		/*
		 when: clicking a row checkbox
		 what: toggles checked state on row, and add/removes it from checked array
		 */
		priv.rowChecked = function (e) {
			var elem = $(this);

			//get the row's unique value
			var unique = elem.closest('tr').data('unique');
			if (priv.options.debug) console.log('row({0}) {1}'.f(unique, elem.is(':checked') ? 'checked' : 'unchecked'));

			//store the row in checked array
			if (elem.is(':checked')) _uniqueCols[unique] = priv.getRow(unique);
			else delete _uniqueCols[unique];
		};

		/*
		 when: clicking anywhere on a row
		 what: row data and other info is returned to caller
		 */
		priv.rowClicked = function (e) {
			if (!_uniqueCol) {
				if (priv.options.debug) console.log('no unique column specified');
				return;
			}

			//gather callback data
			var elem = $(this);
			var column = _data.cols[elem.data('column')];
			var unique = elem.closest('tr').data('unique');
			var row = priv.getRow(unique);
			var isChecked = elem.closest('tr').find('.unique').is(':checked');

			//trigger callback
			if (typeof priv.options.rowClicked == 'function') {
				priv.options.rowClicked.call(e.target, {
					event: e,
					row: row,
					column: column,
					checked: isChecked
				});
			}

		};

		/**
		 * Inline edit.
		 */
		priv.rowDblClicked = function (e) {
			// hide popover for typespecial fld on click
			if (_popoverCellCurrent) {
				_popoverCellCurrent.popover('hide');
			}

			// e.clientX: 1002; e.clientY: 245
			if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
				_inlineEditBox.modal();
				//_inlineEditBox.css({'position':'absolute', 'top':'100px', 'left':'100px'});
				_inlineEditBox.show();
				_inlineEditBox.find('input[name=ID]').val(e.data.id);
				_inlineEditBox.find('input[name=col]').val(e.data.col);
				_inlineEditBox.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
				$.ajax({
					url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT_INLINE&ID=' + e.data.id + '&col=' + e.data.col,
					type: 'GET',
					dataType: 'text',
					data: '',
					async: true,
					success: function (data) {
						_inlineEditBox.find('.inlineEditBox-cnt').html(data);
						_inlineEditBox.find('.btn-save').show();

						_inlineEditBox.find('.se_type-date').datepicker({
							format: "yyyy-mm-dd"
							, language: 'pl'
							, todayBtn: "linked"
						});
						_inlineEditBox.find('.se_type-datetime').parent().datetimepicker({
							language: 'pl'
							, format: 'yyyy-MM-dd hh:mm'
							, weekStart: 1
						});

						_inlineEditBox.find('textarea').autosize();

						var fld = _inlineEditBox.find('input[id^="f"]');
						if (fld && !fld.hasClass('se_type-date')) {
							fld.focus();

							fld.keydown(function(event) {
								console.log('input keydown: ', event.which);
								if (event.which == 13) {
									event.preventDefault();
									_inlineEditBox.find('form').submit();
								}
							});
						}
					},
					error: function (err) {
						console.log('err');
					}
				});
			} else {
				console.log('NO data');
				return false;
			}
		};

		priv.ajaxLoadTypeSpeciallCell = function(id, col) {
			//console.log('ajaxLoadTypeSpeciallCell load id=' + id + ' col=' + col);
			if (_popoverCellAjaxXhr) {
				_popoverCellAjaxXhr.abort();
			}

			var _popoverCellAjaxXhr = $.ajax({
				type: 'GET',
				url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=TYPESPECIALL_CELL&ID=' + id + '&col=' + col,
				dataType: 'json',
				contentType: "application/json; charset=utf-8",
				data: '',
				success: function(req){
					//console.log('ajaxLoadTypeSpeciallCell Data: ', req);
					if (req.data && req.data.tbl_id > 0) {
						var addHtml = '';
						for(var i in req.data.items){
							var url = 'index.php?MENU_INIT=VIEWTABLE_AJAX';
							url += '&ZASOB_ID=' + req.data.tbl_id;
							url += '&f_' + req.data.fld_name + '=' + req.data.items[i].id;
							url += '&_hash=' + Math.random().toString(36).substring(2);
							addHtml += '<a href="' + url + '">Wyszukaj ' + req.data.items[i].id + '</a>: ' + req.data.items[i].label;
							addHtml += '<br>';
						}
						_popoverCell.append(addHtml);
						jQuery('#popoverCellContent').append(addHtml);
					}
				}
			});

		};

		priv.popoverCell = function (e) {
			e.preventDefault();
			e.stopPropagation();
			if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
				var lastId = _popoverCell.data('rowid'),
					lastCol = _popoverCell.data('col');

				if (lastId == e.data.id && lastCol == e.data.col) {
					//_popoverCellCurrent.popover('toggle');
				}
				else {
					if (_popoverCellCurrent) {
						_popoverCellCurrent.popover('destroy');
					}

					_popoverCell.data('rowid', e.data.id);
					_popoverCell.data('col', e.data.col);
					_popoverCell.html(e.data.value + '<div id="popoverCellContent"></div>');
					if (_data.cols[e.data.col]) {
						if (_data.cols[e.data.col]._tsRetId > 0) {
							priv.ajaxLoadTypeSpeciallCell(e.data.id, e.data.col);
						}
					}

					_popoverCellCurrent = jQuery(e.currentTarget);
					// title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">&times;</button>'
					var opts = {
						placement: 'left'
						, trigger: 'click'
					//	, title: e.data.col + '<a href="#" class="icon-remove pull-right" onclick="return hidePopover();"></a>'
						, title: '<div style="display:block;position:relative;padding:0 20px 0 0;">' + (e.data.friendly || e.data.col) + ' <button type="button" class="close" onclick="return hidePopover();" style="position:absolute;right:0;top:0;">&times;</button>' + '</div>'
						, html: true
						, content: _popoverCell.html()
					}

					_popoverCellCurrent.popover(opts);
					_popoverCellCurrent.popover('show');
				}
			} else {
				console.log('NO data');
				return false;
			}
			return;
		};

		priv.routeChanged = function(e) {
			hash = e.data.hash || '';
			if (hash.length == 0) {
				return;
			}
			if (hash.substring(0, 1) != '#') {
				hash = '#' + hash;
			}
			location.hash = hash;
		},

		publ.init = function (options) {
			if (priv.options.debug) console.log('TableAjax initialization...');
			//merge supplied options with defaults
			$.extend(priv.options, defaults, options);
			priv.init();
			return publ;
		};

		publ.loadPage = function(page, pageSize) {
			var skipCols = true, // skipCols = true - prevent columns delete
				resetChecked = false;
			var reqData = {
				page: page,
				pageSize: (pageSize || priv.options.pageSize),
				currSortCol: (_currSortCol || ''),
				currSortFlip: _currSortFlip ? "desc" : "asc"
			};

			if (Object.keys(_filterCols).length > 0) {
				$.each(_filterCols, function (col, colProps) {
					if (colProps.filter && colProps.filter.length > 0) {
						reqData['f_' + col] = colProps.filter;
					}
				});
				skipCols = true;
			}

			// specialFilters
			$.each(_specialFilters, function(groupName, btnValue) {
				if (btnValue.length > 0) {
					reqData['sf_' + groupName] = btnValue;
				}
			});

			if (priv.options.forceFilterInit) {
				$.map(priv.options.forceFilterInit, function (fltrProps, fltr) {
					reqData['f_' + fltr] = fltrProps;
					filtersInitSet = true;
				});
			}

			_table.parent().parent().addClass('AjaxTable-loading');

			$.ajax({
				url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>',
				type: 'GET',
				dataType: 'json',
				contentType: "application/json; charset=utf-8",
				data: reqData,
				async: true,
				success: function (data) {
					if (data.d && data.d.cols)
						priv.setData(data.d, skipCols, resetChecked);
					else
						priv.setData(data, skipCols, resetChecked);
					if (typeof callback == "function")
						callback.call(this);
					_table.parent().parent().removeClass('AjaxTable-loading');
				},
				error: function (err) {
					//console.log('request error: {0}'.f(JSON.stringify(err)));
				}
			});
		};

		publ.getCurrentPage = function() {
			return _currPage;
		};

		publ.popoverCellRemove = function () {
			_popoverCellCurrent.popover('destroy');
			_popoverCell.data('rowid', -1);
			_popoverCell.data('col', -1);
			_popoverCell.html('');
		};

		return publ;
	}

	$.fn.TableAjax = function (options) {
		options = options || {};
		return this.each(function () {
			options.id = this;
			$(this).data('TableAjax', new TableAjax().init(options));
		});
	};

	$.fn.TableAjaxLoadPage = function (page, pageSize) {
		//console.log('TableAjaxLoadPage: ' + page + ' size: ' + pageSize);
		return this.each(function () {
			var tblAjax = jQuery(this).data('TableAjax');
			var curPage = page || tblAjax.getCurrentPage();
			if (tblAjax) tblAjax.loadPage(curPage, pageSize);
		});
	};

	String.prototype.format = String.prototype.f = function () {
		var s = this;
		i = arguments.length;
		while (i--) s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
		return s;
	};

})(jQuery);
		</script>
<?php
	$filterInit = $this->_filterInit;
	$forceFilterInit = $this->_forceFilterInit;
	$pageSizes = $this->_pageSizes;
	$rowFunctions = $this->_showRowFunctionsJson();
?>
		<script>
jQuery(document).ready(function(){
	jQuery('#<?php echo $this->_htmlID; ?>').TableAjax({
		url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>',
		columnPicker: true,
		filter: true,
		filterInit: <?php echo json_encode($filterInit); ?>,
		forceFilterInit: <?php echo json_encode($forceFilterInit); ?>,
		debug: false, // TODO: DBG
		height: 400, // TODO: ?
		sorting: true, // TODO: ?
		paging: true, // TODO: ?
		pageSizes: <?php echo json_encode($pageSizes); ?>,
		pageChanged: function(args) {
			var con = jQuery('#<?php echo $this->_htmlID; ?>');
			con.TableAjaxLoadPage(args.page);
		},
		pageSizeChanged: function(args) {
			var con = jQuery('#<?php echo $this->_htmlID; ?>');
			con.TableAjaxLoadPage(0, args.pageSize);
		},
		tblFunctions: {
			shortdesc: {
				icon: 'align-left',
				title: 'Long desc',
				method: 'longTextChanged'
			},
			create: {
				href: '#CREATE',
				icon: 'plus',
				title: 'Dodaj nowy rekord'
			}
		},
		rowFunctions: <?php echo json_encode($rowFunctions); ?>,
		specialFilterFunctions: <?php
			$fltrs = $this->_dataSource->getSpecialFilters();
			if (!empty($fltrs)) {
				echo json_encode($fltrs);
			} else {
				echo 'false';
			}
			echo ',';
		?>
		router: function () {
			var routes = {
				EDIT: function (args) {
					var recordID = args;
					if (typeof args == 'object') {
						recordID = args.shift();
						recordID = parseInt(recordID);
					}
					if (typeof recordID !== 'number' || recordID <= 0) {
						// TODO: msg
						return false;
					}
					var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
					cont.hide();

					// remove previous task content
					var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
					taskCnt.parent().remove();
					taskCnt.remove();

					var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
					jQuery('<ul class="breadcrumb">' +
						'<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a> <span class="divider">/</span></li>' +
						'<li class="active">Edytuj rekord</li>' +
					'</ul>').appendTo(taskCont);
					taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
					jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);

					jQuery.ajax({
						url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT&ID=' + recordID,
						type: 'GET',
						dataType: 'text',
						data: '',
						async: true,
						success: function (data) {
							taskCnt.removeClass('AjaxTable-loading');
							//console.log('request finished L.<?php echo __LINE__; ?>');
							jQuery(data).appendTo(taskCnt);

							taskCnt.find('.se_type-date').datepicker({
								format: "yyyy-mm-dd"
								, language: 'pl'
								, todayBtn: "linked"
							});
							taskCnt.find('.se_type-datetime').parent().datetimepicker({
								language: 'pl'
								, format: 'yyyy-MM-dd hh:mm'
								, weekStart: 1
							});

						},
						error: function (err) {
							taskCnt.removeClass('AjaxTable-loading');
							//console.log('request error: {0}'.f(err));
						}
					});

					//return false;
				},
				HIST: function (args) {
					var recordID = args;
					if (typeof args == 'object') {
						recordID = args.shift();
						recordID = parseInt(recordID);
					}
					if (typeof recordID !== 'number' || recordID <= 0) {
						// TODO: msg
						return false;
					}
					var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
					cont.hide();

					// remove previous task content
					var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
					taskCnt.parent().remove();
					taskCnt.remove();

					var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
					jQuery('<ul class="breadcrumb">' +
						'<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a> <span class="divider">/</span></li>' +
						'<li class="active">Historia rekordu</li>' +
					'</ul>').appendTo(taskCont);
					var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
					jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);

					jQuery.ajax({
						url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIST&ID=' + recordID,
						type: 'GET',
						dataType: 'text',
						data: '',
						async: true,
						success: function (data) {
							taskCnt.removeClass('AjaxTable-loading');
							//console.log('request finished L.<?php echo __LINE__; ?>');
							jQuery(data).appendTo(taskCnt);
						},
						error: function (err) {
							taskCnt.removeClass('AjaxTable-loading');
							//console.log('request error: {0}'.f(err));
						}
					});
					//return false;
				},
				FILES: function tableAjaxFiles(args) {
					var recordID = args;
					if (typeof args == 'object') {
						recordID = args.shift();
						recordID = parseInt(recordID);
					}
					if (typeof recordID !== 'number' || recordID <= 0) {
						// TODO: msg
						return false;
					}
					var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
					cont.hide();

					// remove previous task content
					var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
					taskCnt.parent().remove();
					taskCnt.remove();

					var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
					jQuery('<ul class="breadcrumb">' +
						'<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a> <span class="divider">/</span></li>' +
						'<li class="active">Pliki</li>' +
					'</ul>').appendTo(taskCont);
					var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTable-loading"></div>').appendTo(taskCont);
					jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);

					jQuery.ajax({
						url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES&ID=' + recordID,
						type: 'GET',
						dataType: 'text',
						data: '',
						async: true,
						success: function (data) {
							taskCnt.removeClass('AjaxTable-loading');
							//console.log('request finished L.<?php echo __LINE__; ?>', data);
							jQuery(data).appendTo(taskCnt);
						},
						error: function (jqXHR, textStatus, errorThrown) {
							//console.log('request error:', jqXHR.status, 'txt:', jqXHR.responseText, 'err:', jqXHR);
							taskCnt.removeClass('AjaxTable-loading');
							var txt = jqXHR.responseText || 'Error';
							if (jqXHR.status == 404) {
								jQuery('<div class="container"><div class="alert alert-error">' + txt + '</div></div>').appendTo(taskCnt);
							} else {
								jQuery('<div class="container"><div class="alert alert-error">' + txt + '</div></div>').appendTo(taskCnt);
							}
						}
					});
					//return false;
				},
				CREATE: function tableAjaxCreate() {
					var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
					cont.hide();

					// remove previous task content
					var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
					taskCnt.parent().remove();
					taskCnt.remove();

					var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
					jQuery('<ul class="breadcrumb">' +
						'<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a> <span class="divider">/</span></li>' +
						'<li class="active">Dodaj nowy rekord</li>' +
					'</ul>').appendTo(taskCont);
					taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
					jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);

					var reqData = {};
					var forceFilterInit = <?php echo json_encode($forceFilterInit);// TODO: read from TableAjax ?>;
					if (forceFilterInit) {
						$.map(forceFilterInit, function (fltrProps, fltr) {
							reqData['ff_' + fltr] = fltrProps;
						});
					}

					jQuery.ajax({
						url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE',
						type: 'GET',
						dataType: 'text',
						data: reqData,
						async: true,
						success: function (data) {
							taskCnt.removeClass('AjaxTable-loading');
							//console.log('request finished L.<?php echo __LINE__; ?>');
							jQuery(data).appendTo(taskCnt);

							taskCnt.find('.se_type-date').datepicker({
								format: "yyyy-mm-dd"
								, language: 'pl'
								, todayBtn: "linked"
							});
							taskCnt.find('.se_type-datetime').parent().datetimepicker({
								language: 'pl'
								, format: 'yyyy-MM-dd hh:mm'
								, weekStart: 1
							});
						},
						error: function (err) {
							taskCnt.removeClass('AjaxTable-loading');
							//console.log('request error: {0}'.f(err));
						}
					});
					//return false;
				}
			};
			var routePath = location.hash;
			//console.log('location.hash: ' + routePath);
			if (location.hash == '' || location.hash == '#') {
				return false;
			}
			if (routePath.charAt(0) == '#') {
				routePath = routePath.substr(1);
			}
			//console.log('routePath: ' + routePath);
			var parts = routePath.split('/');
			var task = parts.shift();
			//console.log('task(' + task + ') parts:');
			//console.log(parts);
			if (task in routes && typeof routes[task] == 'function') {
				routes[task](parts);
			} else {
				return false;
			}
		},
		filtersClean: true,
		longDesc: true
	});
});

function tableAjaxBackToTable() {
	var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
	cont.show();
	var taskCont = jQuery('#<?php echo $this->_htmlID . '_task'; ?>').parent();
	taskCont.remove();

	// reload first page
	var con = jQuery('#<?php echo $this->_htmlID; ?>');
	con.TableAjaxLoadPage(0);// TODO: load current page
}

function tableAjaxCopy(args) {
	var recordID = args;
	if (typeof args == 'object') {
		recordID = args.shift();
		recordID = parseInt(recordID);
	}
	if (typeof recordID !== 'number' || recordID <= 0) {
		// TODO: msg
		return false;
	}

	if (!confirm('Czy na pewno chcesz utworzyc nowy rekord na podstawie danych z rekordu ID = ' + recordID + '?')) {
		return false;
	}

	var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
	//cont.hide();
	//var taskCont = jQuery('#<?php echo $this->_htmlID . '_task'; ?>').parent();
	//taskCont.remove();

	cont.children('.alert').fadeOut('slow');
	var alert = jQuery('<div class="alert fade in"><strong>Kopiuj rekord</strong> ... </div>').prependTo(cont);

	jQuery.ajax({
		url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=COPY&ID=' + recordID,
		type: 'GET',
		dataType: 'text',
		data: '',
		async: true,
		success: function (data) {
			//console.log('data: ', data);
			alert.remove();
			alert = jQuery(data).prependTo(cont);
			alert.alert();
			var con = jQuery('#<?php echo $this->_htmlID; ?>');
			con.TableAjaxLoadPage(0);
		},
		error: function (err) {
			alert.remove();
			console.log(err);
		}
	});

	return false;
}

function hidePopover() {
	var con = jQuery('#<?php echo $this->_htmlID; ?>');
	if (con) {
		var tblAjax = con.data('TableAjax');
		if (tblAjax) {
			tblAjax.popoverCellRemove();
		}
	}
	return false;
}
		</script>
		<?php
		$out = ob_get_contents();
		ob_end_clean();
		return $out;
	}

	public function ajaxTask($task) {
		switch ($task) {
			case 'EDIT': {
				$id = V::get('ID', 0, $_REQUEST, 'int');
				if ($id > 0) {
					$this->sendAjaxEdit($id, $_REQUEST);
				} else {
					echo '404';
				}
				break;
			}
			case 'EDIT_SAVE': {
				$id = V::get('ID', 0, $_REQUEST, 'int');
				if ($id > 0) {
					$this->sendAjaxEditSave($id, $_REQUEST);
				} else {
					echo '404';
				}
				break;
			}
			case 'EDIT_INLINE': {
				$id = V::get('ID', 0, $_REQUEST, 'int');
				$col = V::get('col', '', $_REQUEST);
				if ($id > 0 && !empty($col)) {
					$this->sendAjaxEditInline($id, $col, $_REQUEST);
				} else {
					echo '404';
				}
				break;
			}
			case 'EDIT_INLINE_SAVE': {
				$id = V::get('ID', 0, $_REQUEST, 'int');
				$col = V::get('col', '', $_REQUEST);
				if ($id > 0 && !empty($col)) {
					$this->sendAjaxEditInlineSave($id, $col, $_REQUEST);
				} else {
					echo '404';
				}
				break;
			}
			case 'COPY': {
				$id = V::get('ID', 0, $_REQUEST, 'int');
				if ($id > 0) {
					$this->sendAjaxCopy($id, $_REQUEST);
				} else {
					echo '404';
				}
				break;
			}
			case 'CREATE': {
				$this->sendAjaxCreate($_REQUEST);
				break;
			}
			case 'CREATE_SAVE': {
				$this->sendAjaxCreateSave($_REQUEST);
				break;
			}
			case 'HIST': {
				$id = V::get('ID', 0, $_REQUEST, 'int');
				if ($id > 0) {
					$this->sendAjaxHistory($id, $_REQUEST);
				} else {
					echo '404';
				}
				break;
			}
			case 'FILES': {
				$id = V::get('ID', 0, $_REQUEST, 'int');
				if ($id > 0) {
					$this->sendAjaxFiles($id, $_REQUEST);
				} else {
					echo '404';
				}
				break;
			}
			case 'FILES_UPLOAD': {
				$id = V::get('ID', 0, $_REQUEST, 'int');
				if ($id > 0) {
					$this->sendAjaxFilesUpload($id, $_REQUEST);
				} else {
					echo '404';
				}
				break;
			}
			case 'FILES_LIST': {
				$id = V::get('ID', 0, $_REQUEST, 'int');
				if ($id > 0) {
					$this->sendAjaxFilesList($id, $_REQUEST);
				} else {
					echo '404';
				}
				break;
			}
			case 'FILE_REMOVE': {
				$id = V::get('ID', 0, $_REQUEST, 'int');
				if ($id > 0) {
					$this->sendAjaxFileRemove($id, $_REQUEST);
				} else {
					echo '404';
				}
				break;
			}
			case 'FILES_CONN_TBL_LIST': {
				$id = V::get('ID', 0, $_REQUEST, 'int');
				if ($id > 0) {
					$this->sendAjaxFilesConnTblList($id, $_REQUEST);
				} else {
					echo '404';
				}
				break;
			}
			case 'TYPESPECIAL': {
				$fldID = V::get('fldID', 0, $_REQUEST, 'int');
				if ($fldID > 0) {
					$this->sendTypeSpecial($fldID, $_REQUEST);
				} else {
					echo '404';
				}
				break;
			}
			case 'TYPESPECIALL_CELL': {
				$id = V::get('ID', 0, $_REQUEST, 'int');
				$col = V::get('col', '', $_REQUEST);
				if ($id > 0 && !empty($col)) {
					$this->sendTypeSpecialCell($id, $col, $_REQUEST);
				} else {
					echo '404';
				}
				break;
			}
			case 'HIDDEN_COLS_SAVE': {
				$this->sendHiddenColsSave($_REQUEST);
				break;
			}
			default:
				$this->sendAjaxData($_REQUEST);
		}
	}

	/**
	 * ajax url: &_task=EDIT_INLINE
	 * @param $rowID - $_GET['ID']
	 * @param $fieldName - $_GET['col']
	 */
	private function sendAjaxEditInline($rowID, $fieldName, $args) {
		$DBG = ('1' == V::get('DBG', '', $_REQUEST));
		header("Content-type: text/plain");

		$fieldID = $this->_acl->getFieldIdByName($fieldName);
		if (!$fieldID) {
			echo "404: No field by name ({$fieldName})";
			exit;
		}

		if ($DBG) echo "fieldID: {$fieldID}\n";

		$row = $this->_dataSource->getItem($rowID);
		if (!$row) {
			echo "404: No item ID({$rowID})";
			exit;
		}

		if (!$this->_acl->isAllowed($fieldID, 'R', $row)) {
			if ($DBG) echo " R not allowed\n";
		} else {
			if ($DBG) echo " R allowed\n";
		}

		if (!$this->_acl->isAllowed($fieldID, 'W', $row)) {
			if ($DBG) echo " W not allowed\n";
		} else {
			if ($DBG) echo " W allowed\n";
		}

		$fieldVal = '';
		if ($this->_acl->isAllowed($fieldID, 'R', $row)) {
			$fieldVal = V::get($fieldName, $fieldVal, $row);
		} else {
			$fieldVal = '*****';
		}

		$fieldVal = V::get("f{$fieldID}", $fieldVal, $_POST);

		$vCol = $this->_acl->getField($fieldID);
		$vCol['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];

		$tsValues = array();
		Lib::loadClass('Typespecial');
		$typeSpecial = Typespecial::getInstance($fieldID, $vCol['name']);
		if ($typeSpecial) {
			if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$fieldID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
			$specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $row->ID, $fieldName, V::get($fieldName, $fieldVal, $row));
			if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$fieldID.') specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValues);echo'</pre>';}
			if (!empty($specialValues)) {
				$tsValues[$row->ID] = implode('<br>', $specialValues);
			}
		}

		Lib::loadClass('SE_Layout');
		?>
		<label for="<?php echo "f{$fieldID}"; ?>" class="AjaxTableEdit-label">
			<strong title="<?php echo "[{$fieldID}] {$fieldName}"; ?>"><?php echo "{$vCol['label']}"; ?></strong>
			<?php if (!empty($vCol['opis'])) : ?>
				<em><?php echo $vCol['opis']; ?></em>
				<?php $perms = $this->_acl->getFieldPerms($fieldID); SE_Layout::hotKeyDBG($perms); ?>
			<?php endif; ?>
		</label>
		<?php
			$fieldParams = array('widthClass'=>'inside-modal', 'maxGrid'=>6);
			if (!empty($tsValues[$row->ID])) {
				$fieldParams['typespecialValue'] = $tsValues[$row->ID];
			}
			$vDefault = $this->_dataSource->getColDefault($fieldName);
			if (!empty($vDefault)) {
				$fieldParams['default'] = $vDefault;
			}
			echo $this->_acl->showFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $row);
			if ($typeSpecial) {
				echo '<p style="padding:100px 0;"></p>';
			}
		exit;
	}

	private function sendAjaxEditInlineSave($rowID, $fieldName, $args) {
		$DBG = ('1' == V::get('DBG', '', $_REQUEST));
		sleep(1);// TODO: RMME DBG loading

		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">TODO: save ID(' . $id . ') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($args);echo'</pre>';}
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">acl (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_acl);echo'</pre>';}
		$dbID = $this->_acl->getDB();
		$db = DB::getDB($dbID);

		if (!$db) {
			header('HTTP/1.0 406 Not Acceptable');
			exit;
		}

		$tblName = $this->_acl->getName();

		$fieldID = $this->_acl->getFieldIdByName($fieldName);
		if (!$fieldID) {
			header('HTTP/1.0 404 Not Found');
			echo "404: No field by name ({$fieldName})";
			exit;
		}

		$row = $this->_dataSource->getItem($rowID);
		if (!$row) {
			header('HTTP/1.0 404 Not Found');
			echo "404: No item ID({$rowID})";
			exit;
		}

		if (!$this->_acl->isAllowed($fieldID, 'W', $row)) {
			header('HTTP/1.0 403 Forbidden');
			echo "403: field not allowed to Write ({$fieldName})";
			exit;
		} else {
			if ($DBG) echo " Write allowed\n";
		}

		$sqlObj = new stdClass();
		if (array_key_exists("f{$fieldID}", $args)) {
			if (!$this->_acl->isAllowed($fieldID, 'R', $record) && '*****' == $args["f{$fieldID}"]) {
				// default value for perms 'W' without 'R' is '*****'
			}
			else {
				$sqlObj->{$fieldName} = $args["f{$fieldID}"];

				if (empty($args["f{$fieldID}"]) && strlen($args["f{$fieldID}"]) == 0) {// fix bug in input type date and value="0000-00-00"
					$sqlObj->{$fieldName} = $this->_acl->fixEmptyValueFromUser($fieldID);
				}
			}
		}
		else {
			if ($DBG) echo " TODO: field value not set\n";
		}
		$sqlObj->ID = $rowID;
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">E('.$tblName.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sqlObj);echo'</pre>';}

		$ret = $db->UPDATE_OBJ($tblName, $sqlObj);
		if ($ret > 0) {
			echo '<div class="alert alert-success">';
				echo "Rekord zapisany pomyślnie";//"Record saved successfully";
			echo '</div>';
		} else if ($ret == 0) {
			echo '<div class="alert alert-info">';
				echo "Nie wprowadzono żadnych zmian";
				if ($db->has_errors()) {
					//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">db errors: (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($db->get_errors());echo'</pre>';
				}
			echo '</div>';
		} else {
			echo '<div class="alert alert-error">';
				echo '<h4>' . "Wystąpiły błędy!" . '</h4>';
				if ($db->has_errors()) {
					$errors = $db->get_errors();
					echo implode('<br>', $errors);
				}
			echo '</div>';
		}

		exit;
	}

	private function sendAjaxEdit($id, $args) {
		header("Content-type: text/plain");
		$DBG = ('1' == V::get('DBG', '', $_REQUEST));

		$cols = array();

		$record = $this->_dataSource->getItem($id);
		if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
			echo '<div class="alert alert-error">';
				echo "Brak dostępu do rekordu";// TODO: more info - reason
			echo '</div>';
			return;
		}

		$fieldsList = $this->_acl->getFields();
		foreach ($fieldsList as $kID => $vCol) {
			if ($vCol['name'] == 'ID') {
				unset($fieldsList[$kID]);
				continue;
			}
			$cols[$kID] = '';
			if ($this->_acl->isAllowed($kID, 'R', $record)) {
				$cols[$kID] = V::get($vCol['name'], '', $record);
			} else {
				$cols[$kID] = '*****';
			}
			$cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);

			$fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : str_replace('_', ' ', $vCol['name']);
		}

		$tsValues = array();
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fieldsList (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($fieldsList);echo'</pre>';}
		if (!empty($fieldsList)) {
			Lib::loadClass('Typespecial');
			foreach ($fieldsList as $vColID => $vCol) {
				$typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
				if ($typeSpecial) {
					if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vColID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
					$colValue = V::get($vCol['name'], '', $record);
					if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">V::get('.$vCol['name'].', "", $record) (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($colValue);echo'</pre>';}
					$specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $record->ID, $vCol['name'], $colValue);
					if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vColID.') specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValues);echo'</pre>';}
					if (!empty($specialValues)) {
						$tsValues[$vColID] = implode('<br>', $specialValues);
					}
				}
			}
		}
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">tsValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($tsValues);echo'</pre>';}

		$rowFunctionsOut = $this->_showRowFunctions($record->ID, array('edit', 'cp'), true);

		Lib::loadClass('SE_Layout');
		?>
		<div class="container AjaxFrmHorizontalEdit">
		<form class="form-horizontal" action="" method="post" id="EDIT_FRM_<?php echo $this->_htmlID; ?>">
			<fieldset>
				<legend>Edycja rekordu Nr <?php echo $record->ID; ?><span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span></legend>

				<?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
					<?php if ($this->_acl->isAllowed($kID, 'W', $record)) : ?>
						<div class="control-group">
							<label class="control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
								<i class="icon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars($vCol['opis']); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
								<?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
							</label>
							<div class="controls">
								<?php
									$fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
									if (!empty($tsValues[$kID])) {
										$fieldParams['typespecialValue'] = $tsValues[$kID];
									}
									echo $this->_acl->showFormItem('W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record);
								?>
							</div>
						</div>
					<?php elseif ($this->_acl->isAllowed($kID, 'R', $record)) : ?>
						<div class="control-group">
							<label class="control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
								<i class="icon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars($vCol['opis']); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
								<?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
							</label>
							<div class="controls">
								<p style="margin-top:5px;">
								<?php
									//echo $this->_acl->showFormItem('R', $kID, "f{$kID}", $cols[$kID], array('appendBack'=>true), $record);
									if (!empty($tsValues[$kID])) {
										echo $tsValues[$kID];
									} else if (!empty($record->{$vCol['name']})) {
										echo $record->{$vCol['name']};
									}
								?>
								</p>
							</div>
						</div>
					<?php endif; ?>
				<?php endforeach; ?>

				<div class="control-group">
					<div class="controls">
						<button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Zapisz</button>
					</div>
				</div>

			</fieldset>
		</form>
		<p style="padding:100px 0;"></p>
		</div>
<script>
jQuery(document).ready(function(){
	jQuery('textarea').autosize();

	jQuery('.frm-help').popover({trigger:'hover'});

	jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
		var data = jQuery(this).serialize();

		// TODO: change Edit btn to return to edit record with fields -> show form

		var taskCont = jQuery('#<?php echo $this->_htmlID; ?>_task').parent();
		//taskCont.empty();
		taskCont.children().fadeOut('slow');
		var alertCntWrap = jQuery('<div class="AjaxTableAlert AjaxTable-loading"></div>').prependTo(taskCont)
			, alertCnt = jQuery('<div class="container"></div>').prependTo(alertCntWrap);
		jQuery('<div class="alert alert-error"><div style="padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;"> zapisywanie ... </div></div>').appendTo(alertCnt);

		jQuery.ajax({
			url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT_SAVE&ID=<?php echo $record->ID; ?>',
			type: 'POST',
			dataType: 'text',
			data: data,
			async: true,
			success: function (data) {
				alertCntWrap.removeClass('AjaxTable-loading');
				//console.log('request finished L.<?php echo __LINE__; ?>');
				alertCnt.empty();
				var out = '';
				out += data;
				out += '<div class="breadcrumb">' +
						' <a href="#" onclick="return tableAjaxBackToTable();" class="btn btn-link btn-small"> <i class="icon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>' +
						'<span class="divider">/</span>' +
						' <a href="#EDIT/<?php echo $id; ?>/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-small"> <i class="icon-pencil"></i> Edytuj rekord <?php echo $id; ?></a>' +
					'</div>';
				jQuery(out).appendTo(alertCnt);
			},
			error: function (jhr, textStatus, errorThrown) {
				var errorTxt = jhr.responseText || 'Error';
				alertCntWrap.removeClass('AjaxTable-loading');
				//console.log('Request Error: {0}: {1}'.f(textStatus, errorThrown));
				alertCnt.empty();
				jQuery(errorTxt).appendTo(alertCnt);
				var errLinks = jQuery('<div class="breadcrumb"></div>').appendTo(alertCnt);
				jQuery('<a href="#" onclick="return tableAjaxBackToTable();"> <i class="icon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>').appendTo(errLinks);
				var backToEditBtn = jQuery('<a href="#EDIT/<?php echo $id; ?>/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-small"> <i class="icon-pencil"></i> Popraw dane <?php echo $id; ?></a>').appendTo(errLinks);
				backToEditBtn.on('click', function(){
					alertCnt.remove();
					taskCont.children().fadeIn('slow');
					return false;
				});
			}
		});

		return false;
	});

	jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value input').on('input', function(e) {
		var input, btn;
		input = jQuery(e.target);
		btn = input.next();
		if (btn.is('button')) {
			if (btn.attr('title') != input.val()) {
				btn.show();
			} else {
				btn.hide();
			}
		}
	});
	jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value button.btn-appendBack').on('click', function(e) {
		var input, btn;
		btn = jQuery(e.target);
		input = btn.prev();
		if (input.is('input')) {
			if (btn.attr('title') != input.val()) {
				input.val(btn.attr('title'));
				btn.hide();
			}
		}
	});
});
</script>
		<?php
		exit;
	}

	private function sendAjaxEditSave($id, $args) {
		$DBG = ('1' == V::get('DBG', '', $_REQUEST));
		sleep(1);// TODO: RMME DBG loading

		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">TODO: save ID(' . $id . ') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($args);echo'</pre>';}
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">acl (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_acl);echo'</pre>';}
		$dbID = $this->_acl->getDB();
		$db = DB::getDB($dbID);

		if (!$db) {
			header('HTTP/1.0 406 Not Acceptable');
			exit;
		}

		$tblName = $this->_acl->getName();

		$record = $db->get_by_id($tblName, $id);
		if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
			echo '<div class="alert alert-error">';
				echo "Brak dostępu do rekordu";// TODO: more info - reason
			echo '</div>';
		}

		$sqlObj = new stdClass();
		$fields = $this->_acl->getFields();
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fields (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($fields);echo'</pre>';}
		foreach ($fields as $kID => $vField) {
			if (!$this->_acl->isAllowed($kID, 'W', $record)) {
				continue;
			}
			if (array_key_exists("f{$kID}", $args)) {
				if (!$this->_acl->isAllowed($kID, 'R', $record) && '*****' == $args["f{$kID}"]) {
					// default value for perms 'W' without 'R' is '*****'
				}
				else {
					$sqlObj->{$vField['name']} = $args["f{$kID}"];

					if (empty($args["f{$kID}"]) && strlen($args["f{$kID}"]) == 0) {// fix bug in input type date and value="0000-00-00"
						$sqlObj->{$vField['name']} = $this->_acl->fixEmptyValueFromUser($kID);
					}
				}
			}
		}
		$sqlObj->ID = $id;
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sqlObj);echo'</pre>';}

		$ret = $db->UPDATE_OBJ($tblName, $sqlObj);

		if ($ret > 0) {
			echo '<div class="alert alert-success">';
				echo "Rekord zapisany pomyślnie";//"Record saved successfully";
			echo '</div>';
		} else if ($ret == 0) {
			echo '<div class="alert alert-info">';
				echo "Nie wprowadzono żadnych zmian";
			echo '</div>';
		} else {
			header('HTTP/1.0 404 Not Found');
			echo '<div class="alert alert-error">';
				echo '<h4>' . "Wystąpiły błędy!" . '</h4>';
				if ($db->has_errors()) {
					$errors = $db->get_errors();
					echo implode('<br>', $errors);
				}
			echo '</div>';
		}

		exit;
	}

	private function sendAjaxCreate($args) {
		header("Content-type: text/plain");
		$DBG = ('1' == V::get('DBG', '', $_REQUEST));

		$cols = array();
		$forceFilterInit = array();
		foreach ($_GET as $k => $v) {
			if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
				$fldName = substr($k, 3);
				$forceFilterInit[$fldName] = $v;
			}
		}

		$fieldsList = $this->_acl->getFields();
		foreach ($fieldsList as $kID => $vCol) {
			$defaultValue = '';
			if ($vCol['name'] == 'ID') {
				unset($fieldsList[$kID]);
				continue;
			}

			if (!empty($forceFilterInit[$vCol['name']])) {
				$defaultValue = $forceFilterInit[$vCol['name']];
			}

			// TODO: read from session cache
			$cols[$kID] = V::get("f{$kID}", $defaultValue, $_POST);

			$fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
		}

		Lib::loadClass('SE_Layout');
		?>
		<div class="container AjaxFrmHorizontalEdit">
		<form class="form-horizontal" action="" method="post" id="CREATE_FRM_<?php echo $this->_htmlID; ?>">
			<fieldset>
				<legend>Dodaj nowy rekord</legend>


				<?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
					<?php if ($this->_acl->isAllowed($kID, 'C')) : ?>
						<div class="control-group">
							<label class="control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
								<i class="icon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars($vCol['opis']); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
								<?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
							</label>
							<div class="controls">
								<?php
									$fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
									echo $this->_acl->showFormItem('C', $kID, "f{$kID}", $cols[$kID], $fieldParams);
								?>
							</div>
						</div>
					<?php endif; ?>
				<?php endforeach; ?>

				<div class="control-group">
					<div class="controls">
						<button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Dodaj rekord</button>
					</div>
				</div>

			</fieldset>
		</form>
		</div>

<script>
jQuery(document).ready(function(){
	jQuery('textarea').autosize();

	jQuery('.frm-help').popover({trigger:'hover'});

	jQuery('#CREATE_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
		var data = jQuery(this).serialize();

		var taskContLast = jQuery('#<?php echo $this->_htmlID; ?>_task'),
			taskCont = taskContLast.parent();
		taskContLast.fadeOut('slow');
		var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
		jQuery('<div class="alert alert-error"><div style="padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;"> save ... </div></div>').appendTo(taskCnt);

		jQuery.ajax({
			url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE_SAVE',
			type: 'POST',
			dataType: 'json',
			data: data,
			async: true,
			success: function(data) {
				//console.log('success L.<?php echo __LINE__; ?> data', data);
			},
			error: function(xhr) {
				//console.log('error L.<?php echo __LINE__; ?> xhr', xhr);
			},
			complete: function(xhr) {
				if (xhr.responseJSON) {
					var data = xhr.responseJSON;
				} else {
					// TODO: error
				}

				taskCnt.removeClass('AjaxTable-loading');
				taskCnt.empty();
				if (typeof data == 'object') {
					if (data.type == 'ERROR') {
						var out = '<div class="container">' + 
								'<div class="alert alert-error">' +
									'<h4>Wystąpiły błędy!</h4>' + data.msg +
								'</div>';
						out += '<div class="breadcrumb">' +
									' <a class="create-fix" href="#CREATE/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-small"> <i class="icon-arrow-left"></i> Wróć do formularza i popraw dane</a></li>' +
								'</div>' +
							'</div>';
						jQuery(out).appendTo(taskCnt);
						var taskContLastNode = taskContLast
							, taskCntNode = taskCnt;
						taskCnt.find('.create-fix').click(function(){
							taskCntNode.remove();
							taskContLastNode.fadeIn('slow');
							return false;
						});
					}
					else if (data.type == 'SUCCESS') {
						var msg = '';
						if (data.id && data.id > 0) {
							msg = 'Utworzono pomyślnie rekord: ID = ' + data.id;
						} else if (data.msg) {
							msg = data.msg;
						} else {
							msg = 'OK';
						}
						var out = '<div class="container">';
						out += '<div class="alert alert-success">' + msg + '</div>';
						out += '<div class="breadcrumb">' +
								' <a href="#" onclick="return tableAjaxBackToTable();" class="btn btn-link btn-small"> <i class="icon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>' +
								'<span class="divider">/</span>' +
								' <a href="#EDIT/' + data.id + '" class="btn btn-link btn-small"> <i class="icon-pencil"></i> Edytuj rekord ' + data.id + '</a>' +
								'<span class="divider">/</span>' +
								' <a href="#CREATE/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-small"> <i class="icon-plus"></i> Dodaj nowy rekord</a></li>' +
							'</div>';
						out += '</div>';
						jQuery(out).appendTo(taskCnt);
					}
				}
			}
		});

		return false;
	});
});
</script>
		<?php
		exit;
	}

	private function sendAjaxCreateSave($args) {
		header("Content-type: application/json");
		$DBG = ('1' == V::get('DBG', '', $_REQUEST));
		sleep(1);// TODO: RMME DBG loading

		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">TODO: save ID(' . $id . ') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($args);echo'</pre>';}
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">acl (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_acl);echo'</pre>';}
		$dbID = $this->_acl->getDB();
		$db = DB::getDB($dbID);

		if (!$db) {
			header('HTTP/1.0 406 Not Acceptable');
			echo '{"type":"ERROR", "msg": "' . "Błąd połączenia z bazą danych!" . '"}';
			exit;
		}

		$tblName = $this->_acl->getName();

		$sqlObj = new stdClass();
		$fields = $this->_acl->getFields();
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fields (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($fields);echo'</pre>';}
		foreach ($fields as $kID => $vField) {
			if (!$this->_acl->isAllowed($kID, 'C')) {
				continue;
			}
			if (array_key_exists("f{$kID}", $args)) {
				$sqlObj->{$vField['name']} = $args["f{$kID}"];

				if (empty($args["f{$kID}"]) && strlen($args["f{$kID}"]) == 0) {// fix bug in input type date and value="0000-00-00"
					$sqlObj->{$vField['name']} = $this->_acl->fixEmptyValueFromUser($kID);
				}
			}
		}
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sqlObj);echo'</pre>';}

		$retID = $db->ADD_NEW_OBJ($tblName, $sqlObj);

		$retJson = new stdClass();
		$retJson->type = '';
		$retJson->msg = '';

		if ($retID > 0) {
			$retJson->type = 'SUCCESS';
			$retJson->msg = "Utworzono pomyślnie rekord: ID = {$retID}";
			$retJson->id = $retID;
		} else {
			header('HTTP/1.0 404 Not Found');
			$retJson->type = 'ERROR';
			$retJson->msg = "";
			if ($db->has_errors()) {
				$outArr = array();
				$errorsSql = $db->get_errors();
				foreach ($errorsSql as $vErr) {
					if (substr($vErr, 0, 18) == 'SQL QUERY FAILED: ') {
						$vErr = substr($vErr, 18);
						// Duplicate entry '123456-1' for key 'P_NIP'
						if (substr($vErr, 0, 16) == 'Duplicate entry ') {
						}
					}
					$outArr[] = $vErr;
				}
				$retJson->msg .= implode('<br>', $outArr);
			}
		}

		echo json_encode($retJson);
		exit;
	}

	private function sendAjaxCopy($id, $args) {
		header("Content-type: text/plain");
		sleep(1);// TODO: RMME DBG loading

		$dbID = $this->_acl->getDB();
		$db = DB::getDB($dbID);
		if (!$db) {
			header('HTTP/1.0 406 Not Acceptable');
			exit;
		}

		$row = $this->_dataSource->getItem($id);
		if (!$row) {
			header('HTTP/1.0 404 Not Found');
			echo "404: No item ID({$rowID})";
			exit;
		}

		$tblName = $this->_acl->getName();
		$types = $this->_acl->getTypes();
		$uniqKeys = $this->_acl->getUniqueKeys();

		$sqlObj = new stdClass();
		foreach ($types as $kName => $vType) {
			if ($kName == 'ID') {
				continue;
			} else if (in_array($kName, array('A_RECORD_UPDATE_AUTHOR','A_RECORD_UPDATE_DATE'))) {
				continue;
			}
			$sqlObj->{$kName} = V::get($kName, '', $row);
			if (in_array($kName, $uniqKeys)) {
				$sqlObj->{$kName} .= '?';
			}
		}

		$ret = $db->ADD_NEW_OBJ($tblName, $sqlObj);

		if ($ret > 0) {
			echo '<div class="alert alert-success">';
				echo '<button type="button" class="close" data-dismiss="alert"><i class="icon-remove"></i></button>';
				echo "Rekord skopiowany pomyślnie - utworzono rekord nr {$ret}";//"Record saved successfully";
			echo '</div>';
		} else if ($ret == 0) {
			echo '<div class="alert alert-error">';
				echo '<button type="button" class="close" data-dismiss="alert"><i class="icon-remove"></i></button>';
				echo "Nie udało się skopiować rekordu";
				if ($db->has_errors()) {
					echo '<br>' . implode("<br>", $db->get_errors());
				}
			echo '</div>';
		} else {
			echo '<div class="alert alert-error">';
				echo '<button type="button" class="close" data-dismiss="alert"><i class="icon-remove"></i></button>';
				echo "Błąd bazy danych";
			echo '</div>';
		}

		exit;
	}

	private function sendAjaxHistory($id, $args) {
		header("Content-type: text/plain");

		$record = $this->_dataSource->getItem($id);
		if (!$record) {
			header('HTTP/1.0 404 Not Found');
			echo "404: No item ID({$rowID})";
			exit;
		}

		$visibleCols = $this->_acl->getRealFieldList();
		$rowsHist = $this->_dataSource->getHistItems($id);

		$rowFunctionsOut = $this->_showRowFunctions($record->ID, array('hist', 'cp'), true);

		foreach ($rowsHist as $k => $row) {
			$row->_author = $row->A_RECORD_UPDATE_AUTHOR;
			$row->_created = $row->A_RECORD_UPDATE_DATE;

			if (!$row->_author || $row->_author == 'N/S;') {
				$row->_author = $row->A_RECORD_CREATE_AUTHOR;
			}
			if (!$row->_created || $row->_created == 'N/S;') {
				$row->_created = $row->A_RECORD_CREATE_DATE;
			}
		}

		$visibleColsWithIds = array();
		$visibleColsLabels = array();
		foreach ($visibleCols as $vColName) {
			$fldId = $this->_acl->getFieldIdByName($vColName);
			if ($fldId) {
				$visibleColsWithIds[$fldId] = $vColName;
				$label = $this->_acl->getFieldLabel($fldId);
				$label = (!$label)? $vColName : '<span title="' . "[{$fldId}] {$vColName}" . '">' . $label . '</span>';
				$visibleColsLabels[$fldId] = $label;
			}
		}

		?>
		<fieldset>
			<legend>Historia rekordu Nr <?php echo $id; ?>
				<span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span>
			</legend>
		</fieldset>

		<?php if (empty($rowsHist)) : ?>
			<div class="alert alert-info">
				<h4>Brak danych</h4>
			</div>
		<?php else: ?>
		<table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">
			<thead>
				<tr>
					<th>Data</th>
					<th>User</th>
					<th>Zmiany</th>
				</tr>
			</thead>
			<tbody>
			<?php foreach ($rowsHist as $row) : ?>
				<tr>
					<td style="white-space:nowrap"><?php echo $row->_created; ?></td>
					<td><?php echo $row->_author; ?></td>
					<td>
					<?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
						<?php if (in_array($colName, array('ID', 'A_RECORD_UPDATE_DATE', 'A_RECORD_UPDATE_AUTHOR', 'A_RECORD_CREATE_DATE', 'A_RECORD_CREATE_AUTHOR'))) continue; ?>
						<?php if ($row->$colName == 'N/S;') continue; ?>
						<p><em><?php echo $visibleColsLabels[$fldId]; ?></em>: 
							<?php if ($this->_acl->isAllowed($fldId, 'R', $record)) : ?>
								<?php echo $row->$colName; ?>
							<?php else : ?>
								<span title="Brak uprawnień do odczytu tego pola">*****</span>
							<?php endif; ?>
						</p>
					<?php endforeach; ?>
					</td>
				</tr>
			<?php endforeach; ?>
			</tbody>
		</table>

		<div style="overflow-x:scroll; overflow-y:visible; padding-bottom:1px; margin:10px 0;">
		<table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">
			<thead>
				<tr>
				<?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
					<th><?php echo str_replace('_', ' ', $visibleColsLabels[$fldId]); ?></th>
				<?php endforeach; ?>
				</tr>
			</thead>
			<tbody>
			<?php foreach ($rowsHist as $row) : ?>
				<tr>
				<?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
					<td>
						<?php if ($row->$colName == 'N/S;') : ?>
							<em>N/S;</em>
						<?php elseif ($this->_acl->isAllowed($fldId, 'R', $record)) : ?>
							<?php echo $row->$colName; ?>
						<?php else : ?>
							<span title="Brak uprawnień do odczytu tego pola">*****</span>
						<?php endif; ?>
					</td>
				<?php endforeach; ?>
				</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
		</div>
		<?php endif; ?>

		<?php
		exit;
	}

	/**
	 * Returns text/plain with type at first line: ERROR, WARNING, INFO, SUCCESS
	 */
	private function sendAjaxFilesUpload($id, $args) {
		// http://www.sitepoint.com/html5-ajax-file-upload/
		//$ajaxFileName = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);

		//header("Content-type: text/plain");
		header("Content-type: application/json");
		$DBG = ('1' == V::get('DBG', '', $_REQUEST));

		$dbID = $this->_acl->getDB();
		$db = DB::getDB($dbID);
		if (!$db) {
			header('HTTP/1.0 406 Not Acceptable');
			echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
			exit;
		}

		$record = $this->_dataSource->getItem($id);
		if (!$record) {
			header('HTTP/1.0 404 Not Found');
			echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
			exit;
		}

		$tblName = $this->_acl->getName();
		$confTblName = "{$tblName}_COLUMN";
		Lib::loadClass('FoldersConfig');
		$folderConfAll = FoldersConfig::getRawData();
		if (!FoldersConfig::hasConfig($confTblName)) {
			header('HTTP/1.0 404 Not Found');
			echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych(' . $tblName . ')"}';
			exit;
		}

		$folderConf = FoldersConfig::getAll($confTblName);

		Lib::loadClass('FileUploader');
		$uploader = new FileUploader($confTblName, $record);
		$errMsg = '';
		if (!$uploader->setConfig($folderConf, $errMsg)) {
			header('HTTP/1.0 404 Not Found');
			echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych(' . $tblName . ') <br>' . $errMsg . '"}';
			exit;
		}
		$uploader->findFolder();

		$errorMsg = '';
		if (!empty($_POST['SCANS_COLUMN_ADD'])) {
			$uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
		}
		else {
			$uploaded = $uploader->tryUploadAjax($errorMsg);
		}

		/*
			//$errorMsg = "wykonalem funkcje move dla parametrow ".$_FILES['M_DIST_FILES_NAME']['tmp_name']." oraz ".$IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER']."/".$IN7_FILERENAME['DST_FILE_NAME'] ." <br>Informacje dodatkowe :".$IN7_FILERENAME['INFO']." <br> EOL <br> ";
			// TODO: IN7_POST_HISTORY($TABLE, array('M_DIST_FILES'), array(" Wgrano plik z przegladarki WWW ".$_SERVER['REMOTE_ADDR']." ".$_FILES['M_DIST_FILES_NAME']['name']." do ".$IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER']."/".$IN7_FILERENAME['DST_FILE_NAME']." "), $thiss, $SESSION);
			// TODO: IN7_POST_HISTORY($TABLE, array('M_DIST_FILES'), array(" Wgrano plik z przegladarki WWW ".$_SERVER['REMOTE_ADDR']." ".$_FILES['M_DIST_FILES_NAME']['name']." do ".$IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER']."/".$IN7_FILERENAME['DST_FILE_NAME']." "), $thiss, $SESSION);
		 */

		if ($uploaded) {
			$uploadedFileName = '';
			$uploadedFile = $uploader->getLastUploadedFile();
			if ($uploadedFile) {
				$uploadedFileName = explode('/', $uploadedFile);
				$uploadedFileName = end($uploadedFileName);
			}
			echo '{"type":"SUCCESS", "string": "Plik został poprawnie wgrany do odpowiedniego katalogu '.$uploadedFileName.'"}';

			if (!empty($uploadedFileName)) {
				$sqlObj = new stdClass();
				$sqlObj->ID = $record->ID;
				$sqlObj->M_DIST_FILES = "Wgrano plik {$uploadedFileName}";
				$db->UPDATE_OBJ($this->_tbl, $sqlObj);
			}
		} else {
			echo '{"type":"ERROR", "string": "' . $errorMsg . '"}';
		}
		exit;
	}

	private function sendAjaxFileRemove($id, $args) {
		header("Content-type: application/json");
		$DBG = ('1' == V::get('DBG', '', $_REQUEST));

		if (empty($_POST['filename'])) {
			echo '{"type":"ERROR", "string": "Nie wybrano pliku do usunięcia"}';
			exit;
		}

		$dbID = $this->_acl->getDB();
		$db = DB::getDB($dbID);
		if (!$db) {
			header('HTTP/1.0 406 Not Acceptable');
			echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
			exit;
		}

		$record = $this->_dataSource->getItem($id);
		if (!$record) {
			header('HTTP/1.0 404 Not Found');
			echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
			exit;
		}

		$tblName = $this->_acl->getName();
		$confTblName = "{$tblName}_COLUMN";
		Lib::loadClass('FoldersConfig');
		$folderConfAll = FoldersConfig::getRawData();
		if (!FoldersConfig::hasConfig($confTblName)) {
			header('HTTP/1.0 404 Not Found');
			echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
			exit;
		}

		$folderConf = FoldersConfig::getAll($confTblName);

		Lib::loadClass('FileUploader');
		$uploader = new FileUploader($confTblName, $record);
		if (!$uploader->setConfig($folderConf)) {
			header('HTTP/1.0 404 Not Found');
			echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
			exit;
		}
		$uploader->findFolder();

		$errorMsg = '';
		$removed = $uploader->tryRemoveFromAjax($_POST['filename'], $errorMsg);
		if (!$removed) {
			echo '{"type":"ERROR", "string": "{' . $errorMsg . '}"}';
		} else {
			echo '{"type":"SUCCESS","string":"Plik został poprawnie usunięty"}';
		}
		exit;
	}

	private function sendAjaxFilesList($id, $args) {
		header("Content-type: application/json");

		$dbID = $this->_acl->getDB();
		$db = DB::getDB($dbID);
		if (!$db) {
			header('HTTP/1.0 406 Not Acceptable');
			echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
			exit;
		}

		$record = $this->_dataSource->getItem($id);
		if (!$record) {
			header('HTTP/1.0 404 Not Found');
			echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
			exit;
		}

		$tblName = $this->_acl->getName();
		$confTblName = "{$tblName}_COLUMN";
		Lib::loadClass('FoldersConfig');
		$folderConfAll = FoldersConfig::getRawData();
		if (!FoldersConfig::hasConfig($confTblName)) {
			header('HTTP/1.0 404 Not Found');
			echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
			exit;
		}

		$folderConf = FoldersConfig::getAll($confTblName);

		Lib::loadClass('FileUploader');
		$uploader = new FileUploader($confTblName, $record);
		if (!$uploader->setConfig($folderConf)) {
			header('HTTP/1.0 404 Not Found');
			echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
			exit;
		}
		$uploader->findFolder();

		$mainFolder = $uploader->getDestFolder();

		$files = $uploader->getFilesFromFolder($mainFolder, false, true);
		$localPath = $uploader->getLocalPath();
		$folderWeb = $uploader->getFolderWeb();
		$jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
		echo json_encode($jsonFiles);
		exit;
	}

	private function sendAjaxFilesConnTblList($id, $args) {
		header("Content-type: application/json");
		$DBG = ('1' == V::get('DBG', '', $_REQUEST));

		$dbID = $this->_acl->getDB();
		$db = DB::getDB($dbID);
		if (!$db) {
			header('HTTP/1.0 406 Not Acceptable');
			echo 'No DB (' . $dbID . ')';
			exit;
		}

		$record = $this->_dataSource->getItem($id);
		if (!$record) {
			header('HTTP/1.0 404 Not Found');
			echo 'No item ID(' . $rowID . ')';
			exit;
		}

		$connTblName = '';
		$connTblID = V::get('connTblID', 0, $_REQUEST, 'int');
		if ($connTblID <= 0) {
			header('HTTP/1.0 406 Not Acceptable');
			echo 'No conn Table ID';
			exit;
		}

		$connTblTypespecials = $this->getConnectedTblTypespecials($connTblID);
		if (empty($connTblTypespecials)) {
			header('HTTP/1.0 406 Not Acceptable');
			echo "No conn Table (ID={$connTblID})";
			exit;
		}

		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">connTblTypespecials (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($connTblTypespecials);echo'</pre>';}

		if(1) {
			header('HTTP/1.0 404 Not Found');
			echo 'TODO: ...';
			exit;
		}


		$tblName = $this->_acl->getName();
		$confTblName = "{$tblName}_COLUMN";
		Lib::loadClass('FoldersConfig');
		$folderConfAll = FoldersConfig::getRawData();
		if (!FoldersConfig::hasConfig($confTblName)) {
			header('HTTP/1.0 404 Not Found');
			echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
			exit;
		}

		$folderConf = FoldersConfig::getAll($confTblName);

		Lib::loadClass('FileUploader');
		$uploader = new FileUploader($confTblName, $record);
		if (!$uploader->setConfig($folderConf)) {
			header('HTTP/1.0 404 Not Found');
			echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
			exit;
		}
		$uploader->findFolder();

		$mainFolder = $uploader->getDestFolder();

		$files = $uploader->getFilesFromFolder($mainFolder, false, true);
		$localPath = $uploader->getLocalPath();
		$folderWeb = $uploader->getFolderWeb();
		$jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
		echo json_encode($jsonFiles);
		exit;
	}

	public function convertFileListToJson($files, $folderWeb, $localPath, $mainFolder) {
		sort($files);
		$jsonFiles = array();
		foreach ($files as $vFilePath) {
			$file = new stdClass();
			$file->name = str_replace("{$localPath}/{$mainFolder}/", '', $vFilePath);
			//$file->name = explode('/', $vFilePath);
			//$file->name = end($file->name);
			$file->size = filesize($vFilePath);
			$file->sizeStr = round($file->size, 2) . "B";
			if ($file->size > 1024 * 1024) {
				$file->sizeStr = round(($file->size / (1024 * 1024)), 2) . "M";
			} else if ($file->size > 1024) {
				$file->sizeStr = round(($file->size / 1024), 2) . "K";
			}
			$file->type = '';
			$file->created = date("Y-m-d H:i:s", filectime($vFilePath));
			$file->web = str_replace($localPath, $folderWeb, $vFilePath);
			$jsonFiles[] = $file;
		}
		return $jsonFiles;
	}

	private function getConnectedTables() {
		$connTbls = array();
		return $connTbls;// TODO: OFF - hardlinki tworzone w bash_sync_perms.php

		$fields = $this->_acl->getVisibleFieldList();
		if (!empty($fields)) {
			Lib::loadClass('Typespecial');
			foreach ($fields as $vColID => $vCol) {
				$typeSpecial = Typespecial::getInstance($vColID);
				if ($typeSpecial) {
					$tsConnTbls = $typeSpecial->getTblAliasList();
					if (!empty($tsConnTbls)) {
						foreach ($tsConnTbls as $kID => $vName) {
							$connTbls[$kID] = $vName;
						}
					}
				}
			}
		}

		return $connTbls;
	}

	private function getConnectedTblTypespecials($connTblID) {
		$connTblTypespecials = array();

		$fields = $this->_acl->getVisibleFieldList();
		if (!empty($fields)) {
			Lib::loadClass('Typespecial');
			foreach ($fields as $vColID => $vCol) {
				$typeSpecial = Typespecial::getInstance($vColID);
				if ($typeSpecial) {
					$tsConnTbls = $typeSpecial->getTblAliasList();

					if (array_key_exists($connTblID, $tsConnTbls)) {
						$connTblTypespecials[] = $typeSpecial;
					}
				}
			}
		}

		return $connTblTypespecials;
	}

	private function sendAjaxFiles($id, $args) {
		header("Content-type: text/plain");
		$DBG = ('1' == V::get('DBG', '', $_REQUEST));

		$dbID = $this->_acl->getDB();
		$db = DB::getDB($dbID);
		if (!$db) {
			header('HTTP/1.0 406 Not Acceptable');
			exit;
		}

		$record = $this->_dataSource->getItem($id);
		if (!$record) {
			header('HTTP/1.0 404 Not Found');
			echo "404: No item ID({$rowID})";
			exit;
		}

		$tblName = $this->_acl->getName();
		$confTblName = "{$tblName}_COLUMN";
		Lib::loadClass('FoldersConfig');
		$folderConfAll = FoldersConfig::getRawData();
		if (!FoldersConfig::hasConfig($confTblName)) {
			header('HTTP/1.0 404 Not Found');
			echo "Brak danych konfiguracyjnych";
			exit;
		}

		$folderConf = FoldersConfig::getAll($confTblName);
		//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$folderConf (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($folderConf);echo'</pre>';

		Lib::loadClass('FileUploader');
		$uploader = new FileUploader($confTblName, $record);
		$errMsg = '';
		if (!$uploader->setConfig($folderConf, $errMsg)) {
			header('HTTP/1.0 404 Not Found');
			echo "Błąd danych konfiguracyjnych ({$tblName})";
			echo '<br>' . "\n" . $errMsg;
			exit;
		}
		$uploader->findFolder();
		if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">uploader (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($uploader);echo'</pre>'; }

		$mainFolder = $uploader->getDestFolder();
		if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">mainFolder (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($mainFolder);echo'</pre>'; }

		$files = $uploader->getFilesFromFolder($mainFolder, false, true);
		if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">files (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($files);echo'</pre>'; }

		$sharePoint = V::get('share_point', null, $folderConf);
		if ($sharePoint) {
			$sharePoint = FoldersConfig::getNfsOsPath() . "{$sharePoint}/{$mainFolder}";
		}
		$localPath = $uploader->getLocalPath();
		$folderWeb = $uploader->getFolderWeb();
		$jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
		if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">jsonFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($jsonFiles);echo'</pre>'; }

		$folderSkanyConf = FoldersConfig::getAll('SCANS_COLUMN');
		$skanyLocalPath = V::get('mount_point', null, $folderSkanyConf);
		$skanySharePoint = V::get('share_point', null, $folderSkanyConf);
		$skanyFolderWeb = V::get('www_share_point', null, $folderSkanyConf);
		$skanyFiles = $uploader->getFilesFromSkany($folderSkanyConf, false);
		sort($skanyFiles);

		$fileTypes = FoldersConfig::getAll('m_dist_files_types');

		$rowFunctionsOut = $this->_showRowFunctions($record->ID, array('files', 'cp'), true);

		?>
		<script src="stuff/jquery.form.js"></script>
		<div class="container">

		<h4 style="margin:20px 0 3px 0;">Pliki w katalogu 
			<?php if ($sharePoint) : ?>
				<a href="<?php echo $sharePoint; ?>"><code><?php echo $mainFolder; ?></code></a>
			<?php else : ?>
				<code><?php echo $mainFolder; ?></code>
			<?php endif; ?>
			<span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span>
		</h4>
		<div style="max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">
		<table class="table table-bordered table-hover">
			<colgroup>
				<col style="">
				<col style="width:30px;">
				<?php if ($sharePoint) : ?>
					<col style="width:30px;">
				<?php endif; ?>
				<col style="width:80px;">
				<col style="width:140px;">
			</colgroup>
			<tbody id="FILES_LIST_<?php echo $this->_htmlID; ?>">
				<?php if (empty($mainFolder)) : ?>
					<tr>
						<td colspan="5">
							<div class="alert alert-warning">
								<h4>Brak folderu!</h4>
								Folder dla tego rekordu nie został utworzony.
							</div>
						</td>
					</tr>
				<?php elseif (empty($files)) : ?>
					<tr>
						<td colspan="5">
							<div class="alert alert-info">
								<h4>Brak plików</h4>
							</div>
						</td>
					</tr>
				<?php endif; ?>
			</tbody>
		</table>
		</div>

		<br>
		<br>

		<div id="FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>"></div>

		<form enctype="multipart/form-data" method="POST" action="" id="FILES_FRM_<?php echo $this->_htmlID; ?>" class="form-inline">

			<input type="hidden" name="M_DIST_UPLOAD_SOURCE" value="local">
			<ul id="FILES_TAB_<?php echo $this->_htmlID; ?>" class="nav nav-tabs" style="margin:0;">
				<li class="active"><a href="#local" data-toggle="local">Wybierz plik lokalny</a></li>
				<li><a href="#scan" data-toggle="scan">Wybierz plik ze skanów</a></li>
			</ul>
			<div id="myTabContent" class="tab-content">
				<div class="tab-pane fade in active" id="local" style="text-align: center;">
					<input name="M_DIST_FILES_NAME" type="file" size="60" class="field-upload btn" style="width:86%;margin:10px auto;padding:10px 4%;background:#eee;text-align:center;" ondragover="this.style.backgroundColor='#D9EDF7'" ondragleave="this.style.backgroundColor='#eee'" ondragend="this.style.backgroundColor='#eee'">
				</div>
				<div class="tab-pane fade" id="scan">
					<?php if (empty($skanyFiles)) : ?>
						<div class="alert alert-info">
							<h4>Brak plików</h4>
							<?php if(!empty($skanyFolderWeb)) echo "skonfiguruj urządzenie biurowe aby wysyłało skany na ftp://skaner:(h*a*s*l*o)@".$_SERVER['SERVER_NAME']." <br> lub <a href=".FoldersConfig::getNfsOsPath().$skanySharePoint.">".FoldersConfig::getNfsOsPath().$skanySharePoint."</a>"; ?>
						</div>
					<?php else : ?>
						<div style="max-height:150px; overflow:auto; border-bottom:1px solid #ddd;">
							<table class="table table-bordered table-hover">
								<colgroup>
									<col style="width:30px;">
									<col style="">
									<col style="width:30px;">
									<col style="width:80px;">
									<col style="width:140px;">
								</colgroup>
								<tbody>
								<?php foreach ($skanyFiles as $vFilePath) : ?>
									<tr>
									<?php
										$vFileName = explode('/', $vFilePath);
										$vFileName = end($vFileName);
										$vFileSize = filesize($vFilePath);
										$vFileSizeOut = round($vFileSize, 2) . "B";
										if ($vFileSize > 1024 * 1024) {
											$vFileSizeOut = round(($vFileSize / (1024 * 1024)), 2) . "M";
										} else if ($vFileSize > 1024) {
											$vFileSizeOut = round(($vFileSize / 1024), 0) . "K";
										}
									?>
									<td><input style="margin:0;" type="radio" name="SCANS_COLUMN_ADD" value="<?php echo $vFileName; ?>"></td>
									<td><div style="overflow:hidden; white-space:nowrap;" title="<?php echo $vFileName; ?>"><?php echo $vFileName; ?></div></td>
									<td style="white-space:nowrap; text-align:center;"><a href="<?php echo str_replace($skanyLocalPath, $skanyFolderWeb, $vFilePath); ?>" target="_blank" class="ico-download-alt"></a></td>
									<td style="white-space:nowrap;"><?php echo $vFileSizeOut; ?></td>
									<td style="white-space:nowrap;"><?php echo date("Y-m-d H:i:s", filectime($vFilePath)); ?></td>
									</tr>
								<?php endforeach; ?>
								</tbody>
							</table>
						</div>
					<?php endif; ?>
				</div>
			</div>
			<script>
				$('#FILES_TAB_<?php echo $this->_htmlID; ?> a').click(function (e) {
					e.preventDefault();
					$(this).tab('show');
				})
				.on('shown', function (e) {
					var fileSource = $(e.target).data('toggle')
						, frm = jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').get(0);
					if (frm['M_DIST_UPLOAD_SOURCE']) {
						frm['M_DIST_UPLOAD_SOURCE'].value = fileSource;
					}
				})
			</script>

			<br>

			<table style="width:100%" class="table table-noborder">
				<tr>
					<td colspan="5">
						<h4>Ustal nazwę pliku zgodną z obiegiem dokumentów
						<?php //TODO: link do procesu o obiegu dokumentów <i class="icon-question-sign" style="cursor:help" title="działa w nowszych przeglądarkach jak Firefox, Chrome"></i> ?>
					</h4>
					</td>
				</tr>
				<tr>
					<th style="border-right:1px solid #eee">ID</th>
					<th style="border-right:1px solid #eee">TYP</th>
					<th style="border-right:1px solid #eee">Opis <i class="icon-question-sign" title="kogo dotyczy / czego / sprawa / nazwa_firmy itp"></i></th>
					<th style="border-right:1px solid #eee">Data Wersji</th>
					<th>Numer Wersji</th>
				</tr>
				<tr>
					<td style="border-right:1px solid #eee;">
						<?php echo $record->ID; ?>
					</td>
					<td style="border-right:1px solid #eee;">
						<select name="M_DIST_FILES_TYPE">
							<?php foreach ($fileTypes as $kType => $vLabel) : ?>
								<option value="<?php echo $kType; ?>"<?php if ($kType == 'TODO') { echo ' selected="selected"'; } ?> ><?php echo $vLabel; ?></option>
							<?php endforeach; ?>
						</select>
						<br>
						<label class="checkbox">
							<input type="checkbox" name="M_DIST_FILES_TYPE_AUTO">
							Wykrycie automatyczne TYPU z wysylanego pliku
						</label>
						<label  class="checkbox">
							<input type="checkbox" name="M_DIST_FILES_TEMP">
							Plik tymczasowy / roboczy / nieoficjalny (_TEMP)
						</label>
					</td>
					<td style="border-right:1px solid #eee;">
						<input type="text" name="M_DIST_FILES_DESCRIPTION" value="<?php echo $M_DIST_FILES_DESCRIPTION; ?>" maxlength="50">
						<br><label>jeśli nie zostanie podany to zostanie automatycznie wygenerowany na podstawie nazwy pliku wysyłanego</label>
					</td>
					<td style="border-right:1px solid #eee;">
						<input type="date" name="M_DIST_FILES_DATE" value="<?php echo date('Y-m-d');?>" maxlength="10" class="span2">
						<br><label>jeśli nie zostanie podana to zostanie ustawiona na dzisiaj (<?php echo date('Y-m-d');?>)</label>
					</td>
					<td>
						<input type="number" name="M_DIST_FILES_VERSION" class="span2">
						<br>
						<label  class="checkbox">
							<input type="checkbox" name="M_DIST_FILES_VERSION_AUTO">
							Automatycznie dodaj wersje
						</label>
					</td>
				</tr>
				<tr>
					<td colspan="5">
						<div id="FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>"></div>
						<p>
							<input type="submit" value="Wyślij" class="btn btn-primary"> wybrany plik do folderu:
						</p>
						<p>
							<code><b><?php echo $uploader->getDestPathShare(true); ?></b></code>
							<br><i style="color:#777">(Jeśli folder nie istnieje to zostanie utworzony automatycznie)</i>
						</p>
					</td>
				</tr>
			</table>
		</form>
		</div>
		<script>
function fileListUpdateAjax<?php echo $this->_htmlID; ?>() {
	var postData = {};
	jQuery.ajax({
		url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES_LIST&ID=<?php echo $record->ID; ?>',
		type: 'POST',
		//dataType: 'json',
		//contentType: "application/json; charset=utf-8",
		data: postData,
		async: true,
		success: function (data) {
			fileListUpdate<?php echo $this->_htmlID; ?>(data);
		},
		error: function (jhr, textStatus, errorThrown) {
			console.log('request error: ', errorThrown, ' textStatus: ', textStatus);
		}
	});
}

function fileListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
	var fileListNode = jQuery('#FILES_LIST_<?php echo $this->_htmlID; ?>');
	fileListNode.empty();
	fileListJson.map(function(file){
		var node = $('<tr></tr>');
		var fFun = $('<i class="ico-remove" style="cursor:pointer" data-filename="' + file.name + '"></i>');
		var fNameCell = $('<td style="overflow: hidden;"></td>');
		var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
		fName.append(fFun);
		fName.append(file.name);
		fName.appendTo(fNameCell);
		node.append(fNameCell);
		node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="' + file.web + '" target="_blank" class="ico-download-alt"></a>' + '</td>');
		<?php if ($sharePoint) : ?>
			node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="<?php echo $sharePoint; ?>/' + file.name + '" target="_blank" class="ico-folder-open"></a>' + '</td>');
		<?php endif; ?>
		node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
		node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
		node.appendTo(fileListNode);

		$(fFun).click(function(e){
			var n = $(e.target);
			var fname= n.data('filename');
			if (!fname) {
				return false;
			}
			if (confirm('Czy jesteś pewien, że chcesz usunąć plik o nazwie ' + fname + '?')) {
				var postData = {filename: fname};
				jQuery.ajax({
					url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILE_REMOVE&ID=<?php echo $record->ID; ?>',
					type: 'POST',
					//dataType: 'json',
					//contentType: "application/json; charset=utf-8",
					data: postData,
					async: true,
					success: function (data) {
						if (data && data.type) {
							if (data.type == 'SUCCESS') {
								n.parents('tr').remove();
								//console.log('TODO: SUCCESS msg: ', data.string);
							}
							else if (data.type == 'ERROR') {
								//console.log('TODO: ERROR msg: ', data.string);
							}
						} else {
							console.log('TODO: ??? data: ', data);
						}
					},
					error: function (jhr, textStatus, errorThrown) {
						console.log('rm error: ', errorThrown, ' textStatus: ', textStatus);
					}
				});
			}
		});
	});
}

function connTblListUpdateAjax<?php echo $this->_htmlID; ?>(connTblID) {
	var postData = {};

	// clear current file list
	jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list').empty();

	jQuery.ajax({
		url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES_CONN_TBL_LIST&ID=<?php echo $record->ID; ?>&connTblID=' + connTblID,
		type: 'POST',
		//dataType: 'json',
		//contentType: "application/json; charset=utf-8",
		data: postData,
		async: true,
		success: function (data) {
			connTblListUpdate<?php echo $this->_htmlID; ?>(data);
		},
		error: function (jqXHR, textStatus, errorThrown) {
			var txt = jqXHR.responseText || 'Error';
			jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list').html('<tr><td colspan="6"><div class="alert alert-error">' + txt + '</div></td></tr>');
			console.log('connTblListUpdateAjax error: ', errorThrown, ' textStatus: ', textStatus);
		}
	});
}

function connTblListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
	var fileListNode = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list');
	fileListNode.empty();
	fileListJson.map(function(file){
		var node = $('<tr></tr>');
		var fNameCell = $('<td style="overflow: hidden;"></td>');
		var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
		fName.append(file.name);
		fName.appendTo(fNameCell);
		node.append(fNameCell);
		node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="' + file.web + '" target="_blank" class="ico-download-alt"></a>' + '</td>');
		node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
		node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
		node.appendTo(fileListNode);
	});
}

jQuery(document).ready(function(){

	jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').ajaxForm({
		url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES_UPLOAD&ID=<?php echo $record->ID; ?>',
		beforeSubmit: function(args, $form, options) {
			var argsMap = [];
			args.map(function(v, k) {
				argsMap[v.name] = v.value;
			});
			// validate
			if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'local') {
				if (!argsMap['M_DIST_FILES_NAME']) {
					console.log('TODO: nie wybrano lokalnego pliku!');
					return false;
				}
			}
			else if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'scan') {
				if (!argsMap['SCANS_COLUMN_ADD']) {
					console.log('TODO: nie wybrano pliku ze skanów!');
					return false;
				}
			}
			else {
				console.log('TODO: nie wybrano źródła pliku!');
				return false;
			}

			var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
			$out.html('Wysyłanie...');
		},
		success: function(data) {
			var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
			var btnClose = '<button type="button" class="close" data-dismiss="alert"><i class="icon-remove"></i></button>';
			if (typeof data == 'object') {
				if (data.type == 'ERROR') {
					$out.html('<div class="alert alert-error">' + btnClose + data.string + '</div>');
				} else if (data.type == 'SUCCESS') {
					$out.html('<div class="alert alert-success">' + btnClose + data.string + '</div>');
					fileListUpdateAjax<?php echo $this->_htmlID; ?>();
				}
			} else {
				if (data.substr(0, 7) == 'WARNING') {
					data = data.substr(7);
					$out.html('<div class="alert alert-warning">' + btnClose + data + '</div>');
				} else if (data.substr(0, 5) == 'ERROR') {
					data = data.substr(5);
					$out.html('<div class="alert alert-error">' + btnClose + data + '</div>');
				} else if (data.substr(0, 7) == 'SUCCESS') {
					data = data.substr(7);
					$out.html('<div class="alert alert-success">' + btnClose + data + '</div>');
					fileListUpdateAjax<?php echo $this->_htmlID; ?>();
				} else if (data.substr(0, 4) == 'INFO') {
					data = data.substr(4);
					$out.html('<div class="alert alert-info">' + btnClose + data + '</div>');
				}
			}
		}
	});

	var fileList = <?php echo json_encode($jsonFiles); ?>;

	fileListUpdate<?php echo $this->_htmlID; ?>(fileList);

	var connTbls = <?php echo json_encode($this->getConnectedTables()); ?>;
	if (connTbls) {
		var connTblsOut = '';
		for(var key in connTbls) {
			connTblsOut += '<button class="btn btn-small conn-tbl-load" data-zasobid="' + key + '">' + connTbls[key] + '</button>';
		};

		if (connTblsOut) {
			connTblsOut = 'Pliki w powiązanych tabelach: <div class="btn-group">' + connTblsOut + '</div>';
			connTblsOut += '<div style="max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">' +
				'<table class="table table-bordered table-hover">' +
					'<colgroup>' +
						'<col style="">' +
						'<col style="width:30px;">' +
						<?php if ($sharePoint) : ?>
							'<col style="width:30px;">' +
						<?php endif; ?>
						'<col style="width:80px;">' +
						'<col style="width:140px;">' +
					'</colgroup>' +
					'<tbody class="files-list">' +
					'</tbody>' +
				'</table>' +
				'</div>';

			var _connTblsWrap = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>');
			_connTblsWrap.css('marginBottom', '26px');
			_connTblsWrap.html(connTblsOut);
			_connTblsWrap.find('.conn-tbl-load').each(function(){
				jQuery(this).click(function(e){
					var tblID = jQuery(e.target).data('zasobid');
					console.log('clicked: ', tblID);
					if (tblID) {
						connTblListUpdateAjax<?php echo $this->_htmlID; ?>(tblID);
					}// TODO: else show error
				});
			});
		}
	}

});
		</script>
		<?php
		exit;
	}

	private function sendTypeSpecial($fldID, $args) {
		$DBG = ('1' == V::get('DBG', '', $_REQUEST));

		header("Content-type: application/json");

		$fldName = '';
		$fld = $this->_acl->getField($fldID);
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fld('.$fldID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($fld);echo'</pre>';}
		if (!$fld) {
			// 404
		} else {
			$fldName = $fld['name'];
		}

		$jsonData = array();
		Lib::loadClass('Typespecial');
		$typeSpecial = Typespecial::getInstance($fldID, $fldName);
		if ($typeSpecial) {
			$query = V::get('q', '', $_REQUEST);
			$rawRows = null;
			$rows = $typeSpecial->getValuesWithExports($query);
			if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">rows('.$query.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($rows);echo'</pre>';}
			foreach ($rows as $kID => $vItem) {
				$itemJson = new stdClass();
				$itemJson->id = $vItem->id;
				$itemJson->name = $vItem->param_out;
				if (!empty($vItem->exports)) {
					$itemJson->exports = $vItem->exports;
				}
				$jsonData[] = $itemJson;
			}
		}

		/*
			MENU_INIT:VIEWTABLE_AJAX
			ZASOB_ID:1188
			_task:TYPESPECIAL
			fldID:3866

			Form Dataview sourceview URL encoded
			q:te
		 */
		echo json_encode($jsonData);
		exit;
	}

	private function sendTypeSpecialCell($id, $fldName, $args) {
		$DBG = ('1' == V::get('DBG', '', $_REQUEST));

		header("Content-type: application/json");
		$jsonData = new stdClass();

		$fldID = $this->_acl->getFieldIdByName($fldName);
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fld('.$fldName.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($fldID);echo'</pre>';}

		$item = $this->_dataSource->getItem($id);
		if (!$this->_acl->isAllowed($fldID, 'R', $item)) {
			$jsonData->msg = 'Brak dostępu';
			echo json_encode($jsonData);
			exit;
		}

		if (!$fldID) {
			$jsonData->msg = 'Wrong field';
			echo json_encode($jsonData);
			exit;
		}

		Lib::loadClass('Typespecial');
		$typeSpecial = Typespecial::getInstance($fldID, $fldName);
		if ($typeSpecial) {
			$jsonData->data = $typeSpecial->getReturnData($this->_zasobID, $id, $fldName, '');
			if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">specialValuesByIds('.$id.'/'.$fldName.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValuesByIds);echo'</pre>';}
		}

		echo json_encode($jsonData);
		exit;
	}

	private function sendAjaxData($args) {
		$DBG = ('1' == V::get('DBG', '', $_REQUEST));

		header("Content-type: application/json");

		//sleep(1);// TODO: TEST

		$pageSize = V::get('pageSize', 10, $args, 'int');
		$page = V::get('page', 0, $args, 'int');
		$currSortCol = V::get('currSortCol', '', $args);
		$currSortFlip = V::get('currSortFlip', '', $args);
		if ($page > 0) {
			$page -= 1;
		}
		else {
			
		}

		$params = array();
		$params['limit'] = $pageSize;
		$params['limitstart'] = $page * $params['limit'];
		$params['order_by'] = ($currSortCol)? $currSortCol : '';
		$params['order_dir'] = $currSortFlip;

		$filters = new stdClass();
		$filters->currSortCol = $currSortCol;
		$filters->currSortFlip = $currSortFlip;
		foreach ($args as $k => $v) {
			if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
				$params[$k] = $v;
				$filters->{$k} = $v;
			}
			else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
				$params[$k] = $v;
				$filters->{$k} = $v;
			}
		}

		$this->setFilters($filters);

		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">_dataSource (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_dataSource);echo'</pre>';}
		$vCols = $this->_acl->getVirtualFieldList();
		if (!empty($vCols)) {
			if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">vCols (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCols);echo'</pre>';}
		}

		Lib::loadClass('Typespecial');

		$total = $this->_dataSource->getTotal($params);
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">get_total (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($total);echo'</pre>';}
		$items = $this->_dataSource->getItems($params);
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">items (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($items);echo'</pre>';}
		// TODO: add virtual data by Typespecial
		if (!empty($vCols) && !empty($items)) {
			foreach ($vCols as $vColID => $vCol) {
				$colType = $this->_acl->getFieldTypeById($vColID);
				if ($colType) {
					continue;// pomin Typespecial dla realnych komorek w bazie danych
				}

				$typeSpecial = Typespecial::getInstance($vColID, $vCol);
				if ($typeSpecial) {
					if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vColID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
					$ids = array_keys($items);
					$specialValues = $typeSpecial->getValuesByIds($this->_zasobID, $ids);
					if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vCol.') specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValues);echo'</pre>';}
					if (!empty($specialValues)) foreach ($specialValues as $kItemID => $vValues) {
						$tsValue = implode('<br>', $vValues);
						if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Item['.$kItemID.'].'.$vCol.' specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($items[$kItemID]);echo'</pre>';}
						if (!empty($items[$kItemID]->{$vCol}) && !empty($tsValue)) {
							$items[$kItemID]->{$vCol} .= ": {$tsValue}";
						} else {
							$items[$kItemID]->{$vCol} = $tsValue;
						}
					}
				}
			}
		}

		$visibleCols = $this->_acl->getVisibleFieldList();
		if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">visibleCols (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($visibleCols);echo'</pre>';}

		$jsonData = new stdClass();
		$jsonData->total = $total;
		$jsonData->cols = new stdClass();
		$ind = 0;
		foreach ($visibleCols as $fieldID => $col) {
			$ind++;
			$jsonData->cols->{$col} = (object)array('index'=>$ind);
			if ($col == 'ID') {
				// /SE/se-dev/index.php?MENU_INIT=USERS2_MARKETING_EDIT&ARG1=EDIT&ARG1_VAL=31105
				$jsonData->cols->{$col}->format = '<a href="#EDIT/{0}">{0}</a>';
				$jsonData->cols->{$col}->unique = true;
			}
			else if (in_array($col, array('A_STATUS','A_STATUS_CURRENT','A_SERVICES_STATUS_CURRENT'))) {
				$jsonData->cols->{$col}->format = '<div class="cell-A_STATUS-{0}">{0}</div>';
			}
			else if (in_array($col, array('Status'))) {
				// Ahmes problems Status colors
				$jsonData->cols->{$col}->format = '<div class="cell-Status-{0}">{0}</div>';
			}
			if ('' !== ($label = $this->_acl->getFieldLabel($fieldID))) {
				$jsonData->cols->{$col}->friendly = $label;
			}
			$colType = $this->_acl->getFieldType($col);
			if ($colType) {// @see MarkTableAjaxFilterColType
				if ($colType['type'] == 'date') {
					//$jsonData->cols->{$col}->type = 'date';// TODO: require datepicker
				}
			} else {// typespecial - no type
				$jsonData->cols->{$col}->type = 'special';
			}

			$typeSpecial = Typespecial::getInstance($fieldID, $col);
			if ($typeSpecial) {
				if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">typeSpecial (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
				$jsonData->cols->{$col}->_tsRetId = $typeSpecial->getReturnId();
			}

			// @see sendHiddenColsSave
			// $_SESSION['USER_PROFILE'][$this->_zasobID][fld_id] => boolean
			if (isset($_SESSION['USER_PROFILE'][$this->_zasobID])) {
				if (isset($_SESSION['USER_PROFILE'][$this->_zasobID][$fieldID])) {
					if ($_SESSION['USER_PROFILE'][$this->_zasobID][$fieldID] != 1) {
						$jsonData->cols->{$col}->hidden = true;
					}
				}
			}
		}
		$jsonData->rows = array();
		foreach ($items as $vItem) {
			// TODO: hide items without 'R'
			foreach ($visibleCols as $kID => $vCol) {
				// TODO: ID default 'R'
				if (!$this->_acl->isAllowed($kID, 'R', $vItem)) {
					$vItem->{$vCol} = '*****';
				}

				// null => empty string
				if (!isset($vItem->{$vCol}) || (!$vItem->{$vCol} && $vItem->{$vCol} !== '0')) {
					if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">isEmptyString['.$vCol.'] (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vItem->{$vCol});echo'</pre>';}
					$vItem->{$vCol} = '';
				}
			}
			$jsonData->rows[] = $vItem;
		}
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">this->_dataSource (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_dataSource);echo'</pre>';
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">jsonData (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($jsonData);echo'</pre>';
		echo json_encode($jsonData);
		exit;
	}

	private function fixEmptyValueFromUser($fieldID) {// TODO: moved to TableAcl->fixEmptyValueFromUser
		$value = '';
		$type = $this->_acl->getFieldTypeById($fieldID);
		if ($type) {
			if ($type['type'] == 'date') {
				$value = $type['default'];
			}

			// fix bug when field is unique and is null allowed: change empty string to null
			if ($type['null']) {
				$value = 'NULL';
			}

			// fix bug when field is enum and is set to '0': for php '0' is empty
			if (substr($type['type'], 0, 4) == 'enum') {// && $args["f{$fieldID}"] === '0') {
				if (false !== strpos($type['type'], "''")) {
					// enum('', '1','2')
					$value = '';
				} else if (false !== strpos($type['type'], "'0'")) {
					// enum('0', '1','2')
					$value = '0';
				} else {
					$value = $type['default'];
				}
			}
		}
		return $value;
	}

	/**
	 * set hidden cols in $_SESSION['USER_PROFILE'][$this->_zasobID];
	 *   $_SESSION['USER_PROFILE'][$this->_zasobID][fld_id] => boolean
	 */
	private function sendHiddenColsSave($args) {
		if (empty($_POST)) {
			exit;
		}

		Lib::loadClass('UserProfile');
		UserProfile::load();

		// clean up old, wrong values
		if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
			unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
		}

		$colVis = array();
		if (array_key_exists($this->_zasobID, $_SESSION['USER_PROFILE'])) {
			$colVis = $_SESSION['USER_PROFILE'][$this->_zasobID];
		}

		$fields = $this->_acl->getFields();
		foreach ($fields as $kFldId => $vFld) {
			$vFldName = $vFld['name'];
			if (isset($_POST[$vFldName])) {
				if ($_POST[$vFldName] == 'SHOW') {
					$colVis[$kFldId] = 1;
				} else if ($_POST[$vFldName] == 'HIDE') {
					$colVis[$kFldId] = 0;
				}
			}
		}

		$_SESSION['USER_PROFILE'][$this->_zasobID] = $colVis;

		UserProfile::save();
	}

}
