// 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.unDiacritic = function (str)
	{
	// remove diacritics
	var a, b, chr, out, i;
	a = "徜栾殪礤掘篝鲟殱鵀聊认商团家釉掷妽谫茌貛";
	b = "aacdeeillnooorstuuuyrzAACDEEILLNOOORSTUUUYRZ";
	out = '';
	for(i = 0; i < str.length; i++)
		{
		chr = str.charAt(i);
		if (a.indexOf(chr) != -1)
			{
			chr = b.charAt(a.indexOf(chr));
			}
		out += chr;
		}
	return out;
	}


this.func.tableReadKeys = function(row,col_skip)
	{
	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++)
		{
//alert([col_skip,i])
		if (FILTER.func.arrayFindValue(col_skip,i))
			{continue;}
		val = row[i];
		key_all.by_id[i]     = val;
		key_all.by_name[val] = i;
		}
//alert(['tableReadKeys',key_all.by_id.join('\n'),'---',key_all.by_name.toSource()].join('\n'));	
	return key_all;
	}

this.func.tableReadFilters = function(arr, key_by_id, start)
	{
	root.func.log(root.name + '.func.tableReadFilters');
	var i, i_end, j, j_end, k, k_end, out, filter_name, key_by_id, key_by_name, col_id, ms, f, order_by;
	var start = isExist(start) ? start * 1 : 0;
	start = start>=0 ? start : 0;
//	f = root.table.key_all;
//	x = root.getTableKeys(arr);
//	key_by_id   = x.key_by_id;
//	key_by_name = x.key_by_name;
	// vyrobi filtry ze sloupcu tabulky ve tvaru out['FAKULTA_SP'] = ['text0','text1'...]
	ms = new MultiSortClass();
	out = [];
//	i_end = name_all.length;
	j_end = arr.length;
	i_end = key_by_id.length;
	for (i=0;i<i_end;i++)
		{
		if (!isExist(key_by_id[i]))	// vynech sloupce, ktera neexistuji v zahlavi csv
			{
			alert('createFilters: neexistuje sloupec ' + i);
			continue;
			}
		if (!isExist(out[i]))
			{
			out[i] = [];
			}
		k_end  = 0;
		for (j=start;j<j_end;j++)		// start=1 vynech prvni radek, to je zahlavi!
			{
//			if (!isExist(arr[j][key_id]) || (filter_name=='FAKULTA_VY' && arr[j][key_id]==''))	// vynech, pokud neni platna hodnota + vynechat, kdyz je to FAKULTA_VY a je prazdna
//				{continue;}
			for (k=0;k<k_end;k++)		// vyhledej, zda se neshoduje uz s ulozenym
				{
				if (out[i][k]==arr[j][i])
					{break;}
				}
			if (!(k<k_end))			// pridej novy
				{				
				out[i][k_end] = arr[j][i];
				k_end++;
				}
			}
		ms.func.setOpt([{'col':i, 'cmp':root.table.structure.by_id[i], 'order':'asc'}]);	// nastav funkci pro serazeni, provede validaci
//alert(ms.opt.source[0].toSource())
//alert(ms.opt.cmp[col_id].toSource())
		out[i].sort(ms.opt.cmp[i]);	// serad podle abecedy, precti funkci serazeni
		}
//alert(['words',out.toSource()])
//alert(filter_all['FAKULTA_SP'])
	return out;
	}




this.func.tableStructure = function(name_all)
	{
	var i, i_end, stru, val, val_all;
	val_all = [
	'strnum', 'str', 'strzasuvka','strdiakritika',
	'str', 'str', 'strdiakritika',
	'str', 'str', 'str', 'str', 'str',
	'str','str','str','str',
	'str','str','str','str','str',
	'str','str','str','str','str',
	'str'
	];
	stru = {};
	stru.by_id   = [];
	stru.by_name = {};
	i_end = name_all.length;
	for (i=0;i<i_end;i++)
		{
		val = isExist(val_all[i]) ? val_all[i] : 'str';
		stru.by_id[i] = val;
		stru.by_name[name_all[i]] = val;
		}
//alert(stru.toSource())
	return stru;
	}

this.func.tableOrderBy = function(arr,key_by_id,order_by_all)
	{
	root.func.log(root.name + '.func.tableOrderBy (' + arr.length + ')');
	if (!isArray(order_by_all))
		{return arr;}
//alert(order_by.toSource());
	var i, i_end, opt,j,a,b,c, ms, row;
	ms  = new MultiSortClass();
	opt = [];
	j   = 0;
	i_end = order_by_all.length;
	for (i=0;i<i_end;i++)
		{
		row = order_by_all[i];
		if (isExist(row.col) && isExist(key_by_id[row.col]))
			{
			a = row.col;
			b = isExist(row.cmp) ? row.cmp : '';	// MS si sam vyradi neexistujici sort funkci
			c = isExist(row.order) && row.order=='desc' ? 'desc' : 'asc';
			opt[j] = {col:a, cmp:b, order:c};
			j++;
			}
		}
//	opt = [
//		{col:5,cmp:'str',order:'asc'},	// ucitel jmeno
//		{col:9,cmp:'str',order:'asc'}	// predmet text
//	]
	if (!isArray(opt))
		{
		return arr;
		}
	root.order_by = opt;
	ms.func.setOpt(opt);
	arr.sort(ms.cmp);
	return arr;
	}

this.func.htmlCreateHead = function(key_all)
	{
	root.func.log(root.name + '.func.htmlCreateHead');
	var tpl, arr, i, j, i_end, str, word;
	tpl = {};
	tpl.all = "\n"+'\
<div class="fw">{text}</div>\
';
	tpl.text_butt = "\n"+'\
<div class="search">{text}</div>\
';
	tpl.text = "\n"+'\
<input type="text" name="{name}" id="{id}" value="{value}" onkeyup="{onkeyup}" placeholder="{placeholder}" class="{css}">{text}\
';
//style="{css}" 
	tpl.butt = "\n"+'\
<input type="button" onclick="{onclick}" class="butt hover" value="&DownArrow;">\
';
	tpl.container = "\n"+'\
<div id="{id}" class="container"><\/div>\
';
	tpl.order = "\n"+'\
<div onclick="{onclick}" class="fms hover" title="{col_id} {type} {css}">{text}&nbsp;<span class="{css}">{butt}<\/span><\/div>\
';
//<div onclick="{onclick}" class="fms hover">{text}&nbsp;<span class="{css}">{butt}<\/span><br><span class="type">{type}<\/span><\/div>\
	// --- fw ---
var bool;
	j      = 0;
	arr    = [];
	arr[j] = []
	i_end = key_all.length;
	for (i=0;i<i_end;i++)
		{
		name = key_all[i];
//		word = isExist(root.fw.word) && isExist(root.fw.word[i]) ? root.fw.word[i] : '';
//		css  = isExist(root.fw.checked) && isExist(root.fw.word[i]) ? root.fw.word[i] : '';
		word = root.fw.func.getWord(i);
		bool = root.fw.func.getCountMax(i);
		css  = bool[0]==true ? 'error' : bool[1]==false ? 'success' : '';
		str  = '';
		str += render(tpl.text,{
			'name'   : 'fw_search_' + i,
			'id'     : 'fw_search_' + i,
			'value'  : word,
			'placeholder': name,
			'text'   : '',
			'onkeyup': 'APP.fw.func.filterSearchKeyUp(event);',
			'onblur' : 'APP.fw.func.writingEnd();',
			'css'    : css
			});
		str += render(tpl.butt,{
			'onclick': 'APP.fw.func.filterOpenClick(this,'+i+');'
			});
//alert(str)
		str  = render(tpl.text_butt,{
			'text': str
			});
		str += render(tpl.container,{
			'id': 'fw_container_' + i
			});
		arr[j][i] = render(tpl.all,{
			'text': str
			});
		}
	j++;
//	arr[j++] = arrayClone1(key_all);


	arr[j] = [];
	// --- fms ---
	var order_by_all, order_by, data_all, i, i_end, type_all, type, name;
	order_by_all = root.fms.order_by_all;
	data_all = {
		// name: icon, css
		'none' : ['&#9651;', 'order none'],
		'asc'  : ['&#9650;', 'order asc'],
		'desc' : ['&#9660;', 'order desc']
		}
	type_all   = [];
	i_end = key_all.length;
	for (i=0;i<i_end;i++)
		{
		type_all[i] = 'none';
		}
	if (isArray(order_by_all))
		{
		i_end = order_by_all.length;
		for (i=0;i<i_end;i++)
			{
			order_by = order_by_all[i];
			if (!isExist(type_all[order_by.col]))
				{
				continue;
				}
			type_all[order_by.col] = order_by.order;
			}
		}
	i_end = key_all.length;
	for (i=0;i<i_end;i++)
		{
		name = key_all[i];
		type = type_all[i];
		arr[j][i] = render(tpl.order,{
			'col_id' : i,
			'text'   : name,
			'butt'   : data_all[type][0],
			'type'   : root.table.structure.by_id[i],
			'css'    : data_all[type][1],
			'onclick': 'APP.fms.func.filterChangeClick(this,'+i+');'
			});
		}
//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;
	}

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.func.tableApplyFilters(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  = '';
	str += HTML.func.createTable(1, arr, head, [], 0, root.tbl.end, root.tbl.row_id, ['<small>'+root.stat.rows.a+' / '+root.stat.rows.b+'<\/small>','']);
	SCREEN.func.table(str);
	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
	arr = FILTER.func.addRowId(arr);
	root.tbl.start  = 1;
	root.tbl.end    = arr.length;
	root.filter_rows.start = 1;
	root.filter_rows.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], col_skip);	// 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();
	APP.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.func.init(opt);
}



var APP, 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: [
			]
		}
	};
APP = new classApp(opt);
//APP.file.func.import();
APP.open.func.htmlNavCreate([]);
APP.open.func.openFromUrl(location.href,'zas_bn13.csv');