// !! zobrazit stav/obsah table.click, aby clovek vedel, zda edituje radek nebo klonuje pro insert / delete

// table engine

var ENG  = {};
ENG.db   = {};
ENG.cfg  = {};
ENG.obj  = {};
ENG.data = {};
ENG.tpl  = {};
ENG.func = {};
// as plugin cols, rows
ENG.cr      = {};
ENG.cr.data = {};
ENG.cr.func = {};
// as plugin filter cols, remove cols, add id col (SELECT)
ENG.fc      = {};
ENG.fc.data = {};
ENG.fc.func = {};
// as plugin filter words (WHERE)
ENG.fw      = {};
ENG.fw.obj  = {};
ENG.fw.data = {};
ENG.fw.tpl  = {};
ENG.fw.func = {};
// as plugin filter multisort (ORDER BY a asc,b desc,c asc...)
ENG.fms        = {};
ENG.fms.obj    = {};
ENG.fms.obj.id = {};
ENG.fms.data   = {};
ENG.fms.tpl    = {};
ENG.fms.func   = {};
// as plugin filter rows (LIMIT start, end)
ENG.fr        = {};
ENG.fr.obj    = {};
ENG.fr.obj.id = {};
ENG.fr.data   = {};
ENG.fr.tpl    = {};
ENG.fr.func   = {};
// as plugin info panel
ENG.ip      = {};
ENG.ip.obj  = {};
ENG.ip.data = {};
ENG.ip.tpl  = {};
ENG.ip.func = {};
//ENG. = [];
ENG.ss        = {};
ENG.ss.obj    = {};
ENG.ss.obj.id = {};
ENG.ss.tpl    = {};
ENG.ss.f      = {};
ENG.ss.data   = {};
ENG.ss.func   = {};

// mode panel
ENG.mp        = {};
ENG.mp.obj    = {};
ENG.mp.obj.id = {};
ENG.mp.tpl    = {};
ENG.mp.data   = {};
ENG.mp.func   = {};

//ENG.hist = {};
//ENG.hist.func = {};
//ENG.hist.func.openClick = function() {};
ENG.edit      = {};
ENG.edit.query_db  = {};
ENG.edit.obj  = {};
ENG.edit.data = {};
ENG.edit.tpl  = {};
ENG.edit.func = {};

ENG.transfer      = {};
ENG.transfer.obj  = {};
ENG.transfer.obj.id = {};
ENG.transfer.data = {};
ENG.transfer.tpl  = {};
ENG.transfer.func = {};



ENG.func.init = function(opt)
{
var i, pref, id;
ENG.cfg.pref = 'zas2_';
ENG.db.keys    = db_keys;
ENG.db.values  = db_values;
ENG.db.map     = db_map;
ENG.db.filters = db_filters;
ENG.db.structure = [
	'num','num',
	'str','str','str',
	'str','str','str','str','str',
	'str','str','str','str','str',
	'str','str','str','str','str',
	'str','str','str','str','str',
	'str'
	];
for (i in opt)
	{
	if (i=='remove' || i=='add' || i=='col_row_id')
		{
		ENG.fc.data[i] = opt[i];
		continue;
		}
	ENG.cfg[i] = opt[i];
	}
ENG.cfg.pref += ENG.cfg.pref!=='' ? '_' : '';
ENG.cfg.col_row_id  = isExist(ENG.cfg.col_row_id) ? ENG.cfg.col_row_id : 0;
pref = ENG.cfg.pref;
ENG.obj.log   = objGet(pref+'log');
ENG.obj.tab_div = objGet(pref+'panel_table');
ENG.obj.navtop    = objGet(pref+'panel_navtop');
ENG.obj.navbottom = objGet(pref+'panel_navbottom');
ENG.data.tab = '';
ENG.cr.data.rows = [0,0];
ENG.cr.data.rows[1]  = ENG.db.map.length;
//ENG.data.old = {};
//ENG.data.old.fr = {};
//ENG.data.cols = [];
ENG.cr.data.cols = [];
ENG.cr.data.rend = [];
ENG.cr.data.ignore = false;
//ENG.tpl.table_th = '<th class="filter"><div onclick="ENG.func.filterOpenClick({key},this);">{key}<br>{value}<\/div><\/th>';//[+] 
//return '<table class="' + table_class + '" onclick="EE.func.updateColumnClick(event);"><thead>' + thead + '<\/thead><tbody>' + tbody + '<\/tbody><\/table>';
ENG.tpl.table     = '<table class="{class}" onclick="{onclick}"><col><thead>{thead}<\/thead><tbody>{tbody}<\/tbody><\/table>';
// onblur="{onblur}"
ENG.tpl.thead_th  = '<th class="filter col{key} hover"><div onclick="{onclick}">{value}<\/div><\/th>';	//no-edit
ENG.tpl.tbody_th  = '<th>{value}<\/th>';
ENG.tpl.tbody_td  = '<td>{value}<\/td>';
//ENG.tpl.table_td =  '<table class="' + table_class + '" onclick="EE.func.updateColumnClick(event);"><thead>' + thead + '<\/thead><tbody>' + tbody + '<\/tbody><\/table>';
//ENG.tpl.x = '<label><input type="checkbox" name="xx"  id="xx" value="xx" onclick="ENG.data.x = this.checked;"> zahadny checkbox</label>';
ENG.tpl.x = '';


// plugins init
ENG.transfer.func.init(pref);
ENG.fc.func.init(pref);	// fc musi byt pred edit
ENG.fw.func.init(pref);
ENG.fr.func.init(pref);
ENG.fms.func.init(pref);
ENG.edit.func.init(pref);
ENG.hist.func.init(pref);
ENG.ip.func.init(pref);
ENG.mp.func.init();	// modes, mp se musi spoustet po edit a history
ENG.fms.func.createAll();
toggle(ENG.fw.obj.all  ,false);
toggle(ENG.fms.obj.all ,false);
toggle(ENG.fr.obj.all  ,false);
//toggle(ENG.hist.obj.all,false);
}

ENG.event = {};
ENG.event.func = {};

ENG.event.func.read = function (event)
	{
	event  = event || window.event;
	target = event.target || event.srcElement;
	return {'event':event, 'target':target};
	}

ENG.event.func.table = function (target)
	{
	var out, tr, table, row_id, col_id;
	out = {'tr':null, 'table':null, 'row_id':-1, 'col_id':-1}
	tr  = target.parentNode;
	if (tr.nodeName!=='TR')	//error, no tr
		{return out;}
	out.tr = tr;
	table  = tr.parentNode;
	if (table.nodeName!=='TABLE')	//if exist tbody
		{table  = table.parentNode;}
	if (table.nodeName!=='TABLE')	//error, no table
		{return out;}
	out.table  = table;
	out.row_id = tr.title * 1;
	out.col_id = target.cellIndex * 1;
	return out;
	}


ENG.mp.func.init = function()
{
var pref = ENG.cfg.pref;
ENG.mp.data.modes_all = {
	//id, text, func
	'view'    : {'text': 'View'    , 'table': ENG.func.eventNoneClick       , 'open': ENG.func.eventNoneClick       , 'close': ENG.func.eventNoneClick},      
	'history' : {'text': 'History' , 'table': ENG.hist.func.historyOpenClick, 'open': ENG.hist.func.openClick       , 'close': ENG.hist.func.historyCloseClick},
//	'edit'    : {'text': 'Edit'    , 'table': ENG.edit.func.editOpenClick   , 'open': ENG.edit.func.openClick       , 'close': ENG.edit.func.closeClick},
	'edit'    : {'text': 'Edit'    , 'table': ENG.edit.func.tableClick   , 'open': ENG.edit.func.openClick       , 'close': ENG.edit.func.closeClick},
	'download': {'text': 'Download', 'table': ENG.func.eventNoneClick       , 'open': ENG.transfer.func.downloadOpenClick , 'close': ENG.transfer.func.closeClick},
	'upload'  : {'text': 'Upload'  , 'table': ENG.func.eventNoneClick       , 'open': ENG.transfer.func.uploadOpenClick   , 'close': ENG.transfer.func.closeClick}
	}
ENG.mp.obj.id.all = pref+'mode_panel';
ENG.mp.obj.all    = objGet(ENG.mp.obj.id.all);
ENG.mp.tpl.all    = '{items}';
ENG.mp.tpl.item   = '<span class="item hover {class}" onclick="{onclick}" title="javascript: {title}">{text}<\/span>';
//ENG.ip.tpl.butt    = '<span class="butt hover" onclick="{onclick}" title="javascript: {onclick}">{text}{stav}<\/span>';
//ENG.mp.func.modeClick();
//ENG.mp.func.modeClick('edit');
ENG.mp.func.modeClick('history');
}

ENG.mp.func.modeClick = function(mode, not_open_close)
{
var modes_all, mode, i, str, tpl, butt, text_add;
//!!! ZACYKLUJE se pri editaci, spousti se funkce navzajem donekonecna
if (!ENG.mp.data.modes_all)	// nastava pri edit.init, kdy se vola tato funkce, ale nemohl probehnout init modu, ktery se zas odvolava na edit a history
	{return;}
tpl       = ENG.mp.tpl;
modes_all = ENG.mp.data.modes_all;
//objGet('xxx').innerHTML = mode
//mode      = isExist(modes_all[mode]) ? mode : 'view';
ENG.func.onTableClick = modes_all[mode]['table'];
//ENG.func.onTableBlurClick = modes_all[mode]['close'];
//ENG.func.onTableBlurClick = function(){alert(111);};
//objGet('xxx').innerHTML = ENG.func.onTableClick + ' ' + (new Date().getTime())
out = [];
// close all opened
if (not_open_close!=true)
	{
	for (i in modes_all)
		{
//alert(modes_all[i].close)
		modes_all[i].close();
		}
	}
for (i in modes_all)
	{
	text_add = '';
	if (i=='history')
		{
		text_add = ENG.hist.db.map.length;
		text_add = ' ('+ text_add +')';
		}
	if (i=='edit')
		{
		text_add = ENG.edit.query_db['update'].length +
			   ENG.edit.query_db['insert'].length +
			   ENG.edit.query_db['delete'].length -
			   ENG.edit.data['update'].deleted -
			   ENG.edit.data['insert'].deleted -
			   ENG.edit.data['delete'].deleted;
		text_add = ' ('+ text_add +')';
		}
	butt = {
		'class'  : mode==i ? 'sel' : '',
		'text'   : modes_all[i]['text'] + text_add,
		'onclick': "ENG.mp.func.modeClick('"+i+"');"
		};
	butt.title = escapeHtml(butt.onclick);
	out[out.length] = render(tpl.item,butt);
	}
ENG.mp.obj.all.innerHTML = render(tpl.all, {'items':out.join(' | ')});
if (not_open_close==true)
	{return;}
modes_all[mode]['open']();
}


ENG.func.eventNoneClick = function(event)
{
return true;
}

ENG.func.log = function(str,reset)
{
var div, obj = ENG.obj.log;
if (isExist(str)) {
	div = obj.innerHTML!=='' ? '<br>' :'';
	obj.innerHTML = ENG.cr.func.strRows() + ' ' + str + div + obj.innerHTML;
	}
if (isExist(reset) && reset==true) {obj.innerHTML = ''; return;}
return obj.innerHTML;
}

ENG.func.doFilters = function(uniq)
{
var tab, str;
var uniq = isExist(uniq) ? uniq : true;
str  = '';
PERF.getTime();
tab = arrayClone2(ENG.db.map);
ENG.cr.data.rows[0] = tab.length;
ENG.func.log('clone=' + PERF.getTime());
tab = ENG.func.filterWords(tab,ENG.fw.data.filter);
ENG.cr.data.rows[0] = tab.length;
ENG.func.log('fw=' + PERF.getTime());
tab = ENG.func.filterMultiSorts(tab,ENG.fms.data.filter);
ENG.cr.data.rows[0] = tab.length;
ENG.func.log('fms=' + PERF.getTime());
tab = ENG.func.filterRows(tab,ENG.fr.data.filter);
ENG.cr.data.rows[0] = tab.length;
ENG.func.log('fr=' + PERF.getTime());
if (uniq)	// unique word in cols for colswidth
	{
	ENG.cr.data.uniq = arrayUniq2(tab);	//for faster colwidth
	ENG.func.log('uniq=' + PERF.getTime());
	}
tab = ENG.func.filterValues(tab);	// change index to value text
ENG.cr.data.rows[0] = tab.length;
ENG.func.log('val=' + PERF.getTime());
return tab;
}


ENG.func.tableShow = function()
{
var tab;
ENG.func.log(null,true);
tab = ENG.func.doFilters(true);
//var str = '';
//str = (tab.length>0 ? '' : '0 radku') + ENG.func.renderTable(tab,{table:ENG.cfg.pref+'table'});
//ENG.func.log('r5=' + PERF.getTime());
//ENG.obj.table.innerHTML = str;
//ENG.obj.table.innerHTML = 
//ENG.tpl.x +
//(tab.length>0 ? '' : '0 radku') + ENG.func.renderTable(tab,{table: ENG.obj.tab_div, class:ENG.cfg.pref+'table'});
ENG.data.tab = tab;
tab = ENG.edit.func.doFiltersQuery(tab);
ENG.func.log('edit=' + PERF.getTime());
ENG.func.renderTable(tab,{
	'tab_div': ENG.obj.tab_div, 
	'class'  : ENG.cfg.pref+'table', 
	'onclick': 'return ENG.func.onTableClick(event);'
//	'onblur':  'return ENG.func.onTableBlurClick(event);'
	});
ENG.func.log('render=' + PERF.getTime());
//alert([ENG.data.ignore.colsWidth==true, ENG.fr.data.filter.toSource(),ENG.fr.data.old.toSource()])
if (ENG.cr.data.ignore==true && ENG.fr.data.filter.start==ENG.fr.data.old.start && ENG.fr.data.filter.end==ENG.fr.data.old.end)
	{
	}
else	{
	ENG.cr.func.colsWidth(ENG.cr.data.uniq);
	ENG.func.log('colsWidth=' + PERF.getTime());
	}
ENG.cr.data.ignore = false;
ENG.fr.data.old = {};
ENG.fr.data.old.start = ENG.fr.data.filter.start;
ENG.fr.data.old.end   = ENG.fr.data.filter.end;
//ENG.func.colsWidth(ENG.obj.table);
//ENG.func.colsWidth(tab);
//ENG.func.log('colsWidth=' + PERF.getTime());
//ENG.func.navShow(tab.length,ENG.db.map.length);
//alert(getColWidth(ENG.obj.table.getElementsByTagName('TABLE')[0]).toSource());
if (ENG.data.x)
{
var table = document.querySelector('#zas2_panel_table table');
//alert(getColWidth(table).toSource());
}
ENG.ip.func.show();
}


	



ENG.cr.func.strRows = function()
{
return ENG.cr.data.rows.join(' / ');
}

ENG.cr.func.colToRendered = function (i)
{
//return isExist(ENG.data.cols[i]) ? ENG.data.cols[i].rendered_id : -1;
return isSet(ENG.cr,'data') && isSet(ENG.cr.data,'cols') && isSet(ENG.cr.data.cols,i) && isSet(ENG.cr.data.cols[i],'rend_id') ? ENG.cr.data.cols[i].rend_id : -1;
}

ENG.cr.func.colFromRendered = function (i)
{
//return isExist(ENG.data.rendered_cols[i]) ? ENG.data.rendered_cols[i].id : -1;
return isSet(ENG.cr,'data') && isSet(ENG.cr.data,'rend') && isSet(ENG.cr.data.rend,i) && isSet(ENG.cr.data.rend[i],'id') ? ENG.cr.data.rend[i].id : -1;
}

ENG.cr.func.colsWidth = function(uniq)	//table
{
// FF - text in canvas is faster than table TD
var i,j,values,upd,y, li, lj, w, width, font0, font1, left, start, w_fw_chbox_scroll, butt, str, w_fms_arrow, w_min, w_min2, bool_edit, col_row_id, w_min_fms, header;
var l,ll;
start = 4;
w_fms_td_triangle = 13;
//butt = 15;
w_fw_chbox_scroll = 40;
border = 0 + 5.6; // bor + 2x padding
font0 = "bold 11.2px arial";
font1 = "12.8px arial";
w_fms_th_arrow = 5+11+3; //or 10 + mezery okolo
w_min = 30;
w_min_fms = w_min - w_fms_th_arrow;
width = 0;
//col_row_id  = isExist(ENG.cfg.col_id) ? ENG.cfg.col_id : 0;
col_row_id  = ENG.cfg.col_row_id;
//values = ENG.data.tab;
values = ENG.db.values;
upd    = ENG.edit.query_db['update'];
header = ENG.db.keys;
bool_edit = isSet(ENG,'edit') && isSet(ENG['edit'],'update') && ENG['edit']['update'].length>0;
li = header.length;
//alert(ENG.data.cols.toSource())
left = start;
lk = upd.length;
ll = ENG.db.values.length;	//upd[0].length, protoze update je prazdne, na zacatku
for (i=0;i<li;++i)	//sloupce
	{
	w_min2 = i!=ENG.cfg.col_row_id ? w_min_fms : w_min;	// korekce pro sloupec 'id' bez sipecky
	id = ENG.cr.func.colToRendered(i);
	if (id<0) {continue;}
	w  = canvasTextWidth(header[i], font0);
	w += w_fms_td_triangle;
	width = w;
	width = width<w_min ? w_min : width;
	lj = uniq[i].length;
	// prochazi vsechna ruzna slova, ktera mohou ve sloupci byt
	for (j=0;j<lj;++j)	//radky
		{
		if (!isExist(uniq[i][j]))	//x y
			{continue;}
		str   = values[i][j];	//y x
		w     = canvasTextWidth(str, font1);
		width = width<w ? w : width;
		// pridej vsechno v update (protoze nevim seznam radku, jen slova)
		if (bool_edit)
			{
			for(k=0;k<lk;k++)	// radky update
				{
				str   = upd[k][i];
				w     = canvasTextWidth(str, font1);
				width = width<w ? w : width;
				}
			}
		}
	width -= Math.floor(width)>>7;	// korekce, dlouhe pole zkrati
	pos    = {
		'left' : Math.floor(left),
		'width': Math.floor(width)
		};
	ENG.cr.data.rend[id].pos = pos;
//ENG.func.log('i/width=' + i + ' / ' + width + ' ' + left);
	left  += width + border;
	}
//rows[i][col_row_id]
//alert(ENG.data.rendered_cols[3].pos.toSource())
}
/*
// FF - text in canvas is faster than table TD
var i,j,x,y, li, lj, w, ww, font0, font1, left, start, chbox_scroll, butt, str;
start = 4;
butt = 13;
chbox_scroll = 40;
border = 1 + 5.6; // bor + 2x padding
font0 = "bold 11.2px arial";
font1 = "12.8px arial";
ww = 0;
x = ENG.db.values;
z = ENG.db.keys;
li = z.length;
//alert(ENG.data.cols.toSource())
left = start;
for (i=0;i<li;++i)
	{
	id = isExist(ENG.data.cols[i]) ? ENG.data.cols[i].rendered_id : -1
	if (id<0) {continue;}
	w = getTextWidth(z[i], font0);
	w+=butt;
	ww = w;
//	y = x[i];
	lj = tab.length;
	for (j=0;j<lj;++j)
		{
		str = x[i][tab[j][i]];
		w = getTextWidth(str, font1);
		ww = ww<w ? w : ww;
		}
	pos = {'left':left, 'width':ww};
	ENG.data.rendered_cols[id].pos = pos;
//ENG.func.log('i/ww=' + i + ' / ' + ww + ' ' + left);
	left += ww + border;
	}
---
	for (j=0;j<lj;++j)
		{
		str = y[j]
		w = getTextWidth(y[j], font1);
		ww = ww<w ? w : ww;
		}
*/
/*
var trs, tds, i, li, pos;
trs = table.getElementsByTagName('TR');
if (!trs || trs.length==0) {return;}
tds = trs[0].getElementsByTagName('TH');
if (!tds || tds.length==0) {return;}
li = tds.length;
pos = {};
for (i=0;i<li;++i)
	{
	pos = {'left':tds[i].offsetLeft, 'width':tds[i].offsetWidth};
	ENG.data.rendered_cols[i].pos = pos;
	}
*/
/*
ENG.func.navShow = function(a,b)
{
var str;
str  = '';
str += a + ' / ' + b;
ENG.obj.navtop.innerHTML = str;
ENG.obj.navbottom.innerHTML = str;
}
*/

ENG.func.filterWords = function(tab,filters)
{
if (filters.length===0) {return tab;}
//return tab;
var i,j,k,x,y,out,tmp,l, row, reg, val, key, bool1, bool2, multi_cols, cols;
out = [];
multi_cols = ENG.fw.data.multi_cols;
if (!multi_cols)
	{
	multi_cols = [];
	row   = tab[0];
	for (j=0; j<row.length; j++)
		{
		multi_cols[j] = [j];
		}	
	}
//alert(tab.length)
//alert(multi_cols[1])
for (i=0; i<tab.length; i++)
	{
	bool1 = true;
	row   = tab[i];
//		ENG.func.fwCmpOr(row,filters,cols);
	for (ii=0; ii<multi_cols.length; ii++)
		{
		cols = multi_cols[ii];
//alert(cols)
		bool1 &= ENG.fw.func.cmpOr(row,filters,cols);
/*
	for (j=0; j<row.length; j++)
		{
		if (isSet(filters,j) && filters[j]!=null)
			{
			filter = filters[j];
//alert(filter.toSource())
//				bool2 = true;
			for (k=0; k<filter.length; k++)	// filtry na slova jsou v negaci
				{
				if (isSet(filter,k) && filter[k]!==null)
					{
//						if (filter[j]===row[j]) {bool2 = false; break;}
					if (filter[k]===row[j]) {bool1 = false; break;}
					}
				}
//			bool1 &= bool2;
//			if (bool1==false) {break;}
			if (bool1==false) {break;}
			}
*/
		if (bool1==false) {break;}
		}
	if (bool1==true)
		{
		out[out.length] = row;
		}
	}
return out;
}

ENG.func.filterMultiSorts = function(tab,cols_sort)
{
var i,c,cols_func;
if (cols_sort.length<=0) {return tab;}
cols_func = [];
for (i in cols_sort)
	{
	c = cols_sort[i];
	c.func = compare_func[c.order][c.type];
	cols_func[i] = c;
	}
//alert(tab)
ENG.fms.data.cols_func = cols_func;
//alert(tab);
tab.sort(ENG.fms.func.cmpRows);
//alert(tab);
return tab;
}

ENG.func.filterRows = function(tab, filter)
{
//alert(filter.toSource())
var start, end;
out   = [];
start = filter.start * 1;
start = start<0 ? 0 : (start>tab.length-1 ? tab.length-1 : start);
end   = filter.end * 1;
end   = end>tab.length-1 ? tab.length-1 : (end<start ? start : end);
end++;
if (end-start == tab.length)
	{return tab;}
//alert ([start,end]);
return arrayClone2(tab,start,end);
}


ENG.func.filterValues = function(tab)
{
//return tab;
var i,j,val;
//alert(tab)
for (i=0; i<tab.length; ++i)
	{
	row = tab[i];
	for (j=0; j<row.length; ++j)
		{
//		tab[i][j] = ENG.db.values[row[j]] ? ENG.db.values[row[j]] : '';
		val = row[j];
		tab[i][j] = ENG.db.values[j] && ENG.db.values[j][val] ? ENG.db.values[j][val] : '';
		}
	}
return tab;
}

ENG.func.renderTable = function(data, opt)
{
var i, j, tbody, thead, row, rows, col_row_id, tr_class, id, start, end, start2, end2, bool_edit, tpl,k, lk,table, bool_ignore;
var sss = '';
tbody = '';
tpl    = ENG.tpl;
row    = data.length>0 ? data[0] : [];
start  = 0;
end    = data.length;
start2 = 0;
end2   = row.length;
//bool_EE = typeof(EE)!='undefined' && EE.query.length>0;
bool_edit = isSet(ENG,'edit');
//bool_ignore = isExist(ENG.cr) && ENG.cr.data.ignore==true;
//alert('edit')
//col_row_id  = isExist(ENG.cfg.col_id) ? ENG.cfg.col_id : 0;
col_row_id  = ENG.cfg.col_row_id;
remove = [];
for(i in ENG.fc.data.remove)
	{
	value = ENG.fc.data.remove[i];
	remove[value] = true;
	}
i = start;
//ENG.func.log('r1=' + PERF.getTime());
tr_class = '';
tr_title = '';
while(i<end)
//for (i=start; i<end; i++)
	{
//if (i>30) break;
//	if (data[i].length==0)	//edit-engine deleted row
//		{continue;}
	row = data[i];
//	tr_class = '';
	if (bool_edit)	// edit-engine
		{
		tr_class = ENG.edit.func.trClassCheck(col_row_id,row[col_row_id]);
		tr_title = ' title="'+row[col_row_id]+'"';
		}
	tbody += "\n"+'<tr'+ tr_class + tr_title +'>';	//no-edit tr_class = '', tr_title = ''
//	tbody += '<th>'+i+'<\/th>';
//	for (j=start2; j<end2; j++)
	j = start2;
	while (j<end2)
		{
		if (!isExist(remove[j]))
			{
			if (j!==ENG.fc.data.col_row_id)
				{
				tbody += '<td>' + row[j] + '<\/td>';	// dramaticky zvysuje time renderovani
//				tbody += render(tpl.tbody_td,{value:row[j]});
				}
			else	{
				tbody += '<th>' + row[j] + '<\/th>';
				}
			}
		++j;
		}
	tbody += '<\/tr>';
	++i;
	}
//tbody+= '<pre>'+sss+'</pre>';
//if (tbody!='')
//	{
//ENG.func.log('r2=' + PERF.getTime());
thead  = "\n"+'<tr>';
row = ENG.db.keys;
//	thead += '<th>&nbsp;<\/th>';
//	for (i=1; i<row.length; i++)
//	for (i=1; i<row.length; i++) //no-edit
i = 0;
j = start2;
//ENG.data.rendered_cols = [];
if (!isArray(ENG.cr.data.cols))
	{
	ENG.cr.data.cols = [];
	}
while (j<end2)			//no-edit
	{
	ENG.cr.data.cols[j] = {};
	ENG.cr.data.cols[j].rend_id = -1;
	if (!isExist(remove[j]))
		{
		ENG.cr.data.cols[j].rend_id = i;
		if (!isObject(ENG.cr.data.rend[i]))
			{
			ENG.cr.data.rend[i]    = {};
			}
//		ENG.cr.data.rend[i]    = {};
		ENG.cr.data.rend[i].id = j;
		if (j!==ENG.fc.data.col_row_id)
			{
//			thead += render(ENG.tpl.table_th,{key:j,value:row[j],onclick:'ENG.fw.func.filterOpenClick('+j+',this);'});
			thead += render(tpl.thead_th,{key:j,value:ENG.fms.func.thValue(j),onclick:'ENG.fms.func.filterChangeClick('+j+',this);'});
			}
		else	{
			thead += render(tpl.thead_th,{key:j,value:row[j],onclick:''});
			}
		++i;
		}
//'<th class="filter"><span onclick="ENG.func.filterOpenClick(this,'+i+');">[+] ' + row[i] + '<\/span><\/th>';
	++j;
	}
thead += '<\/tr>';
//	}
//ENG.func.log('r3=' + PERF.getTime());
//var t='';
//t =  render(tpl.table,{class:css.table, thead:thead, tbody:tbody});
//ENG.func.log('r4=' + PERF.getTime());
table = ENG.tpl.x +
	(end-start>0 ? '' : '0 radku') + 
	render(tpl.table,{'class':opt.class, 'thead':thead, 'tbody':tbody, 'onclick': opt.onclick});//, 'onblur': opt.onblur
if (!isSet(opt,'tab_div'))
	{return table;}
//ENG.obj.table.innerHTML = 
opt.tab_div.innerHTML = table;
}

ENG.func.exportCsv = function()
{
//str = "ah\"oj";
//str = "ah\n\
//oj";
//str = "ah;oj";
//str = "ahoj";
//str = ENG.func.escapeCsvValue(str);
//alert(str)
var tab;
tab = ENG.func.doFilters(false);
newWindowPlainText('csv_file',CSV.export(tab));
}


// --- FW plugin functions

ENG.fw.func.init = function(pref)
{
ENG.fw.obj.all    = objGet(pref+'panel_fw');
ENG.fw.data.filter = [];
ENG.fw.data.multi_cols = false;	//false or [[1],[2],[3],[4],[5],[6],[7],[8]] or [[1],[2,3,4],[5,6,7,8]]
ENG.fw.tpl.all = '<div class=count>{count}<\/div> ' + "\n" + '<div class="filter"><table class="filter">{data}<\/table><\/div>';
ENG.fw.tpl.row = "\n"+'\
<tr{class}>\
<td><input type="checkbox" name="{name}"  id="{id}" value="{value}"{check} onclick="{onclick}"><\/td>\
<td><label for="{id}">{text}<\/label><\/td>\
<\/tr>\
';
}

ENG.fw.func.update = function(key1, key2, value)
{
if (!isSet(ENG.fw.data.filter,key1))
	{
	ENG.fw.data.filter[key1] = [];
	}
ENG.fw.data.filter[key1][key2] = value && isSet(ENG.db.filters[key1],key2) ? ENG.db.filters[key1][key2] : null;
}

ENG.fw.func.create = function(show)
{
var i, str, id, name, data1, data2, value, check, db_filters, tpl, checkedobj2, key;
show = typeof(show)!='undefined' ? show : true;
obj2 = ENG.fw.obj.all;
key  = ENG.fw.data.key;
//alert(key)
ENG.fw.data.opened = key;
db_filters   = ENG.db.filters[key];
user_filters = ENG.fw.data.filter;
tpl = ENG.fw.tpl;
//if (typeof(filters_words[key])!='undefined' && filters_words[key]!=null)
//	{
//	data1 = filters_words[key]
//	}
//else	{
//	data1 = db_filters[key];
//	}
str = '';
data2 = [];
checked = 0;
for (i=0; i<db_filters.length; i++)
	{
	check = true;
	if (isSet(user_filters,key) && isSet(user_filters[key],i) && user_filters[key][i]!=null)
		{check = false;}
	id    = ENG.cfg.pref+"ch_"+i;
	name  = ENG.cfg.pref+"ch[]";
	value = db_filters[i];
//	data2[data2.length] = {class:'',check:check==true?' checked="checked"':'', name:name, id:id, key1:key, key2:i, value:value, text:ENG.db.values[value]};
	data2[data2.length] = {class:'',check:check==true?' checked="checked"':'', name:name, id:id, key1:key, key2:i, value:value, text:ENG.db.values[key][value], onclick:'ENG.fw.func.filterCheckClick(this,'+key+','+i+');'};
	if (check==true) {checked++;}
	}
//data2.sort( function(a,b){return a.text>b.text;} );
data2.sort( function(a,b){return compare_func.asc[ENG.db.structure[key]](a.text,b.text);} );
for (i=0; i<data2.length; i++)
	{
	str += render(tpl.row,data2[i]);
	}
var pos, rend_key;
//rend_key = isSet(ENG.data.cols,key) && isSet(ENG.data.cols[key],'rendered_id') ? ENG.data.cols[key].rendered_id : -1;
rend_key = ENG.cr.func.colToRendered(key);
//isSet(ENG.data.cols,key) && isSet(ENG.data.cols[key],'rendered_id') ? ENG.data.cols[key].rendered_id : -1;
if (rend_key<0)
	{return;}	// chyba, nema render key, coz by mel mit, kdyz se na nej kliklo
pos = ENG.cr.data.rend[rend_key].pos;
//ENG.fw.data.left  = pos.left;
//ENG.fw.data.width = pos.width + 23;	//22 checkbox, scrollbar, space
//obj2.style.marginLeft = ENG.fw.data.left + 'px';
//obj2.style.width = ENG.fw.data.width + 'px';
//obj2.style.marginLeft = ENG.fw.data.left + 'px';
//obj2.style.width = ENG.fw.data.width + 'px';
//ENG.fw.data.width = pos.width;	//22 checkbox, scrollbar, space
//obj2.style.width = ENG.fw.data.width + 'px';
obj2.style.marginLeft = (pos.left +5) + 'px';
obj2.innerHTML   = render(tpl.all,{count:checked + ' / ' + db_filters.length, data:str});
toggle(obj2,show);
//obj2.style.display = show ? 'block' : 'none';
// (id='+key+')
}

ENG.fw.func.cmpOr = function(row,filters,cols)
{
var bool0, bool1, col;
bool0 = false;
//bool1 = true;
//row   = tab[i];
for (j=0; j<cols.length; j++)
	{
	bool1 = true;
	col = cols[j];
	if (isSet(filters,col) && filters[col]!=null)
		{
		filter = filters[col];
//alert(filter.toSource())
//		bool2 = true;
		for (k=0; k<filter.length; k++)	// filtry na slova jsou v negaci
			{
			if (isSet(filter,k) && filter[k]!==null)
				{
//				if (filter[j]===row[j]) {bool2 = false; break;}
				if (filter[k]===row[col]) {bool1 = false; break;}
				}
			}
//		bool1 &= bool2;
//		if (bool1==false) {break;}
		}
	bool0 |= bool1;
	}
return bool0;
}

ENG.fw.func.filterCheckClick = function(obj, key1, key2)
{
ENG.fw.func.update(key1,key2,!obj.checked);
//alert([key1,key2]);
//var pos = ENG.data.rendered_cols[key1].pos;
//ENG.fw.data.left = pos.left;
//ENG.fw.data.width = pos.width;
ENG.func.tableShow();
ENG.fw.func.create();
ENG.ss.func.create();
}

ENG.fw.func.filterOpenClick = function(key, obj1)
{
var obj1,obj2, bool, col, pos, rend_key;
if (!obj1)
	{
	col  = ENG.cr.data.rend[key];
	key  = col.id;
	obj1 = {offsetLeft:col.pos.left, offsetWidth:col.pos.width};
	}
else	{
	obj1 = obj1.parentNode;
	}
//ENG.func.ipShow();
obj2 = ENG.fw.obj.all;
bool = !(ENG.fw.data.opened>=0 && ENG.fw.data.opened==key)
bool = toggle(obj2,bool);
ENG.fw.data.opened = -1;
if (bool==false) {return;}
ENG.fw.data.key   = key;
//ENG.fw.data.left  = obj1.offsetLeft;
//ENG.fw.data.width = obj1.offsetWidth + 22;	//22 checkbox, scrollbar, space
//rend_key = ENG.data.cols[key].rendered_id;
//alert(rend_key)
//if (rend_key<0)
//	{return;}	// chyba, nema render key, coz by mel mit, kdyz se na nej kliklo
//pos = ENG.data.rendered_cols[rend_key].pos;
//ENG.fw.data.left  = pos.left;
//ENG.fw.data.width = pos.width + 22;	//22 checkbox, scrollbar, space
ENG.fw.func.create();
}


// --- FR plugin func ---

ENG.fr.func.init = function(pref)
{
ENG.fr.obj.id.all   = pref+'panel_fr';
ENG.fr.obj.id.form  = pref+'form_fr';
ENG.fr.obj.id.start = pref+'fr_start';
ENG.fr.obj.id.end   = pref+'fr_end';
ENG.fr.obj.all      = objGet(ENG.fr.obj.id.all);
ENG.fr.data.old     = {'start':-1, 'end':-1};	// for first colwidth
ENG.fr.data.filter  = {'start':0, 'end':ENG.db.map.length};	// start, endt
ENG.fr.tpl.all      = '<form name="{name}">{filter}<\/form>';
ENG.fr.tpl.input    = '<label>{label} <input type="text" name="{name}" value="{value}"><\/label>';
ENG.fr.tpl.button   = '<input type="button" value="Pouzit" onclick="{onclick}">';
}

ENG.fr.func.filterOpenClick = function()
{
var bool, str, tpl, names, filter;
bool = toggle(ENG.fr.obj.all);
if (bool)
	{
	names  = ENG.fr.obj.id;
	filter = ENG.fr.data.filter;
	tpl    = ENG.fr.tpl;
	str  = '';
	str += render(tpl.input,{'label':names.start,'name':names.start,'value':filter.start});
	str += render(tpl.input,{'label':names.end  ,'name':names.end  ,'value':filter.end});
	str += render(tpl.button,{'onclick':'ENG.fr.func.filterCloseClick();'});
	ENG.fr.obj.all.innerHTML = render(tpl.all,{'name':names.form,'filter':str});
	return;
	}
ENG.fr.func.filterCloseClick();
}

ENG.fr.func.filterCloseClick = function()
{
var form, names, filter;
names = ENG.fr.obj.id;
form  = document.forms[names.form];
if (form)
	{
	filter = ENG.fr.data.filter;
	filter.start = isSet(form,names.start) ? form[names.start].value * 1 : filter.start;
	filter.end   = isSet(form,names.end)   ? form[names.end].value * 1   : filter.end;
	ENG.fr.data.filter = filter;
	}
//alert(ENG.filters_rows.toSource())
toggle(ENG.fr.obj.all, false);
ENG.func.tableShow();
}

/*
k = 0;
for (i=start; i<count; ++i)
	{
//	row = tab[i];
//	out[k] = [];
//	for (j=0; j<row.length; j++)
//		{
//		out[k][j] = ENG.db.values[row[j]] ? ENG.db.values[row[j]] : '';
//		}
//	out[k] = row;
	out[k] = tab[i];
	++k;
	}
return out;
}
*/


// --- FMS plugin func ---

//&;
//
//&;
//&#9651;
ENG.fms.func.init = function(pref)
{
ENG.fms.obj.id.all           = pref+'panel_fms';
ENG.fms.obj.id.fms_area      = pref+'fms_area';
//ENG.fms.obj.id.fms_select_div    = [];
//ENG.fms.obj.id.fms_select_div[0] = pref+'fms_tbl_select0_div';
//ENG.fms.obj.id.fms_select_div[1] = pref+'fms_tbl_select1_div';
//ENG.fms.obj.id.fms_select_div[2] = pref+'fms_tbl_select2_div';
ENG.fms.obj.id.fms_select    = [];
ENG.fms.obj.id.fms_select[0] = pref+'fms_tbl_select0';
ENG.fms.obj.id.fms_select[1] = pref+'fms_tbl_select1';
ENG.fms.obj.id.fms_select[2] = pref+'fms_tbl_select2';
ENG.fms.obj.all = objGet(ENG.fms.obj.id.all);
ENG.fms.data.filter = [
	{col:5, type:'str', order:'asc'}
	//{col:2, type:'str', order:'desc'},
	//{col:1, type:'str', order:'asc'}
	/*
	{col:2, type:'str', order:'desc'},
	{col:1, type:'str', order:'asc'}
	*/
	//{col:3, type:'str', order:'desc'},
	//{col:6, type:'str', order:'asc'}
	];
ENG.fms.data.example = [		// col_id, col_type, order
	{col:0 , type:ENG.db.structure[0] , order:'desc'},
	{col:17, type:ENG.db.structure[17], order:'asc'}
	];
//ENG.filters_reg = [
//[4,'3.'],
//[5,'tp']
//];
ENG.fms.tpl.all = "\n"+'\
<form name="{name}">\
  <table>\
    <tr>\
      <td rowspan=2>\
        <textarea cols=50 rows=6 id="{area_id}"><\/textarea>\
      <\/td>\
      <td>\
        <table>\
          <tr>\
            <td>{div0}<\/td>\
            <td>{div1}<\/td>\
            <td>{div2}<\/td>\
            <td><input type="button" value="Add" onclick="{add_onclick}"><\/td>\
          <\/tr>\
        <\/table>\
      <\/td>\
    <\/tr>\
    <tr>\
      <td>\
        <input type="button" value="Pouzit"  onclick="{update_onclick}">\
        <input type="button" value="Priklad" onclick="{example_onclick}">\
      <\/td>\
    <\/tr>\
  <\/table>\
<\/form>\
';
ENG.fms.tpl.order = '<span class="{class}">{value}<\/span>';
ENG.fms.tpl.fms0  = "\n"+'\
<option value="{value}"{check}>{text}<\/option>\
';
ENG.fms.tpl.fms1  = "\n"+'\
<select name="{name}" id="{id}">{data}<\/select>\
';
}

ENG.fms.func.thValue = function(col)
{
var filter, text, order, css, order_all, css_all;
order_all = ['&#9651;', '&#9650;', '&#9660;'];
css_all   = ['order none', 'order asc', 'order desc'];
text   = ENG.db.keys[col];
filter = ENG.fms.func.find(col);
order  = filter ? filter.order : '';
order  = order=='' ? 0 : (order=='desc' ? 2 : 1);
css    = css_all[order];
order  = order_all[order];
text  += ' ' + render(ENG.fms.tpl.order,{'class':css,'value':order});
return text;
}

ENG.fms.func.find = function(col)
{
var i, li, filters;
filters = ENG.fms.data.filter;
li = filters.length;
for (i=0;i<li;i++)
	{
	if (filters[i].col==col)
		{return filters[i];}
	}
return false;
}

ENG.fms.func.filterChangeClick = function(col,el)
{
var filter;
ENG.cr.data.ignore = true;
filter = ENG.fms.func.find(col);
var str ='';
str += filter.toSource()
str += "\n\n";
//alert(ENG.db.structure[col])
if (filter!=false)
	{filter.order = filter.order!='asc' ? 'asc' : 'desc';}
else	{
	filter = {'col':col, 'type':ENG.db.structure[col], 'order':'asc'};
	}
str += filter.toSource()
//alert(str)
//ENG.fms.data.filter = [filter];
//ENG.fms.func.select();
ENG.fms.func.update([filter]);
}

ENG.fms.func.cmpRows = function (a,b)
{
var i,c,d, aa, bb, cols_func;//,x;
//x=[];
cols_func = ENG.fms.data.cols_func;
for (i in cols_func)
	{
	c = cols_func[i];
	aa = a[c['col']];
	bb = b[c['col']];
//x=[aa,bb]
//	aa = ENG.db.values[aa];
	aa = ENG.db.values[c['col']][aa];
//if (typeof(aa)=='undefined') alert(x)
//	bb = ENG.db.values[bb];
	bb = ENG.db.values[c['col']][bb];
	d = c['func'](aa,bb);
//if (i==0 && aa!=='ch' && aa!=='1' && aa!=='' && aa!==bb) alert([aa,bb,c['col'],d,c['func']])
	if (d!=0) {return d;}
	}
return 0;
}

ENG.fms.func.convert = function(arr)
{
var arr2, i, str;
arr2 = [];
if (isArray(arr))
	{
	for (i=0;i<arr.length;i++)
		{
		arr2[arr2.length] = "{col:" + arr[i].col + ", type:'" + arr[i].type + "', order:'" + arr[i].order + "'}";
		}
	}
str = (arr2.length>0) ? "\n"+arr2.join(",\n") : '';
return '[' + str + "\n]";	// + [arr2.length, arr.length].join('|')
}

ENG.fms.func.convertBack = function(str)
{
try {eval(str);} catch (e) {return [];}
//alert([eval(str),str])
return eval(str) || [];
}

ENG.fms.func.select = function()
{
ENG.fms.obj.area.value = ENG.fms.func.convert(ENG.fms.data.filter);
}

ENG.fms.func.update = function(value)
{
ENG.fms.data.filter = !value ? ENG.fms.func.convertBack(ENG.fms.obj.area.value) : value;
toggle(ENG.fms.obj.all,false);
ENG.func.tableShow();
}

ENG.fms.func.filterOpenClick = function()
{
toggle(ENG.fms.obj.all);
ENG.ip.func.show();
ENG.fms.func.select();
}

ENG.fms.func.addClick = function()
{
var pref, arr, names;
//pref = ENG.cfg.pref;
names = ENG.fms.obj.id.fms_select;
arr  = {col:getSel(objGet(names[0])) * 1, type:getSel(objGet(names[1])), order:getSel(objGet(names[2])) };
ENG.fms.data.filter = ENG.fms.func.convertBack(ENG.fms.obj.area.value);
ENG.fms.data.filter[ENG.fms.data.filter.length] = arr;
ENG.fms.obj.area.value = ENG.fms.func.convert(ENG.fms.data.filter);
}

ENG.fms.func.exampleClick = function()
{
ENG.fms.obj.area.value = ENG.fms.func.convert(ENG.fms.data.example);
//ENG.func.fmsUpdate();
}

ENG.fms.func.create = function(obj,param,data)
{
var i, str, tpl0, tpl1;
tpl0 = ENG.fms.tpl.fms0;
tpl1 = ENG.fms.tpl.fms1;
str = '';
for (i=0; i<data.length; i++)
	{
	str += render(tpl0,data[i]);
	}
param.data = str;
return render(tpl1,param);
}

ENG.fms.func.createAll = function()
{
var i, data1, data2, out, name, names, divs;
id = ENG.fms.obj.id;
divs = [];
names = ENG.fms.obj.id;
//divs  = ENG.fms.obj.fms_select_div;
out = ['','',''];
data1 = ENG.db.keys;
data2 = [];
for (i=0;i<data1.length;i++)
	{
	data2[data2.length] = {value:i, text:data1[i], check:''};
	}
pref = ENG.cfg.pref;
name    = names.fms_select[0];
divs[0] = ENG.fms.func.create(null, {id:name, name:name}, data2);
data1   = compare_func.asc;
data2   = [];
for (i in data1)
	{
	data2[data2.length] = {value:i, text:i, check:''};
	}
//data2.sort( function(a,b){return a.text>b.text;} );
name    = names.fms_select[1];
divs[1] = ENG.fms.func.create(null, {id:name, name:name}, data2);
data1   = compare_func;
data2   = [];
for (i in data1)
	{
	data2[data2.length] = {value:i, text:i, check:''};
	}
//data2.sort( function(a,b){return a.text>b.text;} );
name    = names.fms_select[2];
divs[2] = ENG.fms.func.create(null, {id:name, name:name}, data2);
ENG.fms.obj.all.innerHTML = render(ENG.fms.tpl.all,{
	area_id: names.fms_area,
	div0: divs[0],
	div1: divs[1],
	div2: divs[2],
	add_onclick    : "ENG.fms.func.addClick();",
	update_onclick : "ENG.fms.func.update();",
	example_onclick: "ENG.fms.func.exampleClick();"
	});
ENG.fms.obj.area = objGet(names.fms_area);
}


// --- FC plugin func, filter cols ---

ENG.fc.func.init = function(pref)
{
ENG.fc.data.remove      = isArray(ENG.fc.data.remove) ? ENG.fc.data.remove : [];
ENG.fc.data.add        *= 1; // convert to number // add nevyuzivam
ENG.fc.data.col_row_id *= 1;
}

// --- IP plugin func ---

ENG.ip.func.init = function(pref)
{
ENG.ip.obj.all = objGet(pref+'panel_info');
//ENG.ip.tpl.all     = '<div class="edit">{edit}<\/div><div class="filters">{filters}<\/div>';
ENG.ip.tpl.all     = '<div class="filters">{filters}<\/div>';
ENG.ip.tpl.filters = '{filters} (filtry fc, fw, fms, fr)';
//ENG.ip.tpl.edit    = "{edit}";
ENG.ip.tpl.butt    = '<span class="butt hover" onclick="{onclick}" title="javascript: {title}">{text}{stav}<\/span>';
}

ENG.ip.func.show = function()	//info panel
{
var tpl, str, s, stav,text, out_filters, out_edit, butt;
//ENG.TPL.ip.fw = 'sloupce'
//ENG.TPL.ip.fms = 'serazeni'
//ENG.TPL.ip.fr = 'radky'
//ENG.TPL.ip.q = 'query'
if (ENG.ip.obj.all)
	{
	tpl  = ENG.ip.tpl;
	stav = [' <span style="color:#d00;">',' <span style="color:#080;">','<\/span>','vypnuto','zapnuto'];
	out_filters  = 'Data Js: ';
	s = ENG.fc.data.remove.length == 0 ? 0 : 1;
	text = s==0?'*':stav[s+3];
	butt = {'text': 'SELECT'  ,'stav': stav[s]+text+stav[2],'onclick': 'alert(ENG.fc.data.remove.toSource());'};
	butt.title = escapeHtml(butt.onclick);
	out_filters += "\n" + render(tpl.butt,butt) + ', ';
	s = ENG.fw.data.filter.length == 0 ? 0 : 1;
	text = stav[s+3];
	butt = {'text': 'WHERE'    ,'stav': stav[s]+text+stav[2],'onclick': 'alert(ENG.fw.data.filter.toSource());'};
	butt.title = escapeHtml(butt.onclick);
	out_filters += "\n" + render(tpl.butt,butt) + ', ';
	s = ENG.fms.data.filter.length == 0 ? 0 : 1;
	text = stav[s+3];
	butt = {'text': 'ORDER BY','stav': stav[s]+text+stav[2],'onclick': 'ENG.fms.func.filterOpenClick();'};
	butt.title = escapeHtml(butt.onclick);
	out_filters += "\n" + render(tpl.butt,butt) + ', ';
	s = !(ENG.fr.data.filter.start==0 && ENG.fr.data.filter.end==ENG.db.map.length) == 0 ? 0 : 1;
	text = ENG.fr.data.filter.start+','+ENG.fr.data.filter.end+' ('+stav[s+3]+')';
	butt = {'text': 'LIMIT'    ,'stav': stav[s]+text+stav[2],'onclick': 'ENG.fr.func.filterOpenClick();'};
	butt.title = escapeHtml(butt.onclick);
	out_filters += "\n" + render(tpl.butt,butt);
	out_filters += ' | ';
//if (typeof(EE)!='undefined')
//	s = EE.query.length == 0 ? 0 : 1;
//if (typeof(EE)!='undefined')
//	out_filters += "\n" + render(tpl.butt,{'text': 'query'    ,'stav': stav[s],'onclick': "EE.func.queryShow();"}) + ' | ';
	butt = {'text': 'ExportCsv','stav': ''     ,'onclick': "ENG.func.exportCsv();"};
	butt.title = escapeHtml(butt.onclick);
	out_filters += "\n" + render(tpl.butt,butt);
//if (typeof(EE)!='undefined')
//	out_filters += "\n" + render(tpl.butt,{'text': 'ExportSql','stav': ''     ,'onclick': "EE.func.exportSql();"});
//	if (typeof(ENG.edit)!='undefined')
//		{
//		out_edit  = "Changes Sql: ";
//		text = ENG.hist.db.map.length;
//		butt = {'text': 'Download history','stav': ' ('+text+')','onclick': "ENG.hist.func.openClick();"};
//		butt.title = escapeHtml(butt.onclick);
//		out_edit += "\n" + render(tpl.butt,butt) + ', ';
//		text = ( ENG.edit.query_db['update'].length +
//			 ENG.edit.query_db['insert'].length +
//			 ENG.edit.query_db['delete'].length);
//		butt = {'text': 'Upload edit','stav': ' ('+text+')','onclick': "ENG.edit.func.uploadOpenClick();"};
//		butt.title = escapeHtml(butt.onclick);
//		out_edit += "\n" + render(tpl.butt,butt);
/*
		text = ENG.edit.query_db['update'].length;
		butt = {'text': 'UPDATE','stav': ' ('+text+')','onclick': "ENG.edit.func.queryShow('"+'update'+"');"};
		butt.title = escapeHtml(butt.onclick);
		out_edit += "\n" + render(tpl.butt,butt) + ', ';
		text = ENG.edit.query_db['insert'].length;
		butt = {'text': 'INSERT','stav': ' ('+text+')','onclick': "ENG.edit.func.queryShow('"+'insert'+"');"};
		butt.title = escapeHtml(butt.onclick);
		out_edit += "\n" + render(tpl.butt,butt) + ', ';
		text = ENG.edit.query_db['delete'].length;
		butt = {'text': 'DELETE','stav': ' ('+text+')','onclick': "ENG.edit.func.queryShow('"+'delete'+"');"};
		butt.title = escapeHtml(butt.onclick);
		out_edit += "\n" + render(tpl.butt,butt);
		out_edit += ' | ';
		butt = {'text': 'ExportRequest','stav': '','onclick': "ENG.edit.func.exportRequest();"};
		butt.title = escapeHtml(butt.onclick);
		out_edit += "\n" + render(tpl.butt,butt) + ', ';
		butt = {'text': 'Login'       ,'stav': '' ,'onclick': "ENG.edit.func.login();"};
		butt.title = escapeHtml(butt.onclick);
		out_edit += "\n" + render(tpl.butt,butt) + ', ';
		butt = {'text': 'Send changes','stav': '' ,'onclick': "ENG.edit.func.sendChanges();"};
		butt.title = escapeHtml(butt.onclick);
		out_edit += "\n" + render(tpl.butt,butt);
*/
//		}
	ENG.ip.obj.all.innerHTML = render(tpl.all,{
		'filters': render(tpl.filters,{'filters':out_filters})
//		'edit'   : render(tpl.edit   ,{'edit'   :out_edit})
		});
	}
}

// --------

// ---------------
// --- SS plugin func --- // live search filter

ENG.ss.func.init = function()
	{
	var pref, i,li;
//SS.f.data_out = ENG.fw.data;
//	ENG.ss.f.words_index = db_filters;
//	ENG.ss.f.words_value = db_values;
	pref = ENG.cfg.pref;
	ENG.ss.obj.id.all = pref+'search';
	ENG.ss.obj.id.search = pref+'search_';
	ENG.ss.obj.id.search_cmp_type = pref+'search_cmp_type';
	ENG.ss.obj.all    = objGet(ENG.ss.obj.id.all);
//	ENG.ss.data.cmp  = 1;	// i uprostred slova
	ENG.ss.data.cmp  = 0;	// jen na zacatku slova
	//ENG.ss.data.phrase = '';
	ENG.ss.data.phrases = [];
	li = ENG.db.filters.length;
	for (i=0;i<li;i++)
		{
		ENG.ss.data.phrases[i] = '';
		}
	ENG.ss.data.key1 = '';
	ENG.ss.data.key2 = '';
//&#8942; &DoubleDownArrow
	ENG.ss.tpl.fw    = "\n"+'\
<span onclick="{onclick}" class="hover">&nbsp;&DownArrow;&nbsp;<\/span>\
';
	ENG.ss.tpl.td    = "\n"+'\
<th class="col{key1}">\
<input type="text" name="{name}" id="{id}" value="{value}" onkeyup="{onkeyup}" placeholder="{placeholder}" style="{css}">{text}\
<\/th>\
';
	ENG.ss.tpl.radio = "\n"+'\
<label><input type="radio" name="{name}" id="{id}" value="{value}" onclick="{onclick}" {checked}> {text}<\/label>\
';
//{radio}<br>\
	ENG.ss.tpl.table = "\n"+'\
<table class="'+pref+'table">\
<thead>\
<tr>\
{td}\
<\/thead>\
<\/tr>\
<\/table>\
';
	ENG.ss.func.create();
	}

ENG.ss.func.create = function()
	{
	var out,td,radio,i,lj,j, row, width,k,fw,tpl;
	var remove;
	remove = [];
	for(i in ENG.fc.data.remove)
		{
		value = ENG.fc.data.remove[i];
		remove[value] = true;
		}

	out   = '';
	td    = '';
	radio = '';
	row   = ENG.db.keys;
//	for (i=0; i<row.length; i++)
//	cols = [1,2,5];
	cols  = ENG.db.keys;
	name  = ENG.ss.obj.id.search;
//alert(name)
	phrases = ENG.ss.data.phrases;
//alert(ENG.data.cols_info.toSource())
	lj = cols.length;
	k = 0;
	tpl = ENG.ss.tpl;
	for (j=0; j<lj; j++)	//no-edit
		{
//		i = cols[j];
		i = j;
		if (!isExist(remove[j]))
			{
//			width = ENG.data.rendered_cols[k].pos.width - 22;
//			width = ENG.data.rendered_cols[k].pos.width - 16;
			fw    = render(tpl.fw,{
				'onclick': 'ENG.fw.func.filterOpenClick('+k+');'
				});
			td   += render(tpl.td,{
				'key1' : i,
				'name' : name+i,
				'id'   : name+i,
				'value': phrases[i],
//				'value' : ENG.ss.func.inpWidth(k),
				'placeholder': row[i],
				'text' : fw,
				'onkeyup': 'ENG.ss.func.search(this,'+i+');',
//				'css'  : 'min-width:'+ENG.ss.func.inpWidth(k)+'px;'
				'css'  : 'width:'+ENG.ss.func.inpWidth(k)+'px;'
				});

			k++;
			}
		}
//	name = ENG.ss.obj.search_cmp_type;
	i = 0;
//	onclick: ENG.ss.func.searchCmpType(this);
//	radio += render(ENG.ss.tpl.radio,{'name':name,'id':name+i,'value':i,'text':'zacatek vsech slov'   ,'checked':'checked="checked"'}); i++;
//	radio += render(ENG.ss.tpl.radio,{'name':name,'id':name+i,'value':i,'text':'zacatek prvniho slova','checked':''});
	out = render(tpl.table,{'radio':radio,'td':td});
	ENG.ss.obj.all.innerHTML = out;
//	ENG.fw.data.multi_cols = [[1],[2,3,4],[5,6,7,8]];
	}

ENG.ss.func.inpWidth = function(i)
	{
	var c;
	c = ENG.cr.data.rend;
/*
//alert([i,
//isSet(c,i)
//])
alert([
isExist(c) , isSet(c,i) , isObject(c[i].pos) , isExist(c[i].pos.width)
])
*/
//alert((isExist(c) && isSet(c[i]) && isObject(c[i].pos) && isExist(c[i].pos.width)))
	if (!(isExist(c) && isSet(c,i) && isObject(c[i].pos) && isExist(c[i].pos.width)))
		{return false;}
//alert(c[i].pos.width)
//if (i==1) alert(c[i].pos.width)
	return c[i].pos.width - 16;
	}

ENG.ss.func.resize = function()
	{
	var i, li, inps, w;
	inps = ENG.ss.obj.all.getElementsByTagName('INPUT');
	if (!inps || inps.length==0) {return;}
	li  = inps.length;
	for (i=0;i<li;i++)
		{
//alert(tds[i].style.width)
		w = ENG.ss.func.inpWidth(i);
		if (w===false)
			{continue;}
		inps[i].style.width = w + 'px';
//		tds[i].innerHTML += ENG.ss.func.colWidth(i)
		}
	}

ENG.ss.func.searchCmpType = function(inp)
	{
	if (inp && inp.checked)
		{
//		ENG.ss.f.search_cmp_type = inp.value * 1;
		ENG.ss.func.searchPhrase();
		}
	}

// od zacatku slova
ENG.ss.func.searchCmp0 = function(a,b)
	{
	return a.indexOf(b)===0 ? -1 : 1;
	}

// i uprostred slova
ENG.ss.func.searchCmp1 = function(a,b)
	{
	var pos = a.indexOf(b);
	return pos===0 || (pos>0 && /[^a-z]/.test(a.charAt(pos-1))) ? -1 : 1;
//alert(pos)
/*
if (pos>0 && /[^a-z]/.test(SS.func.clear(a.charAt(pos-1))))
alert([
pos,
a.charAt(pos-1),
SS.func.clear(a.charAt(pos-1)),
/[^a-z]/.test(SS.func.clear(a.charAt(pos-1))),
a,
b
]);
*/
	}

ENG.ss.func.clear = function(str)
	{
	var a,b,c,out,i;
	// remove diacritics
	a = "徜栾殪礤掘篝鲟殱鵀聊认商团家釉掷妽谫茌貛";
	b = "aacdeeillnooorstuuuyrzAACDEEILLNOOORSTUUUYRZ";
	out = '';
	for(i = 0; i < str.length; i++)
		{
		c = str.charAt(i);
		if (a.indexOf(c) != -1)
			{
			c = b.charAt(a.indexOf(c));
			}
		out += c;
		}
	// lowercase
	out = out.toLowerCase();
	return out;
	} 

ENG.ss.func.search = function(inp,key1)
	{
	var new_phrase, old_phrase;
	old_phrase = ENG.ss.data.phrases[key1];
	new_phrase = escapeTrim(ENG.ss.func.clear(inp.value));
	if (old_phrase==new_phrase)
		{return;}
	ENG.ss.data.key1 = key1;
	ENG.ss.data.phrases[key1] = new_phrase;
	ENG.ss.func.searchPhrase();
	}

ENG.ss.func.searchPhrase = function()
	{
	var phrase, word, key1, word_all,bool, func, multi_cols, col, i,j,li,lj;
	key1 = ENG.ss.data.key1;
//	if (!isSet(ENG.db.words_index,key1)) {return;}
	if (!isSet(ENG.db.filters,key1))
		{return;}
	func     = ENG.ss.data.cmp==1 ? ENG.ss.func.searchCmp1 : ENG.ss.func.searchCmp0;
	phrase   = ENG.ss.data.phrases[key1];
	multi_cols = [key1];
//	if (key1==2) {multi_cols = [2,3,4];}
//	if (key1==5) {multi_cols = [5,6,7,8];}
	lj = multi_cols.length;
	for (j=0;j<lj;j++)
		{
		bool = true;
		col      = multi_cols[j];
//		word_all = ENG.ss.f.words_index[col];
		word_all = ENG.db.filters[col];
		li = word_all.length;
		for (i=0;i<li;i++)
			{
			word = word_all[i];
//			word = ENG.ss.f.words_value[word];
			word = ENG.db.values[col][word];
			word = ENG.ss.func.clear(word);
			bool = func(word,phrase)>0;
			ENG.fw.func.update(col,i,bool);
//ENG.func.filterWords = function(tab,filters,multi_cols)
			}
		ENG.fw.data.key = col;
		ENG.fw.func.create(false);
		}
	ENG.func.tableShow();
	ENG.ss.func.resize();
	}

// --------------

ENG.hist = {};
ENG.hist.db = {};
ENG.hist.data = {};
ENG.hist.obj = {};
ENG.hist.obj.id = {};
ENG.hist.tpl = {};
ENG.hist.func = {};
ENG.hist.func.init = function(pref)
	{
	var i, tpl, names;
	//pref = ENG.cfg.pref;
	ENG.hist.db.keys   = ENG.db.keys;
	ENG.hist.db.values = db_changes_values;
	ENG.hist.db.map    = db_changes_map;

	ENG.hist.obj.id.all        = pref+'hist_panel';
	ENG.hist.obj.id.search_div = pref+'hist_form_search_div';
	ENG.hist.obj.id.search     = pref+'hist_form_search';
	ENG.hist.obj.id.row_id     = pref+'hist_row_id';
	ENG.hist.obj.id.out        = pref+'hist_out';
	ENG.hist.obj.all   = objGet(ENG.hist.obj.id.all);
//	for (i in ENG.hist.obj.id)
//		ENG.hist.obj[i] = objGet(ENG.hist.obj.id[i]);
	tpl = {};
	tpl.all        = '{search_div} {out}';
	tpl.div        = '<div id="{id}">{html}</div>';
	tpl.search_div = '<form name="{name}">{html}<\/form>';
	tpl.input      = '<label>{text} <input type="text" name="{name}" id="{id}" value="{value}"><\/label>';
	tpl.button     = '<input type="submit" value="{text}" onclick="{onclick}">';
	tpl.table      = '<table class="{class}" onclick="{onclick}"><col><thead>{thead}<\/thead><tbody>{tbody}<\/tbody><\/table>';
	tpl.thead_th   = '<th>{value}<\/th>';
	tpl.tbody_th   = '<th>{value}<\/th>';
	tpl.tbody_td   = '<td>{value}<\/td>';
	ENG.hist.tpl = tpl;
	ENG.hist.data.row_id   = '';
	ENG.hist.data.histmode = 1;
//	// history html
	names = ENG.hist.obj.id;
	ENG.hist.obj.all.innerHTML = render(tpl.all,{
		'search_div': render(tpl.div,{'id': names.search_div, 'html': ''}),
		'out'       : render(tpl.div,{'id': names.out       , 'html': ''})
		});
//alert(ENG.hist.obj.all.innerHTML)
	ENG.hist.obj.search_div = objGet(names.search_div);
//alert(222)
	ENG.hist.obj.out        = objGet(names.out);
	ENG.hist.func.htmlSearchForm();
//	toggle(ENG.hist.obj.all,false);
	}

ENG.hist.func.htmlSearchForm = function()
	{
	var bool, str, tpl, names, data;
	tpl   = ENG.hist.tpl;
	names = ENG.hist.obj.id;
	data  = ENG.hist.data;
	str   = '';
	str  += render("\n"+tpl.input , {'text':'Id', 'name':names.row_id,'id':names.row_id,'value':data.row_id});
	str  += render("\n"+tpl.button, {'text':'Vyhledat', 'onclick':'ENG.hist.func.searchClick(); return false;'});
	str  += ' (hledat historii radku)';
//	str  += ' | ';
	ENG.hist.obj.search_div.innerHTML = render(tpl.search_div, {'name':names.search, 'html':str});
	}
///ENG.fr.tpl.all      = '<form name="{name}">{filter}<\/form>';
//}

ENG.hist.func.openClick = function()
{
toggle(ENG.hist.obj.all,true);
/*
var bool, str, tpl, names, data;
bool = toggle(ENG.hist.obj.all);
if (bool)
	{
	names = ENG.hist.obj.id;
	data  = ENG.hist.data;
	tpl   = ENG.hist.tpl;
	str   = '';
	str  += render("\n"+tpl.input ,{'text':'Id radku','name':names.row_id,'id':names.row_id,'value':data.row_id});
	str  += render("\n"+tpl.button,{'text':'Vyhledat','onclick':'ENG.hist.func.closeClick();'});
	str  += ' | ';
//	str  += render("\n"+tpl.button,{'text':'Download from server','onclick':'ENG.hist.func.download();'});
	str  += render("\n"+tpl.out   ,{'text':'','id':names.out});
	ENG.hist.obj.all.innerHTML = render(tpl.all,{'name':names.form,'html':str});
	return;
	}
*/
}

ENG.hist.func.closeClick = function()
{
toggle(ENG.hist.obj.all,false);
}

ENG.hist.func.searchClick = function()
{
var row_id, count;
row_id = objGet(ENG.hist.obj.id.row_id).value;
count  = ENG.hist.func.historyShow(row_id);
}

ENG.hist.func.filterValues = function(row_all)
	{
	var i, j, start, end, start2, end2;
	start_i  = 0;
	end_i    = row_all.length;
	if (end_i-start_i<=0)
		{return [];}
	start_j = 0;
	end_j   = row_all[0].length;
	i = start_i;
	while (i<end_i)
		{
		j = start_j;
		while (j<end_j)
			{
			row_all[i][j] = ENG.hist.db.values[j][row_all[i][j]];
//		row_all[i][j] = ENG.hist.[row_all[i][j]];
//	db.values[col_row_id][row[col_row_id]]
			j++;
			}
		i++;
		}
	return row_all;
	}

ENG.hist.func.findRows = function(row_id)
	{
	var out, i, col_row_id, db;
	out = [];
	col_row_id  = ENG.cfg.col_row_id;
	db = ENG.hist.db;
//alert(db.values)
	for (i=0; i<db.map.length; i++)
		{
		row = db.map[i];
//alert(db.values[col_row_id][row[col_row_id]])
		if (db.values[col_row_id][row[col_row_id]]==row_id)
			{
			out[out.length] = arrayClone1(row);
			}
		}
	return out;
	}

ENG.hist.func.cmpDate = function(b,a)
	{
	return (a[3]>b[3] ? 1 : (a[3]<b[3] ? -1 : 0));
	}

ENG.hist.func.filterOrderByDate = function(row_all)
	{
	return row_all.sort(ENG.hist.func.cmpDate);
	}

/*
ENG.event.func.read = function (event)
	{
	event  = event || window.event;
	target = event.target || event.srcElement;
	return {'event':event, 'target':target};
	}

ENG.event.func.table = function (target)
*/

ENG.hist.func.historyOpenClick = function(event)
{
data = ENG.event.func.read(event);
if (data.target!=null && ENG.hist.data.histmode==1 && data.target.nodeName=='TD')
	{
	ENG.hist.func.historyOpen(ENG.event.func.table(data.target));
	}
}

ENG.hist.func.historyOpen = function(data_target)
	{
//alert(data_target.toSource())
	if (ENG.hist.data.row_id!=null)
		{
		ENG.hist.func.historyCloseClick();
		}
	ENG.hist.func.historyShow(data_target.row_id);
	};

ENG.hist.func.historyCloseClick = function()
	{
	var obj;
	ENG.hist.data.row_id = null;
	obj = ENG.hist.obj;
//	obj.all.style.display = 'none';
//	obj.all.innerHTML = '';
toggle(ENG.hist.obj.all,false);
	}

ENG.hist.func.historyShow = function(row_id)
	{
	var obj, row_all, out;
	if (row_id=='')
		{return;}
//alert(row_id)
	row_all = ENG.hist.func.findRows(row_id);
	if (row_all.length==0)
		{
		return 0;
		}
	row_all = ENG.hist.func.filterValues(row_all);
	row_all = ENG.hist.func.filterOrderByDate(row_all);
	out = ENG.hist.func.createTable(row_all);
	ENG.hist.data.row_id = row_id;
	obj = ENG.hist.obj;
	obj.out.innerHTML = out;
//	obj.all.style.display = '';
	return row_all.length;
	}

//ENG.edit = {};
//ENG.edit.func = {};

ENG.hist.func.createTable = function(row_all)
{
var i, j, start, end, start2, end2, tbody, thead, str, query_all, tpl;
var css, out
css = {};
tpl = ENG.edit.tpl;
start  = 0;
end    = row_all.length;
if (end<=0)
	{return '';}
start2 = 0;
end2   = row_all[0].length;
tbody  = '';
i = start;
while(i<end)
	{
	tr_title = ' title="'+i+'"';
	tbody += "\n"+'<tr'+ tr_title +'>';
	j = start2;
	while (j<end2)
		{
//		if (!isExist(remove[j]))
//			{
//			if (j!==ENG.data.col_row_id)
//				{
				tbody += '<td>' + row_all[i][j] + '<\/td>';
//				}
//			else	{
//				tbody += '<th>' + row_all[i][j] + '<\/th>';
//				}
//			}
		++j;
		}
	tbody += '<\/tr>';
	++i;
	}
row   = ENG.hist.db.keys;
thead = "\n"+'<tr>';
j = start2;
while (j<end2)			//no-edit
	{
//	if (!isExist(remove[j]))
//		{
		thead += render(tpl.thead_th,{'key':j, 'value':row[j], 'onclick':''});
//		}
	++j;
	}
thead += '<\/tr>';
css.table = "zas2_table "+'history';
out = render(tpl.table,{'class':css.table, 'thead':thead, 'tbody':tbody, 'onclick': ''});
return out;
//return render(tpl.table,{'class':css.table, 'thead':thead, 'tbody':tbody, 'onclick': 'return ENG.edit.func.editOpenClick(event);'});

	}







// -------------

ENG.edit.func.init = function(pref)
{
var i, type, type_all, tpl, obj;
tpl = {};
tpl.all       = '{nav} {form} {out}';
tpl.td_input  = '<input type="text" value="{value}" onblur="{onblur}" class="coledit">';	//no-edit
tpl.table     = '<table class="{class}" onclick="{onclick}"><col><thead>{thead}<\/thead><tbody>{tbody}<\/tbody><\/table>';
tpl.thead_th  = '<th class="filter col{key} hover"><div onclick="{onclick}">{value}<\/div><\/th>';	//no-edit
tpl.tbody_th  = '<th>{value}<\/th>';
tpl.tbody_td  = '<td>{value}<\/td>';
tpl.div       = '<div id="{id}">{html}<\/div>';
tpl.nav_item  = '<span class="{class}" onclick="{onclick}" title="{title}">{html}<\/span>';
tpl.form      = '<form name="{name}" onsubmit="{onsubmit}">{html}<\/form>';
tpl.input     = '<label>{text} <input type="text" name="{name}" id="{id}" value="{value}"><\/label>';
tpl.submit_button        = '<input type="submit" value="{text}">';
tpl.qtable_button_delete = '<span class="{class}" onclick="{onclick}" title="{title}">{html}<\/span>';
obj = {};
obj.id = {};
obj.id.all    = pref+'edit_panel';
obj.id.nav    = pref+'edit_panel_nav';
obj.id.insert = pref+'edit_panel_insert';
obj.id.delete = pref+'edit_panel_delete';
obj.id.form   = pref+'edit_panel_form';
obj.id.row_id = pref+'edit_panel_row_id';
obj.id.out    = pref+'edit_panel_out';
obj.all = objGet(pref+'edit_panel');
obj.all.innerHTML = render(tpl.all,{
	'nav' :render(tpl.div,{'id':obj.id.nav , 'html':''}),
	'form':render(tpl.div,{'id':obj.id.form, 'html':''}),
	'out' :render(tpl.div,{'id':obj.id.out , 'html':''})
	});
obj.nav  = objGet(obj.id.nav);
obj.form = objGet(obj.id.form);
obj.out  = objGet(obj.id.out);
ENG.edit.tpl = tpl;
ENG.edit.obj = obj;
ENG.edit.data.editmode = 1;
ENG.edit.data.insert = {};
ENG.edit.data.insert.auto_id = 1;
ENG.edit.data.insert.deleted = 0;
ENG.edit.data.delete = {};
ENG.edit.data.delete.deleted = 0;
ENG.edit.data.update = {};
ENG.edit.data.update.deleted = 0;
//ENG.edit.data.delete = {};
//ENG.edit.data.delete.auto_id = 1;
ENG.edit.data.editmode = 1;
ENG.edit.data.col_row_id = ENG.fc.data.col_row_id;
ENG.edit.data.col = {};
ENG.edit.data.type_all = ['update','insert','delete'];
ENG.edit.data.nav = {};
ENG.edit.data.nav.selected = null;
ENG.edit.data.nav.items = {
	'all'   :{'text':'All'   , 'table':null},
	'update':{'text':'Update', 'table':null},
	'insert':{'text':'Insert', 'table':ENG.edit.func.cloneInsertSet},
	'delete':{'text':'Delete', 'table':ENG.edit.func.cloneDeleteSet}
	};
type_all = ENG.edit.data.type_all;
for(i=0;i<type_all.length;i++)
	{
	type = type_all[i];
	ENG.edit.query_db[type] = [];
	}
ENG.edit.func.editReset();
ENG.edit.func.navCreate('update');
};

ENG.edit.func.navCreate = function(sel)
{
var sel, items, str, tpl, open, data, cnt, i, types_all;
sel   = sel ? sel : ENG.edit.data.nav.selected;
sel   = sel.replace(/[^a-z]/g,'');
items = ENG.edit.data.nav.items;
tpl   = ENG.edit.tpl;
str   = '';
for (i in items)
	{
	cnt  = i!='all' ? ENG.edit.query_db[i].length - ENG.edit.data[i].deleted : 0;
	data = {
		'html'   : items[i].text + (cnt>0? ' ('+cnt+')':''),
		'class'  : 'hover' + (sel==i?' sel':''),
		'onclick': 'ENG.edit.func.navClick(\''+i+'\');'
		};
	data.title = escapeHtml("javascript: "+ data.onclick);
	str += render(tpl.nav_item,data) + " &nbsp; \n";
	}
ENG.edit.obj.nav.innerHTML = str;
if (sel in items)
	{
	ENG.edit.data.nav.selected = sel;
	ENG.edit.func.formCreate(sel);
	ENG.edit.func.queryShow(sel);
	ENG.mp.func.modeClick('edit',true);
//	window[open];
	}
}

ENG.edit.func.noneFormCreate = function()
	{
	ENG.edit.obj.form.innerHTML = '';
	}

ENG.edit.func.formCreate = function(type)
	{
	var str, tpl, obj, names;
//sel   = sel ? sel : ENG.edit.data.nav.selected;
//sel   = sel.replace(/[^a-z]/g,'');
	tpl   = ENG.edit.tpl;
	obj   = ENG.edit.obj;
	names = ENG.edit.obj.id;
	str   = '';
	switch(type)
		{
		case 'insert':
			str += render("\n"+tpl.input        , {'text':'Id', 'name':names.row_id, 'id':names.row_id, 'value':''});
			str += render("\n"+tpl.submit_button, {'text':'Klonuj'});
			str += ' (klonuj radek)';
			str  = render(tpl.form, {
				'name'    : names.insert,
				'html'    : str,
//				'onsubmit': 'var inp = this.'+names.row_id+'; ENG.edit.func.cloneInsert({\'type\':\'\',\'row_id\':inp.value}); inp.focus(); return false;'
// nelze pouzit inp.focus, protoze cely formular prepisuje cloneInsert do divu
				'onsubmit': 'var inp = this.'+names.row_id+'; ENG.edit.func.cloneInsert({\'type\':\'\',\'row_id\':inp.value}); objGet(\''+names.row_id+'\').focus(); return false;'
				});
//'onsubmit':'ENG.edit.insertClick(this.form.'+names.row_id+'.value); return false;'});
			break;
		case 'delete':
			str += render("\n"+tpl.input        , {'text':'Id', 'name':names.row_id, 'id':names.row_id, 'value':''});
			str += render("\n"+tpl.submit_button, {'text':'Smazat'});
			str += ' (smazat radek)';
			str  = render(tpl.form, {
				'name'    : names.delete,
				'html'    : str,
//				'onsubmit':'ENG.edit.func.cloneDelete({\'type\':\'\',\'row_id\':this.'+names.row_id+'.value}); return false;'
				'onsubmit': 'var inp = this.'+names.row_id+'; ENG.edit.func.cloneDeleteSet({\'type\':\'\',\'row_id\':inp.value}); objGet(\''+names.row_id+'\').focus(); return false;'
				});
			break;
		case 'update':
			break;
		case 'all':
			break;
		default: break;
		}
	obj.form.innerHTML = str;
	}

ENG.edit.func.cloneDeleteSet = function(data)
	{
	var type2, row, id;
	if (data.row_id)
		{
		var type2 = 'delete';
		if (data.type=='update' || data.type=='insert' || data.type=='delete')
			{
//			// clone from query
//			ENG.edit.func.queryFindCloneByRowId(data.type, type2, data.row_id);
//			ENG.edit.func.navCreate(type2);
			}
		else	{
			// clone from table
			id  = data.row_id;
			row = ENG.edit.func.dbReadRow(id);
			ENG.edit.func.queryFindReplaceByRowId(type2, id, row);
			ENG.edit.func.navCreate(type2);
//ENG.func.tableShow();
//			data.tr.className += 'q delete';	// zabarvi cervene
			data.tr.className += ENG.edit.func.trClass(type2);	// zabarvi cervene

//var tab;
//tab = ENG.data.tab;
//tab = ENG.edit.func.doFiltersQuery(tab);
//ENG.func.renderTable(tab,{'tab_div': ENG.obj.tab_div, 'class':ENG.cfg.pref+'table', 'onclick': 'return ENG.edit.func.tableClick(event);'});
			}
		}
	}

ENG.edit.func.cloneInsertSet = function(data)
	{
	var type2, row, id, new_id;
	if (data.row_id)
		{
		var type2 = 'insert';
		if (data.type=='update' || data.type=='insert' || data.type=='delete')
			{
			// clone from query
			ENG.edit.func.queryFindCloneByRowId(data.type, type2, data.row_id);
			ENG.edit.func.navCreate(type2);
			}
		else	{
			// clone from table
			id  = data.row_id;
			row = ENG.edit.func.dbReadRow(id);
			new_id = ENG.edit.query_db[type2].length;
			row[ENG.edit.data.col_row_id] = new_id;
			ENG.edit.func.queryUpdate(type2,new_id,row);
			
			ENG.edit.func.navCreate(type2);
			}
		}
	}

ENG.edit.func.navClick = function(sel)
{
//ENG.edit.data.nav.selected = sel;
ENG.edit.func.navCreate(sel);
}

ENG.edit.func.querySelect = function(type, id)
{
return ENG.edit.query_db[type][id];
}

ENG.edit.func.queryUpdate = function(type, id, data)
{
ENG.edit.query_db[type][id] = data;
}

ENG.edit.func.queryDelete = function(type, id)
{
if (ENG.edit.query_db[type][id]!=null)
	{
	ENG.edit.data[type].deleted++;
	}
ENG.edit.query_db[type][id] = null;
}

ENG.edit.func.queryFind = function(type, id)
{
return isSet(ENG.edit.query_db,type) && isSet(ENG.edit.query_db[type],id) ? id : false;
}

ENG.edit.func.queryFindByRowId = function(type, row_id)
{
var i;
for (i=0;i<ENG.edit.query_db[type].length;i++)
	{
	if (ENG.edit.query_db[type][i]==null)
		{continue;}	// preskoc smazane radky
	if (ENG.edit.query_db[type][i][ENG.edit.data.col_row_id]==row_id)
		{return i;}
	}
return false;
}

ENG.edit.func.queryFindAddByRowId = function(type, row_id, data)	// --- HLAVNI FUNKCE 1
{
var id;
id = ENG.edit.func.queryFindByRowId(type, row_id);
if (id==false)
	{
	id = ENG.edit.query_db[type].length;
	}
ENG.edit.func.queryUpdate(type,id,data);
return id;
}

ENG.edit.func.queryFindReplaceByRowId = function(type, row_id, data)	// --- HLAVNI FUNKCE 3	// pouziva delete
{
var id;
id = ENG.edit.func.queryFindByRowId(type, row_id);
if (id!==false)
	{
	return;
	}
id = ENG.edit.query_db[type].length;
ENG.edit.func.queryUpdate(type,id,data);
}

ENG.edit.func.queryFindCloneByRowId = function(type1, type2, row_id)	// --- HLAVNI FUNKCE 2 // pouziva insert e
{
var id;
id1 = ENG.edit.func.queryFindByRowId(type1, row_id);
if (id1==false)
	{
	return;
	}
data = ENG.edit.func.querySelect(type1,id1);
id2  = ENG.edit.query_db[type2].length;
ENG.edit.func.queryUpdate(type2,id2,data);
}

ENG.edit.func.queryShow = function(type)	//'insert' / 'update' / 'delete'
{
var str, type_all,i;
type   = type ? type : ENG.edit.data.nav.selected;
if (type!='all')
	{
	str = ENG.edit.func.qtableOpen(type);
	}
else	{
	str = '';
	type_all = ENG.edit.data.type_all;
//	alert(['type_all',type_all]);
//	alert(['type_all.length',type_all.length]);
	for(i=0;i<type_all.length;i++)
		{
		type = type_all[i];
//	alert(['type',type]);
//		alert(ENG.edit.query_db[type].length)
		if (ENG.edit.query_db[type].length>0)
			{
			str += '<div>'+type+'<\/div>';
			str += ENG.edit.func.qtableOpen(type);
			}
		}
	}
ENG.edit.obj.out.innerHTML = str;
/*
var i, str;
str = '';
for (i=0;i<ENG.edit.query_db[type].length;i++)
	{
	str += ENG.edit.query_db[type][i].toSource()+"\n";
	}
alert(str);
*/
}

ENG.edit.func.exportRequest = function()
{
var out, i, j, k, row, query, query_all, type_all, col_row_id;
col_row_id = ENG.edit.data.col_row_id;
//type_all = ENG.edit.data.type_all;
out = [];
for (i in ENG.edit.query_db)
	{
	query_all = ENG.edit.query_db[i];
	for (j=0;j<query_all.length;j++)
		{
//		query = query_all[j];
		query = query_all[j];
		row = [];
		row[row.length] = i;
		row[row.length] = query[col_row_id] + ''; // to string
		for (j=0;j<query.length;j++)
			{
//			row[row.length] = ENG.db.values[data[j]] ? ENG.db.values[data[j]] : '';
			row[row.length] = query[j];
			}
		out[out.length] = row;
		}
	}
newWindowPlainText('sql_data',CSV.export(out));
}

ENG.edit.func.qTableDeleteButtonClick = function(type, id)	//cloneDeleteRemove
{
//ENG.edit.func.editClose(); vola se onblur editovaciho inputu
ENG.edit.func.queryDelete(type, id);


//			data.tr.className += ENG.edit.func.trClass(type2);	// zabarvi cervene

ENG.edit.func.queryShow();

//tab = arrayClone2(ENG.data.tab);
//tab = ENG.edit.func.doFiltersQuery(tab);
//ENG.func.renderTable(tab,{'tab_div': ENG.obj.tab_div, 'class':ENG.cfg.pref+'table', 'onclick': 'return ENG.edit.func.tableClick(event);'});

ENG.edit.func.navCreate();

//ENG.func.tableShow();	// funguje, odbarvuje cervene
// zjednodusena verze taky funguje, ne uplne dobre, pri edit a delete necha jen edit a tak
tab = ENG.data.tab;
tab = ENG.edit.func.doFiltersQuery(tab);
ENG.func.renderTable(tab,{'tab_div': ENG.obj.tab_div, 'class':ENG.cfg.pref+'table', 'onclick': 'return ENG.edit.func.tableClick(event);'});

}

ENG.edit.func.qtableOpen = function(type)
{
var i, j, start, end, start2, end2, tbody, thead, str, query_all, tpl, data, col_row_id, row;
tpl = ENG.edit.tpl;
query_all = ENG.edit.query_db[type];
start  = 0;
end    = query_all.length;	// pocet radku
//alert(end)
if (end<=0)
	{return '';}
start2 = 0;
end2   = 0;
i = start;
while(i<end)
	{
	if (query_all[i]!=null)	// preskoc prazdne radky
		{
		end2   = query_all[i].length;	// pocet sloupcu
		break;
		}
	i++;
	}
tbody = '';
i = start;

col_row_id = ENG.edit.data.col_row_id;
//alert(col_row_id)
data = {
	'html'   : 'Delete',
	'class'  : 'hover delete',
	};

while(i<end)
	{
	row = query_all[i];
//alert(row)
	if (row==null || typeof(row)=='undefined')	// preskoc smazany radek
		{++i; continue;}
	tr_title = ' title="'+i+'"';
	tbody += "\n"+'<tr'+ tr_title +'>';
	data.onclick = 'ENG.edit.func.qTableDeleteButtonClick(\''+type+'\','+i+');';
	data.title   = escapeHtml("javascript: "+ data.onclick);
	tbody += '<td>' + render(tpl.qtable_button_delete,data) + '<\/td>';	// pridavam sloupec navic
	j = start2;
	while (j<end2)
		{
		if (!isExist(remove[j]))
			{
			if (j!==col_row_id)
				{
				tbody += '<td>' + row[j] + '<\/td>';
				}
			else	{
				tbody += '<th>' + row[j] + '<\/th>';
				}
			}
		++j;
		}
	tbody += '<\/tr>';
	++i;
	}
if (tbody=='')
	{return '';}
row   = ENG.db.keys;
thead = "\n"+'<tr>';
j = start2;
while (j<end2)			//no-edit
	{
	thead += render(tpl.thead_th,{'key':'', 'value':'', 'onclick':''});
	if (!isExist(remove[j]))
		{
		thead += render(tpl.thead_th,{'key':j, 'value':row[j], 'onclick':''});
		}
	++j;
	}
thead += '<\/tr>';
var css = {};
css.table = "zas2_table "+type;
//css.table = "zas2_table "+'update';
return render(tpl.table,{'class':css.table, 'thead':thead, 'tbody':tbody, 'onclick': 'return ENG.edit.func.qTableClick(event);'});
//return ENG.edit.func.onQTableClick(event);
//return render(tpl.table,{'class':css.table, 'thead':thead, 'tbody':tbody, 'onclick': 'return ENG.edit.func.editOpenClick(event);'});

}


//			return ' class="q '+i+'"';  ,patt
ENG.edit.func.trClass = function(type,main)	//='q'
{
if (typeof(main)=='undefined') {main='q';}
return main+' '+type;
}

ENG.edit.func.trClassCheck = function(col_row_id,row_id)
{
var i, j, lj;
str = '';
for (i in ENG.edit.query_db)
	{
	j  = 0;
	lj = ENG.edit.query_db[i].length;
//if (lj>0) alert(ENG.edit.query_db[i])
	while (j<lj)
		{
		if (ENG.edit.query_db[i][j]!=null && row_id==ENG.edit.query_db[i][j][col_row_id])	// ignoruj smazane
			{
			str = ' class="'+ENG.edit.func.trClass(i)+'"'; break;	// posledni clas bude prioritou a tim je 'delete', prebiji tedy 'edit'
			}
		j++;
		}
	}
return str;
}

ENG.edit.func.dbReadRow = function(row_id)
{
var row, li, i, id;
col_row_id = ENG.edit.data.col_row_id;
//alert ([col_row_id])
li = ENG.db.map.length;
row_id = row_id;
for (i=0;i<li;i++)
	{

	if (row_id==ENG.db.values[col_row_id][ENG.db.map[i][col_row_id]])
		{
		row = arrayClone1(ENG.db.map[i]);
		row = ENG.func.filterValues([row]);
		return row[0];
		}
	}
return false;
}

/*
ENG.edit.func.onQTableClick = function(event)
{
event  = event || window.event;
target = event.target || event.srcElement;
//alert(target.nodeName)
if (ENG.edit.data.editmode==1 && target.nodeName=='TD')
	{
	ENG.edit.func.editOpen(target);
	//alert(id);
	}
}

ENG.edit.func.editOpenClick = function(event)
{
event  = event || window.event;
target = event.target || event.srcElement;
//alert(target.nodeName)
if (ENG.edit.data.editmode==1 && target.nodeName=='TD')
	{
	ENG.edit.func.editOpen(target);
	//alert(id);
	}
}
*/

ENG.edit.func.tableClick = function(event)	// klik na hlavni tabulku
{
event  = event || window.event;
var target = event.target || event.srcElement;
if (target.nodeName=='TD')
	{
	ENG.edit.func.cloneOpen(target);
	}
}

ENG.edit.func.qTableClick = function(event)	// klik na tabulku s query, editace treba insert
{
event  = event || window.event;
var target = event.target || event.srcElement;
var sel = ENG.edit.data.nav.selected;
if (target.nodeName=='TD')
	{
	if (sel=='update' || sel=='insert')
		{
		ENG.edit.func.editOpen(target,1);
		}
//	if (sel=='delete')
//		{
//		ENG.edit.func.editOpen(target);
//		}
	}
}

ENG.edit.func.colWidth = function(col)
{
//var time = PERF.getTime();
return (col.nodeName && (col.nodeName=='TD' || col.nodeName=='TH')) ?
	{'width': col.offsetWidth, 'left': col.offsetLeft} : false;
//time = PERF.getTime();
//alert(time);
//return o;
}

ENG.edit.func.openClick = function()
{
toggle(ENG.edit.obj.all,true);
}

ENG.edit.func.closeClick = function()
{
//ENG.edit.func.editClose();	vola se onblur editovaciho inputu
toggle(ENG.edit.obj.all,false);
}

ENG.edit.func.cloneOpen = function (target)
{
var sel, items;
sel = ENG.edit.data.nav.selected;
if (sel=='update')
	{
	ENG.edit.func.editOpen(target);
	return;
	}

var tr, table, data;
tr     = target.parentNode;
if (tr.nodeName!=='TR')	//error, no tr
	{return;}
table  = tr.parentNode;
if (table.nodeName!=='TABLE')	//tbody
	{table  = table.parentNode;}
if (table.nodeName!=='TABLE')	//error, no table
	{return;}
last_class = table.className;
last_class = last_class ? (last_class.indexOf(' ')>=0 ? last_class.split(' ') : [last_class]) : [];
last_class = last_class[last_class.length-1];
data = {};
data.type   = last_class;
data.td     = target;	// nemusi byt td!
data.tr     = tr;
data.value  = trim(target.innerHTML);
data.row_id = tr.title * 1;
data.col_id = ENG.cr.func.colFromRendered(target.cellIndex * 1);	// pocita s tim, ze target je col
items = ENG.edit.data.nav.items;
//alert([sel, items[sel].toSource()]);

items[sel].table(data);
}

ENG.edit.func.editOpen = function (target, prefix)
{
//ENG.func.log('editOpen=' + PERF.getTime());
var tr, col, row_id, col_id, last_class, table;//row, , input;
tr     = target.parentNode;
if (tr.nodeName!=='TR')	//error, no tr
	{return;}
table  = tr.parentNode;
if (table.nodeName!=='TABLE')	//tbody
	{table  = table.parentNode;}
if (table.nodeName!=='TABLE')	//error, no table
	{return;}
prefix = typeof(prefix)=='undefined' ? 0 : prefix;
row_id = tr.title * 1;
col_id = target.cellIndex * 1 - prefix;
if (ENG.edit.data.col.row_id!==row_id || ENG.edit.data.col.col_id!==col_id)
	{
//	ENG.edit.func.editClose(); vola se onblur editovaciho inputu
	last_class = table.className;
	last_class = last_class ? (last_class.indexOf(' ')>=0 ? last_class.split(' ') : [last_class]) : [];
	last_class = last_class[last_class.length-1];
	col = {};
	col.type   = last_class;
	col.td     = target;
	col.value  = trim(target.innerHTML);
	col.row_id = row_id;
	col.col_id = ENG.cr.func.colFromRendered(col_id);
//alert([	col.col_id,	col_id, ENG.cr.data.rend.toSource()])
	col.width  = (col.type=='update' || col.type=='insert' || col.type=='delete') ?
			ENG.edit.func.colWidth(target).width :
			ENG.cr.data.rend[col_id].pos.width;
/*
//alert([i,
//isSet(c,i)
//])
alert([
isExist(c) , isSet(c,i) , isObject(c[i].pos) , isExist(c[i].pos.width)
])
*/
//alert((isExist(c) && isSet(c[i]) && isObject(c[i].pos) && isExist(c[i].pos.width)))
//	if (!(isExist(c) && isSet(c,i) && isObject(c[i].pos) && isExist(c[i].pos.width)))
//		{return false;}
//
//ENG.cr.func.inpWidth(col_id)

//ENG.data.rendered_cols[col.col_id].pos.width);
//alert(	col.col_id)
//	col.value  = [col.row_id,col.col_id,col.width].join(',');
	col.onblur = 'ENG.edit.func.editClose();'
	target.innerHTML = render(ENG.edit.tpl.td_input, col);
	col.input  = target.getElementsByTagName('INPUT')[0];
	ENG.edit.data.col = col;
//alert(col.toSource())
	col.input.style.minWidth = col.width+'px';
	col.input.focus();			// cursor to input
	//input.value = input.value;	// cursor to end
	col.input.selectionStart = col.input.selectionEnd = col.input.value.length; // cursor to end
	}
//alert([row,col])
}

ENG.edit.func.editReset = function()
{
var col;
col = {};
col.td     = null;
col.value  = '';
col.row_id = -1;
col.col_id = -1;
ENG.edit.data.col = col;
}

ENG.edit.func.editClose = function ()
{
//ENG.func.log('editClose=' + PERF.getTime());
var id, value, row, update_id, insert_id, row_id, col_id, col, col_row_id, type, tab;
col_row_id = ENG.edit.data.col_row_id;
col = ENG.edit.data.col;
if (col.td!=null)
	{
	value = col.input.value;
//alert(value)
	value = trim(value);
//alert(col.type)
//ENG.edit.data.type_all
	col.td.innerHTML = value;
	// add query
	if (value!=col.value)
		{
//if (col.type=='insert')
		if (col.type=='update' || col.type=='insert' || col.type=='delete')
			{
			if (col.type=='update' || col.type=='insert')
				{
				type = col.type;
				update_id = col.row_id;
				if (update_id!==false)
					{
					row = ENG.edit.func.querySelect(type,update_id);
					row[col.col_id] = value;
					ENG.edit.func.queryUpdate(type, update_id, row);
//					ENG.edit.func.mainTableUpdate(row[col_row_id], row);
					bool = true;
//tab = arrayClone2(ENG.data.tab);
tab = ENG.data.tab;
tab = ENG.edit.func.doFiltersQuery(tab);
ENG.func.renderTable(tab,{'tab_div': ENG.obj.tab_div, 'class':ENG.cfg.pref+'table', 'onclick': 'return ENG.edit.func.tableClick(event);'});
//ENG.func.tableShow();
					}
				ENG.edit.func.navCreate(type);
				}
			}
		else	{
			row = ENG.edit.func.dbReadRow(col.row_id);
			if (row===false)
				{
				type = 'insert';
//			insert_id = ENG.edit.func.queryFindByRowId('insert', col.row_id);
//			if (insert_id!==false)
//				{
//				row = ENG.edit.func.querySelect('insert',insert_id);
//				row[col.col_id] = value;
//				row[col_row_id] = insert_id;
//				ENG.edit.func.queryUpdate('insert', insert_id, row);
//				}
//			else	{
//				row[col.col_id] = value;
//				ENG.edit.func.queryFindAddByRowId('update',col.row_id,row);
//				}
				ENG.edit.func.navCreate(type);
				}
			else	{
				type = 'update';
				update_id = ENG.edit.func.queryFindByRowId(type, col.row_id);
				if (update_id!==false)
					{
					row = ENG.edit.func.querySelect(type,update_id);
					row[col.col_id] = value;
					ENG.edit.func.queryUpdate(type, update_id, row);
					bool = true;
					}
				else	{
					row[col.col_id] = value;
					ENG.edit.func.queryFindAddByRowId(type,col.row_id,row);
					bool = true;
					}
				col.td.parentNode.className = ENG.edit.func.trClass(type);
				ENG.edit.func.navCreate(type);
//ENG.func.tableShow();
				}
			}
		ENG.ip.func.show();
//ENG.edit.func.queryShow(type); - nahrazuje nav create
		ENG.cr.func.colsWidth(ENG.cr.data.uniq);	// tohle nebude fungovat, protoze se nepouzivaji data i s update query
//		ENG.fw.func.create();
//		ENG.ss.func.create();
		ENG.ss.func.resize();
		}
//	row[el.col_id] = EE.func.dbFindAddValue(el.col_id,value);	// row undefined
////	el.td.innerHTML = value;	 neni treba, protoze se prekresluje cela tabulka
//	row = cloneArray1(EE.db.map[el.row_id]);
//	row[el.col_id] = EE.func.dbFindAddValue(el.col_id,value);	// row undefined
////	EE.func.dbUpdate(EE.func.rowSelect(EE.update.row))
//	EE.func.dbUpdate(row_id,row);
	// sql update
////ENG.func.tableShow();
	}
ENG.edit.func.editReset();
//ENG.func.init();
}

ENG.edit.func.doFiltersQuery = function(tab)
{
var col_row_id, type_all, i, li;
col_row_id = ENG.edit.data.col_row_id;
li = tab.length;
for(i=0;i<li;i++)
	{
	row1 = tab[i];
	lj = ENG.edit.query_db['update'].length;
	for(j=0;j<lj;j++)
		{
		row2 = ENG.edit.query_db['update'][j];
		if (row2!=null && row1[col_row_id]==row2[col_row_id])
			{
			tab[i] = row2;
			break;
			}
		}
/*
	// delete rowy se nebudou mazat, budou cervene
	lj = ENG.edit.query_db['delete'].length;
	for(j=0;j<lj;j++)
		{
		row2 = ENG.edit.query_db['delete'][j];
		if (row1[col_row_id]==row2[col_row_id])
			{
			tab[i] = [];
			break;
			}
		}
*/
	}
return tab;
}



ENG.transfer.func.init = function (pref)
	{
	var tpl, obj, data, url, files_all, str, item_, i, i_end, url_path, str;
	obj = ENG.transfer.obj;
	tpl = ENG.transfer.tpl;
	func = ENG.transfer.func;

	obj.id.all    = pref+'panel_transfer';
	obj.id.status = pref+'transfer_status';
	obj.id.upl    = pref+'transfer_upl';
	obj.id.down   = pref+'transfer_down';
	obj.all = objGet(obj.id.all);

	tpl.link = '<a href="{url}">{text}<\/a>';
	tpl.butt = '<span class="butt hover" onclick="{onclick}">{text}<\/span>';
	tpl.div  = '<div id="{id}">{text}<\/div>';
//	tpl.all  = '{butt} {status} {upl} {down}';
	tpl.all  = '{status} {upl} {down}';

	url_path  = 'http:\/\/localhost\/www\/zelus-new\/zasuvky-csv\/';
	url       = url_path + 'zas2_download.php?file=';
	files_all = [
		'zas2.zip', 
		'zas2.htm', 
		'zas2-css.css', 
		'zas2-db.js', 
		'zas2-db-changes.js', 
		'zas2-inc.js', 
		'zas2-eng.js'
		];

	str = '';
	i_end = files_all.length;
	for (i=0;i<i_end;i++)
		{
		item_ = files_all[i];
		str += render(tpl.link, {'url': url+escapeUrl(item_), 'text': escapeHtml(item_)}) + ', ';
		}
	str = str.substring(0,str.length-2);
	tpl.down = str;

//	butt = [
//		{'text':'Download','onclick':'ENG.transfer.func.downloadOpenClick();'},
//		{'text':'Upload'  ,'onclick':'ENG.transfer.func.uploadOpenClick();'}
//		];
	data = {
//		'butt'  : [],
		'status': render(tpl.div,{'id':obj.id.status, 'text':''}),
		'upl'   : render(tpl.div,{'id':obj.id.upl   , 'text':''}),
		'down'  : render(tpl.div,{'id':obj.id.down  , 'text':''}),
		}
//	for (i=0;i<butt.length;i++)
//		{
//		butt[i] = render(tpl.butt,butt[i]);
//		}
//	data.butt = butt.join(" | \n");
	obj.all.innerHTML = render(tpl.all,data);
	obj.status = objGet(obj.id.status);
	obj.upl    = objGet(obj.id.upl);
	obj.down   = objGet(obj.id.down);

	ENG.transfer.tpl = tpl;
	ENG.transfer.obj = obj;
	ENG.transfer.data.opened_window = null;

	// download init
//	var tpl, obj;
//	obj = ENG.transfer.obj;
//	tpl = ENG.transfer.tpl;
//	if (obj.out.innerHTML!='')
//		{}
	obj.down.innerHTML = render(tpl.down);
	ENG.transfer.func.closeClick();

	}

ENG.transfer.func.closeClick = function()
	{
	toggle(ENG.transfer.obj.status,false);
	toggle(ENG.transfer.obj.upl,false);
	toggle(ENG.transfer.obj.down,false);
	ENG.transfer.data.opened_window = null;
	}

ENG.transfer.func.downloadOpenClick  = function()
	{
	if (ENG.transfer.data.opened_window=='down')
		{
		ENG.transfer.func.closeClick();
		return;
		}
	toggle(ENG.transfer.obj.status,true);
	toggle(ENG.transfer.obj.upl,false);
	toggle(ENG.transfer.obj.down,true);
	ENG.transfer.data.opened_window = 'down';
	}

ENG.transfer.func.uploadOpenClick  = function()
	{
	if (ENG.transfer.data.opened_window=='upl')
		{
		ENG.transfer.func.closeClick();
		return;
		}
	toggle(ENG.transfer.obj.status,true);
	toggle(ENG.transfer.obj.upl,true);
	toggle(ENG.transfer.obj.down,false);
	ENG.transfer.data.opened_window = 'upl';
	}



// --------
/*
//alert(db_map[0].length)
EE = {};	// edit engine
EE.obj = {};
EE.obj = ENG.obj;
EE.db  = {};
EE.db  = ENG.db;
EE.query = [];
EE.func = {};
EE.editmode = 1;
EE.update = {};
*/
//EE.tpl.input = '<input type="text" value="{value}" onblur="EE.func.updateColumnClose(this);" class="coledit">';
//EE.func.dbValueFind = function(val)
//{
//for (i=0; i<EE.db.values.length; i++)
//	{
//	if (EE.db.values[i] == val)
//		{return key;}
//	}
//return false;
//}

//alert(EE.query.toSource())
/*
EE.func.queryShow = function()
{
var i, str;
str = '';
for (i=0;i<EE.query.length;i++)
	{str += EE.query[i].toSource()+"\n";}
alert(str);
}

EE.func.queryFind = function(id)
{
var i;
for (i=0;i<EE.query.length;i++)
	{if (EE.query[i].row_id==id) {return i;}}
return i;
}

//EE.func.queryInsert = function(data)
//{
//EE.query[EE.query.length] = data;
//}

EE.func.queryUpdate = function(id, data)
{
EE.query[id] = data;
}


EE.func.exportSql = function()
{
var out, i, j, row, data, query;
out = [];
for (i=0;i<EE.query.length;i++)
	{
	query = EE.query[i];
	data = query.row;
	row = [];
	row[row.length] = query.type;
	row[row.length] = query.row_id + ''; // to string
	for (j=0;j<data.length;j++)
		{
		row[row.length] = ENG.db.values[data[j]] ? ENG.db.values[data[j]] : '';
		}
	out[i] = row;
	}
newWindowPlainText('sql_data',CSV.export(out));
}
*/

/*
EE.func.queryAdd = function(data)
{
var id, i, row0, row1, bool;
id = EE.func.queryFind(data.row_id);
//alert(id,data.row_id)
if (data.type=='update' && isSet(EE.query,'type')) {data.type = EE.query[id].type;}	// nesmi se prepsat 'insert'
row0 = EE.db.map[data.row_id];
row1 = data.row;
bool = false;
//alert(row0+"\n"+row1)
for (i=0;i<row1.length;i++)	// check changes
	{if (row0[i]!=row1[i]) {bool = true; break;}}
if (bool==true)
	{
	EE.func.queryUpdate(id, data);
	}
}

EE.func.dbFindAddValue = function(col_id,val)
{
var key;
key = inArray(EE.db.values, val);
if (key===false)
	{
	key = EE.db.values.length;
	EE.db.values[key] = val;
	EE.db.filters[col_id][EE.db.filters[col_id].length] = key;
	}
return key;
}

EE.func.dbSelectValues = function(id)
{
var i, row, out;
row = EE.db.map[id];
out = [];
for (i=0; i<row.length; j++)
	{
	out[i] = ENG.db.values[row[i]] ? ENG.db.values[row[i]] : '';
	}
return out;
}

EE.func.dbInsert = function(row)
{
var out, i, bool, key, id;
out = [];
for (i=0;i<row.length;i++)
	{
	out[i] = EE.func.dbFindAddValue(row[i]);
	}
id = EE.db.map.length;
EE.func.queryAdd({row_id:id, row:out, type:'insert'});
EE.db.map[id] = out;
ENG.init();
}

EE.func.dbUpdate = function(id, row)
{
var out, i, bool, key, id;
//out = [];
bool = false;
//for (i=0;i<row.length;i++)
//	{
//	out[i] = EE.func.dbFindAddValue(row[i]);
//	}
//alert(out)
EE.func.queryAdd({row_id:id, row:row, type:'update'});
EE.db.map[id] = row;
//EE.func.queryAdd([id, row, 'update']);
//EE.queryAdd('update', id, row);
ENG.func.init();
ENG.func.tableShow();
}

EE.func.dbDelete = function(id)
{
//EE.func.queryAdd([id, null, 'delete']);
EE.func.queryAdd({row_id:id, row:null, type:'delete'});
EE.db.map[id] = [];
}

EE.func.updateColumnClick = function(event)
{
event  = event || window.event;
target = event.target || event.srcElement;
//alert(target.nodeName)
if (target.nodeName=='TD' && EE.editmode==1)
	{
	EE.func.updateColumnOpen(target);
	//alert(id);
	}
}

EE.func.updateColumnOpen = function (target)
{
var tr, row, col, input;
tr  = target.parentNode;
row_id = tr.title * 1;
col_id = target.cellIndex * 1;
if (EE.update.row_id!==row_id || EE.update.col_id!==col_id)
	{
	EE.func.updateColumnClose();
	EE.update.row_id = row_id;
	EE.update.col_id = col_id;
	EE.update.value = target.innerHTML;
	EE.update.td    = target;
	target.innerHTML = render(EE.tpl.input,EE.update);
	input = target.getElementsByTagName('INPUT')[0];
	input.focus();			// cursor to input
	//input.value = input.value;	// cursor to end
	input.selectionStart = input.selectionEnd = input.value.length; // cursor to end
	}
//alert([row,col])
}

EE.func.updateColumnReset = function()
{
EE.update.row_id = -1;
EE.update.col_id = -1;
EE.update.value = '';
EE.update.td    = null;
}

EE.func.updateColumnClose = function (el)
{
var id, value, row, row_id, col_id;
value = el ? el.value : EE.update.value;
if (EE.update.td)
	{
	value = trim(value);
//	EE.update.td.innerHTML = value;	 neni treba, protoze se prekresluje cela tabulka
	row_id = EE.update.row_id;
	col_id = EE.update.col_id;
	row = cloneArray1(EE.db.map[row_id]);
	row[col_id] = EE.func.dbFindAddValue(col_id,value);	// row undefined
//	EE.func.dbUpdate(EE.func.rowSelect(EE.update.row))
	EE.func.dbUpdate(row_id,row);
	ENG.func.ipShow();
	// sql update
//ENG.func.tableShow();
	}
EE.func.updateColumnReset();
//ENG.func.init();
}
*/

/*
EE.func.rowSelect = function(id)
{
out = [];
tr = 
for (i=0;i<row.length;i++)
	{
	out[i] = EE.func.dbFindAddValue(row[i]);
	}
}
//EE.func.updateColumnReset();
*/


//ENG.func.init({pref:'zas2', remove:[0], add:-1, row_id:0});
//ENG.func.init({pref:'zas2', remove:[0], add:-1, row_id:0});
ENG.func.init({pref:'zas2', remove:[
	1,//'statut',
	2,//'change_id',
	3,//'change_date',
	4//'change_user',
	], add:-1, col_row_id:0});
ENG.func.tableShow();
ENG.ss.func.init();			//search


// ss nefunguje dalsi sloupce!!! - uz jo
// ENG.func.colsWidth - pouzij to pro generovani tabulky, sirky bunek a inputu pro ss!!! proste prilep k te tabulce s daty navrch dalsi s vyhledavacimi policky.





/*
download by meli nabidnout jen linky na soubory
upload by se melo pokusit nahrat zmeny
pak by mel byt box, ktery zobrazuje history radky a upload radky
tlacitka view, history, edit
view - pokud je k dispocizi soubor, radky
history - totez
edit - jen pokud je to online / link na prejit online
*/



