// filter word treba dodelat. Filtruje slova, ale zatim se to neprojevuje na tabulce


function classAppEdit(opt)
{
var root = this;
this.name = 'classApp';

this.tbl = {};		// start: 0, end: 1
this.filter_rows = {};	// start: 0, end: 1
this.table = {};	// table options
this.table.structure = {};
this.table.key_all = {};
this.table.filter_all = {};
this.filex = {};


this.event = {};
this.event.func = {};

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

this.func = {};

this.func.log = null;


this.func.tableReadKeys = function(row)
	{
	root.func.log(root.name + '.func.tableReadKeys');
	var i, i_end, val, key_all;
	key_all = {};
	key_all.by_id   = [];
	key_all.by_name = {};
	i_end = row.length;
	for (i=0;i<i_end;i++)
		{
		val = row[i];
		key_all.by_id[i]     = val;
		key_all.by_name[val] = i;
		}
	return key_all;
	}






this.func.htmlCreateHead = function(key_by_id)
	{
	root.func.log(root.name + '.func.htmlCreateHead');
	var tpl, arr, i, j, i_end, str, word;
	tpl = {};
	tpl.th = '{text}';
	// --- table head ---
	j      = 0;
	arr    = [];
	arr[j] = [];
	i_end  = key_by_id.length;
/*
	for (i=0;i<i_end;i++)
		{
		arr[j][i] = '';
		}
	j++;
	arr[j] = [];
*/
	for (i=0;i<i_end;i++)
		{
		name = key_by_id[i];
		arr[j][i] = render(tpl.th,{
//			'text': escapeHtml(name)
			'text': '<span title="'+escapeHtml(name)+'">'+escapeHtml(name)+'</span>'
			});
		}
//	j++;
//alert(arr);
	return arr;
	}

/*
this.func.tableApplyFilters = function(arr)
	{
	var key_by_id;
	key_by_id = root.table.key_all.by_id;
	arr = arrayClone2(arr);
	root.func.log('classArrayFilters.func.where (' + arr.length + ', start='+root.tbl.start+')');
	arr = FILTER.func.where(arr, key_by_id, root.table.filter_all, root.fw.checked, root.tbl.start);
	arr = root.func.tableOrderBy(arr, key_by_id, root.fms.order_by_all);
	return arr;
	}
*/

function cloneWidth(div0,div1)
	{
	var i, i_end, div0_tbl, div1_tbl, div0_tr, div0_th, div1_tr, div1_th;
//alert(div0.getElementsByTagName('TABLE')[0].offsetWidth)
//alert(div1.getElementsByTagName('TABLE')[0].offsetWidth)

div0_tbl = div0.getElementsByTagName('TABLE')[0]
div1_tbl = div1.getElementsByTagName('TABLE')[0]
div1_tbl.style.width = div0_tbl.offsetWidth + 'px';
//div1_tbl.style.tableLayout = 'fixed';

	div0_tr = div0.getElementsByTagName('TR')[0]
	div0_th = div0_tr.getElementsByTagName('TH');
	div1_tr = div1.getElementsByTagName('TR')[0]
	div1_th = div1_tr.getElementsByTagName('TH');
	i_end = div0_th.length;
	for (i=0;i<i_end;i++)
		{
		div1_th[i].style.width = (div0_th[i].offsetWidth - 14 - 1) + 'px';	// -padding, border
//		div1_th[i].innerHTML = div0_th[i].offsetWidth+'<br>'+(div1_th[i].offsetWidth);
//		div1_th[i].innerHTML = div1_th[i].offsetWidth;
		}
//div1.getElementsByTagName('TABLE')[0].style.width = div0.getElementsByTagName('TABLE')[0].offsetWidth + 'px';
//	obj1.style.width = obj0.offsetWidth + 'px';
	}

function clone2(div0,div1)
	{
	var i, i_end, div0_tr, div0_th, div1_tr, div1_th;
t0 = div0.getElementsByTagName('TABLE')[0]
t1 = div1.getElementsByTagName('TABLE')[0]
	div0_tr = div0.getElementsByTagName('TR')[0]
	var clone = div0_tr.cloneNode(true);
	t1.getElementsByTagName('THEAD')[0].appendChild(clone); 
	}

this.func.tableClick = function(event)
	{
	var ev_data, el, pos;
	ev_data = root.event.func.read(event);
	el      = ev_data.target;
	if (el.nodeName=='TD')
		{
//		pos_tbl = getPos($('table'), false, false);
//		pos = getPos(el, true, true)
//		$('cur').style.left = pos.x + pos_tbl.x + 'px';
//		$('cur').style.top  = pos.y + pos_tbl.y + 'px';
//		$('cur').getElementsByTagName('INPUT')[0].focus();
		}
	
	}

this.func.tableApplyChanges = function()
	{
	PERF.getTime();
	root.func.log(root.name + '.func.tableApplyChanges');
	var head, str, arr, key_by_id, el;
	key_by_id = root.table.key_all.by_id;
	root.stat.rows   = {};
	arr  = root.table.data;
	root.stat.rows.a = arr.length;
	root.stat.rows.b = root.tbl.end - root.tbl.start;
//	root.func.log(Math.floor(PERF.getTime()));
//	root.fms.func.tableReadFMS();
	head = root.func.htmlCreateHead(key_by_id);
//	root.func.log(Math.floor(PERF.getTime()));
	str  = HTML.func.createTable(2, arr, head, [], root.tbl.start, root.tbl.end, root.tbl.row_id, []);
	SCREEN.func.table(str);

//	$('table').onclick = root.func.tableClick;
	$('table').onclick = root.edit.func.open;

	str  = HTML.func.createTable(2, [], head, [], root.tbl.start, root.tbl.end, root.tbl.row_id, []);
	SCREEN.func.fixed1(str);
	cloneWidth($('table'),$('fixed1'));
	scrollFixed();
//	SCREEN.func.fixed1('<table class="tbl"><thead></thead></table>');
//	clone2($('table'),$('fixed1'));
	
//	root.fw.func.containerCloseAll();
//	root.fw.func.focus();
	root.func.log(Math.floor(PERF.getTime()));
	}



this.file = {};
this.file.func = {};

this.file.func.exportAll = function()
	{
	READER.func.saveTextAsFile(root.filex.export_name_all, CSV.export(root.table.data));
	}


this.file.func.importCB1 = function(str)
	{
	var arr, str, head,skip;
	root.func.log(root.name + '.func.fileImportCB1');
	arr = CSV.import(str);
	root.func.log(Math.floor(PERF.getTime()));
//	root.tbl.row_id = arr[0].length;	// position row_id at end
	root.tbl.start  = 1;
	root.tbl.end    = arr.length;
//	str  = '';
//	col_skip   = [root.tbl.row_id];
	root.table = {};
	root.table.data       = arr;
	root.table.key_all    = root.func.tableReadKeys(arr[0], []);	// vynech posledni sloupec (id radku)
	key_by_id = root.table.key_all.by_id;

	root.func.log(Math.floor(PERF.getTime()));
	root.func.tableApplyChanges();
	}

this.file.func.import = function()
	{
	root.func.log(root.name + '.func.fileImport');
//	path = 'actual/zas.csv';	// disk
//	path = '../actual/zas.csv';	// aura
//	url = path;
	READER.func.init({log:SCREEN.log, cbEnd:root.file.func.importCB1});
	READER.func.fileFromUrl(root.filex.import_root + root.filex.import_path);
	}

this.stat = {};
this.stat.rows = {};
this.stat.func = {};



this.open = {}
this.open.files = [];
this.open.func = {};

this.open.func.readUrlParams = function(url)
	{
	var dict, str;
	dict = {};
	str = url.replace(/^.*?\?|\#.*$/g,'');	// remove XXX?...#XXX
	str.split("&").forEach(
		function(item)
			{
			arr = item.split("=");
			dict[unEscapeUrl(arr[0])] = unEscapeUrl(arr[1]);
			}
		);
	return dict;
	//alert(dict.toSource());
	}

this.open.func.readUrlServer = function(url)
	{
	return url.replace(/^.*?\/+(.*?)\/+.*$/g,'$1');	// remove XXX//.../XXX
//	 file:///C: | // http://localhost | // http://webapp
	}

this.open.func.openFromUrl = function(url,def)
	{
//alert(url);
	var dict, server, opt;
	dict   = root.open.func.readUrlParams(url);
	server = root.open.func.readUrlServer(url);
//alert(server)
//alert(dict.toSource())
	if (!isExist(dict['file']) && isExist(def))
		{
		dict['file'] = def;
		}
	if (!isExist(dict['file']))
		{
		SCREEN.func.message('openFromUrl: Neplatny nazev souboru v url.','error');
		return;
		}
	path = (server=='webapp.fpf.slu.cz' || server=='localhost' ? 'zas3-view.php?file=' : 'actual/') + dict['file'];
	opt = {
		data: {
			filex: {
				import_root: '',
				import_path: path,
				export_name_all     : dict['file'],
				export_name_filtered: dict['file']
				}
			}
		};
	//alert(opt.toSource())
	root.func.init(opt);
	root.file.func.import();
	root.open.func.htmlNavCreate([dict['file']]);
	}

this.open.func.htmlNavCreate = function(selected)
	{
	var selected = isArray(selected) ? selected : [];
	root.open.files = [
		{file:'zas_bn13.csv'},
		{file:'zas_bn14.csv'},
		{file:'zas_h17.csv'},
		{file:'zas_h10.csv'}
		];
	var tpl, str, i, i_end, item_,url;
	tpl   = {};
	tpl.a = '<span class="butt {class}"><a href="{url}" title="{title}">{name}</a></span>';
	url   = '?file=';
	path  = ''
	str   = '';
	item_all = root.open.files;
	i_end = item_all.length;
	for (i=0;i<i_end;i++)
		{
		item_ = item_all[i];
		item_.name  = escapeHtml(item_.file.replace(/.*?\_([a-z0-9]+)\..*/g,'$1'));	// odstran vse pred '_' a vse za '.'
		item_.title = item_.name;
		item_.class = arrayFindIndex(selected,item_.file)!==false ? 'sel' : '';
		item_.url   = escapeHtml(url + escapeUrl(path + item_.file));
		str  += (str.length>0 ? ' ': '') + render(tpl.a,item_);
		}
	$('nav').innerHTML = str;
	}


this.func.init = function(opt)
	{
	var bool, i, j;
	if (root.func.log)
		{
		root.func.log(root.name + '.func.init');
		}
	if (!isObject(opt))
		{
		return;
		}
	if (isObject(opt.func))
		{
		for (i in opt.func)
			{
			if (isFunction(opt.func[i]))
				{
				root.func[i] = opt.func[i];
				}
			}
		}
	if (isObject(opt.data))
		{
		for (i in opt.data)
			{
			if (isObject(opt.data[i]))
				{
//				if (i=='fmsx' || i=='fwx')
//					{continue;}
				if (!isObject(root[i]))
					{
					root[i] = {};
					}
				for (j in opt.data[i])
					{
					root[i][j] = opt.data[i][j];
					}
				}
			}
//		if (isArray(opt.data['fmsx']))
//			{
//			root.fms['fmsx'] = opt.data['fmsx'];
//			}
//		if (isArray(opt.data['fwx']))
//			{
//			root.fms['fwx'] = opt.data['fwx'];
//			}
		}
	}

this.edit = {};
this.edit.input = null;
this.edit.func = {};

this.edit.func.dataUpdate = function(row_id,col_id,str)
	{
	root.table.data[row_id][col_id] = str;
	}

this.edit.func.close = function()
	{
	var el;
	if (root.edit.input!=null)
		{
		el = root.edit.input;
		el.parentNode.innerHTML = el.value;
// x,y el.parentNode.neco
		root.edit.func.dataUpdate(el.value);
		}
	root.edit.input = null;
	}

this.edit.func.inputCreate = function(el)
	{
	el.innerHTML = '<input style="width:100%;border:0 solid;" value="'+el.innerHTML+'">';
	el = el.getElementsByTagName('INPUT')[0];
	el.focus();
	root.edit.input = el;
	}

this.edit.func.open = function(event)
	{
	var ev_data, el;
	root.edit.func.close();
	ev_data = root.event.func.read(event);
	el = ev_data.target;
	if (isExist(el) && el.nodeName=='TD')
		{
		root.edit.func.inputCreate(el);
		}
	}

this.func.init(opt);
}



var APPEdit, opt;
opt = {
	func: {log: SCREEN.log},
	data: {
		filex: {
//			import_root: 'file:///C:/pp/js-zas3/',				// mlich
//			import_root: 'file:///C://Users/vlha/Downloads/Tajemnik/',	// vlha
			import_root: '',
			import_path: 'actual/zas.csv',	// disk
			export_name_all     : 'zas_bn13.csv',
			export_name_filtered: 'zas_bn13.csv'
			}
//		fmsx: [
//			{'col':3, 'order':'asc'},
//			{'col':1, 'order':'asc'}
//			],
//		fwx: [
//			]
		}
	};
APPEdit = new classAppEdit(opt);
//APP.file.func.import();
APPEdit.open.func.htmlNavCreate([]);
APPEdit.open.func.openFromUrl(location.href,'zas_bn13.csv');


function getPos(el, scroll_left, scroll_top)
	{
	var scr;
	scr = document.documentElement || document.body;
	return {
		x: el.offsetLeft + (scroll_left ? (scr.scrollLeft || scr.clientLeft) : 0),
		y: el.offsetTop  + (scroll_top  ? (scr.scrollTop  || scr.clientTop ) : 0)
		}
	}

function scrollFixed()
	{
	var fix = $('fixed1');
	var tbl = $('table');
	var pos = getPos(tbl, false, true);
//	body = document.documentElement || document.body;
//	fix.style.position = 'absolute';
//	fix.style.left = (tbl.offsetLeft) + 'px';	// + (body.scrollLeft || body.clientLeft)
//	fix.style.top  = (tbl.offsetTop  + (body.scrollTop  || body.clientTop))  + 'px';
	fix.style.left = pos.x + 'px';
	fix.style.top  = pos.y + 'px';
	}

window.onscroll = scrollFixed;
