//
//***********************************************************************
//																																			*
// This file is part of the "fubagToobox" System		 										*
// Author:	Marko Seidel																								*
// Copyright (C) 2021, archium GmbH																			*
//																																			*
//***********************************************************************
//
/**
= Creative Commons Lizenzvertrag =
Diese Software ist von der archium GmbH, Gera ist lizenziert unter einer Creative Commons Namensnennung - Nicht kommerziell - Keine Bearbeitungen 4.0 International Lizenz. (http://creativecommons.org/licenses/by-nc-nd/4.0/deed.de)
Individuelle über diese Lizenz hinausgehende Berechtigungen können Sie unter https://archium.org erhalten.

= Creative Commons License =
Software by archium GmbH, Gera is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. (http://creativecommons.org/licenses/by-nc-nd/4.0/)
Individual permissions beyond the scope of this license may be available at https://archium.org.
**/
// verbiete dragging aller "anchor" <a>..</a>
function disableAnchor(){
	$('a').on('dragstart', function(event){ 
		return false; 
	});
}

function usetheme(_theme){ // theme setzen
	window.setTimeout(function () {
		app.themechange(_theme);
	}, 100);
}

const eProj = 0;
const eHead = 1;
const eMenu = 2;
const eData = 3;
const eProp = 4;
const eThem = 5;
const eDone = 6;
//
var ebody = undefined;
var isprogress = 0;
//
var events = []; // event-kette
events[eProj] = new CustomEvent ('proj', 	{ detail: {next:'head', actual:'proj'}, bubbles : true, cancelable: true, composed: false });
events[eHead] = new CustomEvent ('head', 	{ detail: {next:'menu', actual:'head'}, bubbles : true, cancelable: true, composed: false });
events[eMenu] = new CustomEvent ('menu', 	{ detail: {next:'data', actual:'menu'}, bubbles : true, cancelable: true, composed: false });
events[eData] = new CustomEvent ('data', 	{ detail: {next:'prop', actual:'data'}, bubbles : true, cancelable: true, composed: false });
events[eProp] = new CustomEvent ('prop', 	{ detail: {next:'them', actual:'prop'}, bubbles : true, cancelable: true, composed: false });
events[eThem] = new CustomEvent ('them', 	{ detail: {next:'done', actual:'them'}, bubbles : true, cancelable: true, composed: false });
events[eDone] = new CustomEvent ('done', 	{ detail: {next:'done', actual:'done'}, bubbles : true, cancelable: true, composed: false });
var actualevent = events[eProj];

function callevents(_elem, _event){
	if (_elem != null){
		if (_event != null){
			// console.log('callevents:', _event, _elem);
			_elem.dispatchEvent(_event);
		}
	}
}

function handleevents(e){
	var caption = '..load dataverse';
	if (e == undefined){
		timestart = Date.now()
		console.log('start events..');
		caption = '..load project';
		actualevent = events[eProj]; ebody.addEventListener('proj', function(e){ handleevents(e); }, false); app.module[app.active_module].getproject('project');
		isprogress = 0;
		app.waitpos = 0;
		app.waitmax = 100;
		app.waittitle('Please wait..', caption, true);
		var bar = $.messager.progress('bar');
		bar.progressbar({
			text: '{value}%'
		});
	}else{
		switch (e.detail.actual){
			case "proj":	{ isprogress+=	15; caption = '..load head';						actualevent = events[eHead]; ebody.removeEventListener('proj', handleevents); ebody.addEventListener('head', handleevents, false); app.module[app.active_module].getelements('head', '');break; }
			case "head": 	{ isprogress+=	15; caption = '..load menu';						actualevent = events[eMenu]; ebody.removeEventListener('head', handleevents); ebody.addEventListener('menu', handleevents, false); app.module[app.active_module].getelements('menu', '');break; }
			case "menu": 	{ isprogress+=	15; caption = '..load datagrids';				actualevent = events[eData]; ebody.removeEventListener('menu', handleevents); ebody.addEventListener('data', handleevents, false); app.module[app.active_module].getelements('datagrid', 'dataverse;dataset;user'); disableAnchor();break; }
			case "data":	{ isprogress+=	15; caption = '..load properties';			actualevent = events[eProp]; ebody.removeEventListener('data', handleevents); ebody.addEventListener('prop', handleevents, false); app.module[app.active_module].getelements2('propgrid', 'file;search');break; }
			case "prop":	{ isprogress+=	15; caption = '..load themes';					actualevent = events[eThem]; ebody.removeEventListener('prop', handleevents); ebody.addEventListener('them', handleevents, false); app.module[app.active_module].getthemes();break; }
			case "them":	{ isprogress+=	15; caption = '..closing up';						actualevent = events[eDone]; ebody.removeEventListener('them', handleevents); ebody.addEventListener('done', handleevents, false); app.module[app.active_module].done();break; }
			case "done":		isprogress = 100; caption = '..successfully loaded';	actualevent = null; 				 ebody.removeEventListener('done', handleevents); break;
		}
		app.waittitle('Please wait..', caption);
		app.waitprogress(isprogress, 'callevents', e.detail.actual);
		// console.log('next event..', isprogress, e.detail);
	}
}

function loadIndex() { // startsequenz
 	//
	app.getID(true);
 	ebody = document;
	handleevents(undefined);
}

function getlayout(_prefix, _sub, _suffix) { // layout-initialisierung
	var html = '';
	html+= '<div id="printMessage" class="dataContainer" style="display: none;">';
	html+= '	<p style="font-size: 30px;">Druck wird ausgeführt...</p>';
	html+= '</div>';
	// 
	return html;
}

// ### ######################################################################
// ### initialisierung
// 
app.active_module 										= 'archium';
app.trans.items 											= 'Entries';
// modul-variable als object
app.module[app.active_module] 				= app.module[app.active_module] || {};
app.module[app.active_module].prefix	= 'frm_';
app.module[app.active_module].sub 		= 'data';
app.module[app.active_module].suffix 	= '_edit';
app.module[app.active_module].project = 'archium'; //standard
app.module[app.active_module].layout	 = 'layout_archium';
app.module[app.active_module].region	 = 'region_archium';
app.module[app.active_module].titletab	= ''; 
app.module[app.active_module].titlepan	= '';
//
app.module[app.active_module].svgobject = {} // svg-pfade
app.module[app.active_module].alias 		= '';
app.module[app.active_module].root			= undefined;
app.module[app.active_module].node			= null;
app.module[app.active_module].menu			= null;
app.module[app.active_module].selitem	 = app.makeStruct('id type alias');
app.module[app.active_module].selparent = app.makeStruct('id type alias');
app.module[app.active_module].selected	= new app.module[app.active_module].selitem('1', '', 'root');
//
app.module[app.active_module].searchresult = []; // search-result
app.module[app.active_module].searchheader = {}; // search-header (dataset, file)

// ### ######################################################################
// ### json handling -	start
// ### 
// ### parameter vorbelegen
app.module[app.active_module].getparams = app.module[app.active_module].getparams || function(_from, _type, _what, _who){
	var params = {suid:app.getID()};
	params.from = _from; // 'db', 'file', 'dataverse' oder andere
	params.type = _type;
	params.func = 'getHtml';
	params.what = _what;
	params.who 	= _who;
	params.user = app.user_id;
	params.modl = app.active_module;
	params.info = 'read '+_from+' > '+_what+' > '+_who+'?';
	params.suff = _what;
	params.alias = "root"
	params.refr = true;
	params.proj = app.module[app.active_module].project
	// 
	return params
}

app.module[app.active_module].done = app.module[app.active_module].done || function(){
	app.waitclose(isprogress);
	console.log('all events done!');
}

// ### themes laden (vom server)
app.module[app.active_module].getthemes = app.module[app.active_module].getthemes || function(_this){
 	var params = app.module[app.active_module].getparams('db', 'json', 'params', 'get.themes');
 	params.func = 'getParams';
 	//
 	// console.log('getthemes(before):', params, $(_this), ebody);
 	$.postJSON('', params, function(_data){
 	 	app.message(_data.msg);
 	 	if (_data.success == true){ 
 	 	 	// console.log('getthemes(data):', params.what, 'received :', _data, $(_this));
 	 	 	$('#head_theme').combobox('loadData', _data.themes.data);// combo füllen
			}else{
		}
 	 	//
		callevents(ebody, actualevent);
 	 	//
	},function(jqxhr, textStatus){
		//
	});
}

app.module[app.active_module].loadIndex = app.module[app.active_module].loadIndex || function(){
	__win_reload(this);
}

// ### elemente laden (vom server)
app.module[app.active_module].getelements = app.module[app.active_module].getelements || function(_what, _who){
	var ln = app.module[app.active_module].layout;
	// console.log(_what, 'to get:', _what, '"', _who, '"');
	var layout = document.getElementById(ln);
	if (layout !== null){
		app.module[app.active_module].record = null;
		var who = _who+''
		var loop = who.split(';')
		var params = app.module[app.active_module].getparams('db', 'html', _what, '');
		// console.log('getelements():', params.what, 'request:', params);
		$.postJSON('', params, function(_data){
			// console.log('getelements(data):', _data);
			switch (params.what) {
				case 'svg':{ // svg
					break;
				}
				default:{ // datagrid, propgrid, files...
					if ((params.what == 'datagrid') || (params.what == 'head') || (params.what == 'menu')){ 
						for (var i=0;i<loop.length;i++) {
							ln = 'layout_'+params.proj+'_'+params.what
							if (loop[i] > ''){
								ln = ln+'_'+loop[i]
							}
							// console.log(params.what, 'received 4:', '"', ln,'"');
							var dg = 'dg_'+params.proj+'_'+params.what+'_'+loop[i];
							if (typeof _data === 'string'){ // html (string) aufbereiten 
								repl = _data.replace('%dg%', dg);
								switch(loop[i]){
									case 'dataverse':
									repl = repl.replace('%idfield%', 'id');
									break;
									case 'dataset':
									repl = repl.replace('%idfield%', 'datasetId');
									break;
								}
								// console.log('getelements():', params.what, 'received (',i,'):', '"', ln,'"', '"', dg,'"', '"', pg,'"', repl );
								data = JSON.parse(repl); // objekt aus "string" erstellen
								if (i == 0){ // bei mehreren elementen, fehler nur im ersten durchlauf anzeigen
									app.message(data.msg);
								}
							}
							if (data.success == true) {	
								// console.log('getelements():', params.what, 'received 5:', '"', ln,'"', data);
								layoutbase = document.getElementById(ln);
								if (layoutbase !== null){
									// console.log('getelements():',	params.what, 'received 6:', '"', ln,'"', data);
									$(layoutbase).empty(); // niemals 2-mal einfügen, deshalb evtl. vorher leeren..
									$(layoutbase).append(data.html);// menü, grid ... usw. füllen
									app.easyui(layout);
									// console.log(params.what, 'getelements:', _what, loop[i], '"', _who,'"');
									window.setTimeout(function (_what, _loop) {
										switch(params.what){
											case 'menu':
											app.module[app.active_module].loadmenu(this);
											// callevents(ebody, actualevent);
											break;
											case 'datagrid':
											app.module[app.active_module].loadgrid(this, _what, _loop, "root", "root");
											callevents(ebody, actualevent);
											break;
											default:
											callevents(ebody, actualevent);
										}
										disableAnchor();
									}(params.what, loop[i]), 30);
									}else{
									// console.log('element "', ln, '" not found.');
								}
							}
						}
					}
				}
			}
		},function(jqxhr, textStatus){
			//
		});
		}else{
		// console.log('element "', ln, '" not found.');
	}
};

// ### elemente laden (vom server)
app.module[app.active_module].getelements2 = app.module[app.active_module].getelements2 || function(_what, _who){
	var ln = app.module[app.active_module].layout;
	// console.log(_what, 'to get:', _what, '"', _who, '"');
	var layout = document.getElementById(ln);
	if (layout !== null){
		app.module[app.active_module].record = null;
		var who = _who+''
		var loop = who.split(';')
		var params = app.module[app.active_module].getparams('db', 'html', _what, '')
		// console.log('getelements2():', params.what, 'request:', params);
		$.postJSON('', params, function(_data){
			// console.log('getelements2(data):', _data);
			switch (params.what) {
				case 'svg':{ // svg
					break;
				}
				default:{ // datagrid, propgrid, files...
					if (typeof _data === 'string'){ // html (string) aufbereiten 
						repl = _data;
						if (params.what == 'propgrid'){ 
							var ln = 'layout_'+params.proj+'_'+params.what;
							for (var i=0;i<loop.length;i++) {
								// console.log(params.what, 'received 4:', '"', ln,'"');
								var pg = 'pg_'+params.proj+'_'+params.what+'_'+loop[i];
								switch(loop[i]){
									case 'file':
									repl = repl.replace('%pg_file%', pg);
									repl = repl.replace('%id_file%', 'file_id');
									break;
									case 'search':
									repl = repl.replace('%pg_search%', pg);
									repl = repl.replace('%id_search%', 'file_id');
									break;
								}
							}
							// console.log('getelements():', params.what, 'received (',i,'):', '"', ln,'"', '"', dg,'"', '"', pg,'"', repl );
							data = JSON.parse(repl); // objekt aus "string" erstellen
							app.message(data.msg);
							if (data.success == true) {	
								// console.log('getelements2():', params.what, 'received:', ln);
								// console.log('getelements():', params.what, 'received 5:', '"', ln,'"', data);
								layoutbase = document.getElementById(ln);
								if (layoutbase !== null){
									// console.log('getelements():',	params.what, 'received 6:', $(layoutbase));
									$(layoutbase).empty(); // niemals 2-mal einfügen, deshalb evtl. vorher leeren..
									$(layoutbase).append(data.html);// menü, grid ... usw. füllen
									app.easyui(layout);
									// console.log(params.what, 'getelements:', _what, loop[i], '"', _who,'"');
									window.setTimeout(function (_proj, _what) {
										// console.log('getelements:', _proj, _what);
										var tabs = '#tabs_'+_proj+'_'+_what
										var tab = $(tabs).tabs('getTab', 1);
										tab.panel('options').tab.hide();
										disableAnchor();
 	 	 	 	 	 	 	 	 	 	//
										callevents(ebody, actualevent);
 	 	 	 	 	 	 	 	 	 	//
										window.setTimeout(function () {
											app.module[app.active_module].menu = $('.easyui-tree')
											if (app.module[app.active_module].menu.length > 0){
												if (!app.module[app.active_module].node){
													app.module[app.active_module].node = app.module[app.active_module].root[0]; // achtung, mehrere roots möglich
												}
												app.module[app.active_module].expandnodetree(app.module[app.active_module].menu, app.module[app.active_module].node);
												$('#AC_menu_refresh').linkbutton('disable');
											}							
										}, 10);
									}(app.module[app.active_module].project, params.what), 100);
									}else{
									// console.log('element "', ln, '" not found.');
								}
							}
						}
					}
				}
			}
		},function(jqxhr, textStatus){
			//
		});
		}else{
		// console.log('element "', ln, '" not found.');
	}
};

// ### projekt laden (vom server)
app.module[app.active_module].getproject = app.module[app.active_module].getproject || function(_what){
	// show progress
	$('.easyui-tree').tree('loadData', []); // menü leeren
	// 
	var params = app.module[app.active_module].getparams('db', 'json', _what, '')
	params.func = 'getParams';
	// 
	//console.log(params.what, ' request:', params);
	$.postJSON('', params, function(_data){
		// console.log('getproject(data):', _data);
		app.message(_data.msg);
		if (_data.success == true){ 
			app.local_ip = _data.localip; 
			app.local_port = _data.localport; 
			app.module[app.active_module].project = _data.project;
			app.module[app.active_module].layout = 'layout_'+_data.project;
			app.module[app.active_module].region = 'region_'+_data.project;
      app.module[app.active_module].alias = _data.alias;
			window.setTimeout(function(){
				app.module[app.active_module].getsvg('getsvg', 'dataverse;dataset;datafile;', 'matrix(1.1,0,0,1.1,0,0)', 14, 14, '0 0 16 16');
			}, 100);
 	 	 	//
			callevents(ebody, actualevent);
		}
	},function(jqxhr, textStatus){
		//
	});
	// 
}

// ### svg laden (vom server) ... momentan n.b.
app.module[app.active_module].getsvg = app.module[app.active_module].getsvg || function(_what, _name, _matrix, _width, _height, _viewbox){
	// console.log('getsvg(request):', _what, ':', _name, _matrix, _width, _height, _viewbox);
	var params = app.module[app.active_module].getparams('modul', 'json', _what, '')
	params.func = 'getParams';
	if (_name.length > 0){
		params.who = (_name)?_name:'';
		params.widt = (_width)?_width:30;
		params.heit = (_height)?_height:30;
		params.matx = (_matrix)?_matrix:'matrix(1.1,0,0,1.1,0,0)';
		params.view = (_viewbox)?_viewbox:'0 0 16 16';
		// console.log('getsvg(request):', params.what, ':', params);
		// 
		$.postJSON('', params, function(_data){
			app.message(_data.msg);
			console.log('getsvg received (',params.what ,'):', _data);
			if (_data.success == true) {	
				if (_data.svgobject){
					if (typeof _data.svgobject == 'object'){
						app.module[app.active_module].svgobject = _data.svgobject;
						console.log('postJSON received data: ', _data.total, 'x', params.what);
					}
				}
			}
		},function(jqxhr, textStatus){
			//
		});
	}
}

// ### menü laden (vom server)
app.module[app.active_module].loadmenu = app.module[app.active_module].loadmenu || function(_this){
	// console.log('loadmenu:', $('.easyui-tree'))
	var params = app.module[app.active_module].getparams('dataverse', 'json', 'menu', '')
	params.func = 'getValues';
	// 
	// console.log(params.what, ' request:', params);
	$.postJSON('', params, function(_data){
		// console.log(params.what, ' received:', data);
		app.message(_data.msg);
		if (_data.success == true){ 
			// app.waittitle('Please wait..', '..show menu');
			app.module[app.active_module].menu = $('.easyui-tree')
			if (app.module[app.active_module].menu.length > 0){
				// console.log(params.what, ' received(rows):', _data["rows"]);
				app.module[app.active_module].menu.tree('loadData', _data.rows);// menü füllen
				app.module[app.active_module].menu.tree('collapseAll');
				//
				app.module[app.active_module].node = null;
				app.module[app.active_module].root = app.module[app.active_module].menu.tree('getRoots');
				$.easyui.forEach(app.module[app.active_module].root, true, function(node){
					// console.log(app.module[app.active_module].root, node)	 
					if (node.attributes){
						if (node.attributes.alias != 'root'){
							if (node.attributes.datasetPid){ // achtung, mehrere roots möglich
								if (node.attributes.datasetPid == app.module[app.active_module].root[0].attributes.datasetPid){
									app.module[app.active_module].node = node;
									return false;
								}
							}
						}
					}
					return true;
				});
				//
				callevents(ebody, actualevent);
			}
		}
	},function(jqxhr, textStatus){
		//
	});
	// 
	$('#cc').layout('expand','west');
};

// ### data-grid - laden (vom server)
app.module[app.active_module].loadgrid = app.module[app.active_module].loadgrid || function(_this, _what, _who, _alias, _name){
	// console.log('loadgrid(inner):', _what, _who, _alias, _name);
	var params = app.module[app.active_module].getparams('dataverse', 'json', 'datagrid', _who)
	params.func = 'getValues';
	params.alias = _alias;
	params.name = _name;
	params.grid = '#dg_'+params.proj+'_'+params.what+'_'+params.who
	// 
	app.module[app.active_module].emptygrid(this, params.grid, params.what, false); // grid leeren
	// 
	// console.log("loadgrid(setTitle):", params.what, params.who, params.name)
	app.waittitle('Please wait..', '..load for "'+_who+'"');
	window.setTimeout(function(){
		$.postJSON('', params, function(_data){
			// console.log("loadgrid(data):", _data)
			// console.log('loadgrid(', dg,')',params.what, 'received:', _data);
			app.message(_data.msg);
			if (_data.success == true){ 
				app.waittitle('Please wait..', '..create view for "'+_who+'"');
				window.setTimeout(function(){
					//if (params.who == 'dataset'){
						app.waitclose();
					//}
				}, 1000);
				var dg = $(params.grid);
				if (dg.length > 0){
					var pn = $('#'+app.module[app.active_module].region+'_'+params.who)
					if (_data.total > 0){
						var opt = app.module[app.active_module].emptygrid(this, params.grid, params.what, true); 
						opt.columns = _data.cols;
						_data.opt = opt;
						dg.datagrid(_data.opt);
						dg.datagrid('loadData', _data.rows);// grid füllen
						// console.log("loadgrid(setTitle):", params.what, params.who, params.name, pn)
						pn.panel('setTitle', params.name)
						}else{
						pn.panel('setTitle', '- i found nothing similar here -')
					}
					dg.datagrid('unselectAll')
				}
				// 
				window.setTimeout(function () {
					$('#AC_menu_refresh').linkbutton('enable');
					if (params.who == app.module[app.active_module].selected.type){
						switch(params.who){
							case 'dataverse':
							app.module[app.active_module].selectgridrow(_this, params.grid, app.module[app.active_module].selected.id)
							break;
							case 'dataset':{
								app.module[app.active_module].selectgridrow(_this, params.grid, app.module[app.active_module].selected.id)
								break;
							}
						}
					}
				}, 10);
			}
		},function(jqxhr, textStatus){
			//
		});
	}, 100);
};

// ### property-grid - laden (vom server)
app.module[app.active_module].loadpropgrid = app.module[app.active_module].loadpropgrid || function(_this, _node, _what, _who){
	var lt = $('#'+app.module[app.active_module].layout); 
	if (lt.length == 1){ 
		var pg_verse = lt.layout('panel','east'); 
		//
		var params = app.module[app.active_module].getparams('dataverse', 'json', 'propgrid', _who)
		params.func = 'getValues';
		params.alias = (_node)?_node.attributes.datasetPid:'';
		params.name = app.module[app.active_module].titlepan;
		params.grid = '#pg_'+params.proj+'_'+params.what+'_'+params.who
		params.tabs = '#tabs_'+params.proj+'_'+params.what
		// 
		// console.log('loadpropgrid:', params)
		//
		app.module[app.active_module].emptygrid(this, params.grid, params.what, false); // grid leeren
		//
		$(params.tabs).tabs('select', 0);
		var tab = $(params.tabs).tabs('getTab', 0);
		$(params.tabs).tabs('update', {tab: tab, options:{title: '<span style="font-weight:normal;">Dataset:</span>&nbsp;'+app.module[app.active_module].titletab}})
		// 
		if (_node.attributes.type == 'dataset'){
			$.postJSON('', params, function(_data){
				// console.log('loadpropgrid():', params.what, 'received:', _data);
				app.message(_data.msg);
				if (_data.success == true){ 
					if (_data.total > 0){
						var pg = $(params.grid);
						// console.log('loadgrid(', pg,')',params.what, 'received:', _data);
						if (pg.length > 0){
							app.module[app.active_module].settoolbar('east', false);
							var opt = app.module[app.active_module].emptygrid(this, params.grid, params.what, true); 
							opt.columns = _data.cols;
							_data.opt = opt;
							pg.propertygrid(_data.opt);
							pg.propertygrid('loadData', _data.rows);// grid füllen
							if (lt){
								//								window.setTimeout(function(){
								// if (type == 'dataset'){
								if (pg_verse){
									if (pg_verse.panel('options').collapsed == true){
										lt.layout('expand', 'east');
									}
								}
								//								}, 10);
							}
						}
					}
				}	
			},function(jqxhr, textStatus){
				//
			});
			}else{
			window.setTimeout(function(){
				lt.layout('collapse', 'east');
			}, 10);
		}
		if (pg_verse){
			pg_verse.panel('setTitle', app.module[app.active_module].titlepan);
		}
		}else{
		app.message({type:'alert', title:'Error', msg: 'Fatal error: <br> . layout not found: "'+app.module[app.active_module].layout+'"'});
	}
}
// json handling -	ende
// ### ######################################################################

// ### ######################################################################
// ### button handling -	start
// ###
// ### buttons - enable/disable
app.module[app.active_module].enable = app.module[app.active_module].enable || function(_enable, _prefix, _suff){
	var elem = $('#'+_prefix+_suff);
	window.setTimeout(function(){
		$(elem).linkbutton(_enable?'enable':'disable');
	}, 50);
}

// ### buttons - hide/show (toggle)
app.module[app.active_module].hide = app.module[app.active_module].hide || function(_hidefirst, _prefix, _suff1, _suff2, _class){
	var b1 = $('#'+_prefix+_suff1);
	var b2 = $('#'+_prefix+_suff2);
	window.setTimeout(function(){
		if (_hidefirst){
			$(b1).addClass(_class);
			$(b2).removeClass(_class);
			}else{
			$(b1).removeClass(_class);
			$(b2).addClass(_class);
		}
	}, 50);
}
// ### button handling -	ende
// ### ######################################################################

// ### ######################################################################
// ### property-grid - expand/collapse (alle)
app.module[app.active_module].expandgroups = app.module[app.active_module].expandgroups || function(_this, _expand){
	var pg = $(_this).closest('div.datagrid').find('table.easyui-propertygrid');
	// console.log('expandgroups:', pg);
	if (pg.length == 1){
		var dg = $(pg);
		var b1 = $(_this).attr('id');
		var b2 = '';
		var gr = dg.datagrid('groups');
		var ac = b1.split("_").pop()+'Group';
		if (ac == 'expandGroup'){
			b2 = b1.replace('expand', 'collapse');
			}else{
			b2 = b1.replace('collapse', 'expand')
		}
		$('#'+b1).addClass('mod-tb-btn-hide');
		$('#'+b2).removeClass('mod-tb-btn-hide');
		for(var i=0; i<gr.length; i++){
			dg.datagrid(ac, i);
		}	
		console.log('expandgroups:', gr.length, gr); 
	}
}

// ### ######################################################################
// ### grid handling -	start
// ###
// ### data-grid leeren
app.module[app.active_module].emptygrid = app.module[app.active_module].emptygrid || function(_this, _gridid, _what, _delete){
	var opt = {};
	opt.collapsible = false;
	// opt.view = bufferview; // nachladen der daten bei bedarf (schneller)
	opt.pageSize = 150;
	opt.fitColumns = true;
	opt.remoteSort = false;
	opt.multiSort = true;
	opt.striped = true;
	
	opt.ctrlSelect = true;
	// 
	var dg = $(_gridid);
	if (dg.length > 0){
		data = {}
		data.rows = [];
		if (_delete == true) { // alles löschen, wenn komplett neues grid vorhanden..
			opt.columns = [];
			}else{ 
			// ..sonst nur leeren
			opt.fitColumns = false;
			opt.columns = dg.datagrid('options').columns;
		}
		data.opt = opt;
		if (_what == 'datagrid'){
			opt.singleSelect = true;
			dg.datagrid(data.opt);
			dg.datagrid('loadData', data.rows); // grid leeren
			} else{
			if (_what == 'propgrid'){
				dg.propertygrid(data.opt);
				dg.propertygrid('loadData', data.rows); // grid leeren
			}
		}
	}
	return opt;
};

// ### ######################################################################
// ### data-grid zeile nach id selektieren
app.module[app.active_module].selectgridrow = app.module[app.active_module].selectgridrow || function(_this, _gridid, _id){
	var dg = $(_gridid);
	if (dg.length > 0){
		dg.datagrid('unselectAll');
		var idfield = dg.attr('idfield')
		var rows = dg.datagrid('getRows');
		for(var i=0,len=rows.length; i<len; i++){
			if (rows[i][idfield] == _id){
				dg.datagrid("selectRecord", rows[i][idfield]);
			}
		}
	}
}

// ### ######################################################################
// ### property-grid - check/uncheck (einzelnen)
app.module[app.active_module].checkgroup = app.module[app.active_module].checkgroup || function(_this, _value, _event){
	var dv = $(_this).closest('div.datagrid');
	if (dv.length == 1){
		// ### ##################################################################
		// ### achtung! 
		// ### das normale ermitteln der "checkboxen" funktioniert nicht, da das "grid-view" 2-mal existiert.
		// ### > die anzahl der "checkboxen" würde sich verdoppeln.
		// ### var ck = $(dv).find('input.checkbox.dataset');
		// ### ##################################################################
		var ck = dv.find('.easyui-propertygrid').prev('div').find('input.checkbox.dataset');
		// console.log('checkgroup(one 1):', ck.length, ck);
		var pg = $(dv).find('table.easyui-propertygrid');
		if (pg.length == 1){
			var dg = $(pg);
			var groups = dg.datagrid('groups');
			var group = null;
			var ck = $(_event.target);
			for(var i=0; i<groups.length; i++){
				if (groups[i].value == _value){
					var checked = ck.is(':checked');
					group = groups[i];
					break;
				}
			}
			if (group != null){
				var ac = checked?'checkRow':'uncheckRow';
				for(var i=group.startIndex; i<group.startIndex+group.rows.length; i++){
					dg.datagrid(ac, i);
				}
				
				var doi = $(ck).attr('doi');
				var lbl = $(ck).attr('name');
				for(var r=0; r<groups.length; r++){				
					if (groups[r].value.indexOf('&file;') > 0){
						if (groups[r].value.indexOf('&'+ doi) > 0){
							for(var i=groups[r].startIndex; i<groups[r].startIndex+groups[r].rows.length; i++){
								dg.datagrid(ac, i);
							}
						}
					}
				}
			}
			var sels = dg.datagrid('getChecked');
			doit = (sels.length != 0)?true:false;
			// console.log('checkgroup(one):', doit);
			app.module[app.active_module].settoolbar('east', doit);
			//
			// ck = dv.find('input.checkbox.dataset:checked');
		}
	}
}

// ### ######################################################################
// ### property-grid - check/uncheck (alle)
app.module[app.active_module].checkgroups = app.module[app.active_module].checkgroups || function(_this, _check){
	var dv = $(_this).closest('div.datagrid');
	if (dv.length == 1){		
		// ### ##################################################################
		// ### achtung! 
		// ### das normale ermitteln der "checkboxen" funktioniert nicht, da das "grid-view" 2-mal existiert.
		// ### > die anzahl der "checkboxen" würde sich verdoppeln.
		// ### var ck = $(dv).find('input.checkbox.dataset');
		// ### ##################################################################
		var ck = dv.find('.easyui-propertygrid').prev('div').find('input.checkbox.dataset');
		// console.log('checkgroup(all 1):', ck.length, ck);
		var pg = $(dv).find('table.easyui-propertygrid');
		if (pg.length == 1){
			const start = Date.now();
			var ac = $(_this).attr('id').split("_").pop()+'Row';
			var checked = true
			if (ac != 'checkRow'){
				checked = false;
			}
			var dg = $(pg);
			var rows = dg.datagrid('getRows');
			for(var i=0; i<rows.length; i++){
				dg.datagrid(ac, i);
			}
			var sels = dg.datagrid('getChecked');
			doit = (sels.length != 0)?true:false;
			for(var i=0; i<ck.length; i++){
				$(ck[i]).prop('checked', checked);
			}
			app.module[app.active_module].settoolbar('east', doit);
			// 
			// ck = dv.find('input.checkbox.dataset:checked')
			// console.log('checkgroup(all 2):', ck.length, ck);
		}
	}
}

// ### ######################################################################
// ### onexpand - (layout)
app.module[app.active_module].expandregion = app.module[app.active_module].expandregion || function(_this, _region){
	switch (_region){
		case 'east':
		var rg = $(_this).layout('panel', _region);
		var pg = $(rg).find('div.datagrid');
		if (pg.length > 0){
			var dg = $(pg).find('table.easyui-propertygrid');
			if (dg.length == 1){
				var sels = dg.datagrid('getChecked');
				// console.log('expandnode region:', $(_this), dg, pg, sels);
				app.module[app.active_module].settoolbar(_region, (sels.length != 0)?true:false);
			}
		}
	}
}

// ### ######################################################################
// ### oncollapse - (layout)
app.module[app.active_module].collapseregion = app.module[app.active_module].collapseregion || function(_this, _region){
	switch (_region){
		case 'east':
		var rg = $(_this).layout('panel', _region);
		var pg = $(rg).find('div.datagrid');
		if (pg.length > 0){
			var dg = $(pg).find('table.easyui-propertygrid');
			if (dg.length == 1){
				dg.datagrid('clearChecked');
				dg.datagrid('clearSelections');
				var sels = dg.datagrid('getChecked');
				// console.log('expandnode region:', $(_this), dg, pg, sels);
				app.module[app.active_module].settoolbar(_region, (sels.length != 0)?true:false);
			}
		}
	}
}

// ### ######################################################################
// ### toobar anpassen - (layout-region)
app.module[app.active_module].settoolbar = app.module[app.active_module].settoolbar || function(_region, _doit){
	switch (_region){
		case 'east':
		var btn = 'AC_search_';
		app.module[app.active_module].hide(_doit, btn, 'check', 'uncheck', 'mod-tb-btn-hide')
		app.module[app.active_module].enable(true, btn, 'search');
		app.module[app.active_module].enable(_doit, btn, 'save');
		//app.module[app.active_module].enable(_doit, btn, 'excel');
	}
}

// ### ######################################################################
// ### menü-knoten expandieren - (knoten finden, daten (grids) laden, basis selektieren)
app.module[app.active_module].expandnodetree = app.module[app.active_module].expandnodetree || function(_tree, _node){
	// console.log('expandnodetree:', _node);
	type = (_node.attributes.type)?_node.attributes.type:"unknown"
	if (type == 'file'){
		return;
	}
	var lt = $('#'+app.module[app.active_module].layout); 
	if (lt.length == 1){ 
		app.module[app.active_module].selected = new app.module[app.active_module].selitem(_node.id, _node.attributes.type, _node.attributes.alias)
		// 
		var title = (_node.attributes.type == 'dataset')?_node.attributes.title:'- i found nothing similar here -'
		var node = $(_tree).tree('getParent', _node.target)
		node = (node)?node:_node
		alias = (node.attributes.alias)?node.attributes.alias:"root"
		name = (node.attributes.name)?node.attributes.name:"root"
		// 
		if (typeof _node.children == 'object'){
 			$(_tree).tree('collapseAll');
 	 	 	// console.log('expandnodetree(1):', _node.target.id);
 	 	 	$(_tree).tree('expandTo', _node.target);
 	 	 	$(_tree).tree({
 	 	 	 	onExpand: function(_node, _tree){
					app.timestart = Date.now()
 	 	 	 	 	// var tt = $(_node.target).closest('.easyui-tree');
 	 	 	 	 	$(_tree).tree('select', _node.target); 
 	 	 	 	 	// console.log('onExpand(on):', _node.target, _tree);
 	 	 	 	 	var dgt_verse = '';
 	 	 	 	 	app.module[app.active_module].titlepan = '';
 	 	 	 	 	app.module[app.active_module].titletab = title;
 	 	 	 	 	var dgt_delim = '&nbsp;&raquo;&nbsp;';
 	 	 	 	 	var dg_verse = lt.layout('panel','center');
 	 	 	 	 	if (dg_verse){
 	 	 	 	 	 	// var node = $(_tree).tree('getSelected');
 	 	 	 	 	 	while(node){
 	 	 	 	 	 	 	if (node.attributes){
 	 	 	 	 	 	 	 	if (node.attributes.type){
 	 	 	 	 	 	 	 	 	switch(node.attributes.type){
 	 	 	 	 	 	 	 	 	 	case "dataverse":
 	 	 	 	 	 	 	 	 	 	dgt_verse = dgt_delim + node.text + dgt_verse;
 	 	 	 	 	 	 	 	 	 	break;
									}
									}else{
 	 	 	 	 	 	 	 	 	dgt_verse = node.text + dgt_verse;
 	 	 	 	 	 	 	 	 	app.module[app.active_module].titlepan = dgt_verse;
								}
							}
 	 	 	 	 	 	 	node = $(_tree).tree('getParent', node.target);
						}
 	 	 	 	 	 	dg_verse.panel('setTitle', dgt_verse);
					}
 	 	 	 	 	app.module[app.active_module].loadgrid(_tree, 'datagrid', 'dataverse', alias, dgt_verse);
 	 	 	 	 	// app.module[app.active_module].loadgrid(_tree, 'datagrid', 'dataset', alias, dgt_verse);
 	 	 	 	 	app.module[app.active_module].loadpropgrid(_tree, _node, 'propgrid', 'file');
 	 	 	 	 	// 
 	 	 	 	 	$('li').removeClass('parent-menu');
 	 	 	 	 	elem = $(_tree).tree('getParent', _node.target);
 	 	 	 	 	if ($(elem).length > 0){
 	 	 	 	 	 	$(elem.target).closest('li').addClass('parent-menu');
 	 	 	 	 	 	var parent = $(elem)[0]
 	 	 	 	 	 	app.module[app.active_module].selparent = new app.module[app.active_module].selitem(parent.id, parent.attributes.type, parent.attributes.alias)
						}else{
 	 	 	 	 	 	app.module[app.active_module].selparent = new app.module[app.active_module].selitem(1, "dataverse", "root")
					}
				}(_node, _tree)
			})
 	 	 	$(_tree).tree('expand', _node.target);
		}
		}else{
		app.message({type:'alert', title:'Error', msg: 'Fatal error: <br> . layout not found: "'+app.module[app.active_module].layout+'"'});
	}
}

// ### grid handling -	ende
// ### ######################################################################
function syntaxHighlight(json) {
	json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
	return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
		var cls = 'number';
		if (/^"/.test(match)) {
			if (/:$/.test(match)) {
				cls = 'key';
				} else {	
				cls = 'string';
			}
			} else if (/true|false/.test(match)) {
			cls = 'boolean';
			} else if (/null/.test(match)) {
			cls = 'null';
		}
		return '<span class="' + cls + '">' + match + '</span>';
	});
}

// ### suche - in property-grid anstoßen
app.module[app.active_module].gosearch = app.module[app.active_module].gosearch	|| function(_this, _dialog){
	// console.log('gosearch(): ', app.sid, _this.focus(), _dialog)	
	timestart = Date.now();
	$(_this).first().focus();
	app.module[app.active_module].execute(_dialog, 'search', 'dataverse');
}

// ### suche - in property-grid laden (vom server)
app.module[app.active_module].searchvalues = app.module[app.active_module].searchvalues || function(_this, _what, _who, _param){
	// console.log('searchvalues:', app.active_module, _what, _who, _param, _this);
	var lt = $('#'+app.module[app.active_module].layout); 
	if (lt.length == 1){ 
		var pg_verse = lt.layout('panel','east'); 
		var params = app.module[app.active_module].getparams('search', 'json', _what, _who)
		params.func = 'getValues';
		params.alias = '';
		params.name = app.module[app.active_module].titlepan;
		params.grid = '#pg_'+params.proj+'_'+params.what+'_'+params.who
		params.tabs = '#tabs_'+params.proj+'_'+params.what
		params.parm = _param;
		// 
		app.module[app.active_module].emptygrid(this, params.grid, params.what, false); // grid leeren
		//
		$(params.tabs).tabs('select', 0);
		var tab = $(params.tabs).tabs('getTab', 1);
		tab.panel('options').tab.hide();
		$(params.tabs).tabs('update', {tab: tab, options:{title: '- i found nothing similar here -'}})
		// 
		// console.log('searchvalues(before)',params);
		//
		app.waitmax = 100;
		app.wait('Search', 'Read data from "Dataverse" - waiting...', true);
		//
		var startDate = new Date();
		$.postJSON('', params, function(_data){
			// console.log('searchvalues(data):', params.what, 'received:', _data);
			app.message(_data.msg);
			if (_data.success == true){ 
				var data = _data.search;
				if (data){
					if (_data.success == true){ 
						timeend = Date.now();
						// console.log('searchvalues(dvs-complete):', ' dauer(ms):', timeend-timestart);
						timestart = Date.now();
						var pg = $(params.grid);
						// console.log('searchvalues(', params.grid,')',params.what, 'received 1:', data);
						if (pg.length > 0){
							app.module[app.active_module].settoolbar('east', false);
							var opt = app.module[app.active_module].emptygrid(this, params.grid, params.what, true); 
							opt.columns = data.cols;
							data.opt = opt;
							pg.propertygrid(data.opt);
							if (data.total > 0){
								app.module[app.active_module].searchcolumns = data.columns;
								app.module[app.active_module].searchentries = data.entries;
								app.module[app.active_module].searchtime = new Date();
								pg.propertygrid('loadData', data.rows);// grid füllen
								window.setTimeout(function(){
									if (pg_verse){
										if (pg_verse.panel('options').collapsed == true){
											lt.layout('expand', 'east');
										}
										pg_verse.panel('setTitle', params.name);
									}
									groups = pg.datagrid('groups');
									// console.log('searchvalues 1:', pg_verse.find('div.datagrid-group span input'));
									var tab = $(params.tabs).tabs('getTab', 1);
									tab.panel('options').tab.show();
									$(params.tabs).tabs('update', {tab: tab, options:{title: '<span style="font-weight:normal;">Found:</span>&nbsp;'+data.datasets+'&nbsp;datasets&nbsp;&&nbsp;'+data.files+'&nbsp;files'}})
									$(params.tabs).tabs('select', 1);
									//
									var seconds = (app.module[app.active_module].searchtime.getTime() - startDate.getTime()) ;
									timeend = Date.now();
									// console.log('searchvalues(gui-complete):', ' dauer(ms):', timeend-timestart);
									timestart = Date.now();
									// console.log('searchvalues( data ):', seconds, data);
									// app.waitclose();
									$('#dialog_search').dialog('close');
								}, 10);
								}else{
								app.message({type:'alert', title:'Information', msg: 'No result found for this query: <br><br> . '+_data.query+'<br><br>Please, enter a different term and search again.'});
							}
							// app.waitclose();
						}
					}
				}
			}
		},function(jqxhr, textStatus){
			app.waitclose();
		});
		}else{
		app.waitclose();
		app.message({type:'alert', title:'Error', msg: 'Fatal error: <br> . layout not found: "'+app.module[app.active_module].layout+'"'});
	}
}

// schreib-krücke für javascript (getestet bis ca. 3000 zeilen)
app.module[app.active_module].writecsv = app.module[app.active_module].writecsv || function(_filename, _value){ 	 	
 	var fileName = _filename;
 	var fileContent = _value;
 	var refFile = new Blob([fileContent], {type: 'text/plain'});
 	window.URL = window.URL || window.webkitURL;
 	var dlbtn = document.getElementById("download");
 	dlbtn.setAttribute("href", window.URL.createObjectURL(refFile));
 	dlbtn.setAttribute("download", fileName);
 	dlbtn.click();
}

function _getValuefromEntry(_key, _entry){
 	var keyarr = _key.split('.');
 	var value = _entry
 	for (var i=0; i<keyarr.length; i++){
 	 	value = value[keyarr[i]];
	}
 	// console.log('getValuefromEntry(', typeof value,':'+_key+'):', value);
 	return (((value)?value:'---')+'').replace("\t", " ");
};

// ### speichern - csv vorbereiten
app.module[app.active_module].fillcsv = app.module[app.active_module].fillcsv || function(_this, _result){
 	files = [];
 	for (var e = 0; e < _result.save.length; e++){
 	 	// console.log('entry(',e,'):');
 	 	var entry = _result.save[e];
 	 	header = {}
 	 	switch (entry.type){
 	 	 	case 'dataset':{
 	 	 	 	header = app.module[app.active_module].searchheader.dataset;
 	 	 	 	break;
			}
						 
						 
 	 	 	case 'file':{
 	 	 	 	header = app.module[app.active_module].searchheader.file;
 	 	 	 	break;
			}
		}
 	 	if (files[entry._csvfile] == undefined){ // wenn noch nicht vorhanden, ..
 	 	 	// .. dann header und file erstellen
 	 	 	files[entry._csvfile] = []
 	 	 	var shead = '';
 	 	 	var ihead = 0;
 	 	 	for (const [key, value] of Object.entries(header)){
 	 	 	 	if (ihead > 0){
 	 	 	 	 	shead+='\t';
				}
 	 	 	 	shead+=key; // TODO: evtl die übersetzung und reihenfolge verwenden
 	 	 	 	ihead+=1;
			}
 	 	 	files[entry._csvfile] = shead;
 	 	 	// console.log('header(',entry._csvfile,'):', shead);
		} 	 	
 	 	var writestr = files[entry._csvfile];
 	 	var sentry = '';
 	 	var ientry = 0;
 	 	for (const [key, value] of Object.entries(header)){
 	 	 	if (ientry > 0){
 	 	 	 	sentry+='\t';
			}
 	 	 	sentry+=_getValuefromEntry(key, entry);
 	 	 	ientry+=1;
		}
 	 	if (sentry.length > 2){
 	 	 	// console.log('entry(',e,'):', sentry);
 	 	 	files[entry._csvfile] = writestr + '\n' + sentry;
		} 	 	
	}
 	for (const [key, value] of Object.entries(files)){
 	 	app.module[app.active_module].writecsv(key, value); 	
 	 	// console.log('entries(', key,' ):', value);
	}
}

// ### speichern - csv vorbereiten
app.module[app.active_module].createcsv = app.module[app.active_module].createcsv || function(_this, _filename){
	var dv = $(_this).closest('div.datagrid');
	if (dv.length == 1){		
		// ### ##################################################################
		// ### achtung! 
		// ### das normale ermitteln der "checkboxen" funktioniert nicht, da das "grid-view" 2-mal existiert.
		// ### > die anzahl der "checkboxen" würde sich verdoppeln.
		// ### var ck = $(dv).find('input.checkbox.dataset');
		// ### ##################################################################
		var ck = dv.find('.easyui-propertygrid').prev('div').find('input.checkbox.dataset:checked');
		if (ck.length > 0){		
 	 	 	// ermitteln aller angewählten Einträge
 	 	 	var result = [];
 	 	 	result.file = _filename;
 	 	 	try{
 	 	 	 	result.dois = [];
 	 	 	 	result.save = [];
 	 	 	 	result.time = app.module[app.active_module].searchtime;
 	 	 	 	var entries = app.module[app.active_module].searchentries;
 	 	 	 	for (var k = 0; k < ck.length; k++){
 	 	 	 	 	result.dois.push($(ck[k]).attr('doi'));
				}
 	 	 	 	// search - auswertung:
 	 	 	 	for (var d = 0; d < result.dois.length; d++){
 	 	 	 	 	var doi = result.dois[d].replace(';', '');
 	 	 	 	 	for (var e = 0; e < entries.length; e++){
 	 	 	 	 	 	var name = '';
 	 	 	 	 	 	if (entries[e].dataset_persistent_id == doi){
 	 	 	 	 	 	 	name = result.file.replace('%placeholder%', '_file_'+entries[e].dataset_name);
							}else{ 
 	 	 	 	 	 	 	if (entries[e].global_id == doi){
 	 	 	 	 	 	 	 	name = result.file.replace('%placeholder%', '_dataset_'+entries[e].name);
							}else{ continue; }
						}
 	 	 	 	 	 	if (name.length > 0){
 	 	 	 	 	 	 	// console.log('createcsv(', e, '):', name)
 	 	 	 	 	 	 	entries[e]._csvfile = name;
 	 	 	 	 	 	 	result.save.push(entries[e]); 
						}
					}
				}
 	 	 	 	// result.save.enries = entries;
				}finally{
 	 	 	 	// console.log('savecsv(before)', _filename, result, files);
 	 	 	 	// einträge bearbeiten und zum speichern merken
 	 	 	 	app.module[app.active_module].searchresult = result;
 	 	 	 	app.module[app.active_module].fillcsv(_this, result);
 	 	 	 	for (var file in files) {
 	 	 	 	 	var writestr = '';
 	 	 	 	 	// console.log('<< new file:', file);
 	 	 	 	 	for (const [ikey, value] of Object.entries(files[file])) {
 	 	 	 	 	 	if (ikey > 0){
 	 	 	 	 	 	 	writestr+='\n';
						}
 	 	 	 	 	 	writestr+=value;
					}
				} 	 	 	 	
			}
			}else{
			app.message({type:'alert', title:'Information', msg: 'Data selection: <br> . no values checked.'});
		}
		}else{
		app.message({type:'alert', title:'Error', msg: 'Fatal error: <br> . datagrid not found: "'+app.module[app.active_module].layout+'"'});
	}
}

// ### speichern - csv vorbereiten
app.module[app.active_module].savecsv = app.module[app.active_module].savecsv || function(_this, _what, _who, _param){
 	var params = app.module[app.active_module].getparams('db', 'json', 'params', 'search.header')
 	params.func = 'getParams';
 	params.time = app.getTimecompact(app.module[app.active_module].searchtime);
	
 	app.module[app.active_module].searchheader = {}
 	$.postJSON('', params, function(_data){
 	 	app.message(_data.msg);
 	 	if (_data.success == true){ 
 	 	 	// console.log('savecsv(data):', params.what, 'received :', _data);
 	 	 	app.module[app.active_module].searchheader = _data.columns;
 	 	 	app.module[app.active_module].createcsv(_this, params.time+'_%placeholder%.csv');
			}else{
 	 	 	app.confirm(
 	 	 	 	{type:'alert', title:'Information', msg: 'No search "header" found: <br><br> . i will use a standard "header" names.', callback: function(r){
					if (r){
						app.module[app.active_module].createcsv(_this, params.time+'_%placeholder%.csv');
					}}
				});
		}
	},function(jqxhr, textStatus){
		//
	});
}

// ### speichern - excel
app.module[app.active_module].saveexcel = app.module[app.active_module].saveexcel || function(_this, _what, _who, _param){
	// console.log('saveexcel:', app.active_module, _what, _who, _param, _this);
	var dv = $(_this).closest('div.datagrid');
	if (dv.length == 1){		
		// ### ##################################################################
		// ### achtung! 
		// ### das normale ermitteln der "checkboxen" funktioniert nicht, da das "grid-view" 2-mal existiert.
		// ### > die anzahl der "checkboxen" würde sich verdoppeln.
		// ### var ck = $(dv).find('input.checkbox.dataset');
		// ### ##################################################################
		var ck = dv.find('.easyui-propertygrid').prev('div').find('input.checkbox.dataset:checked');
		if (ck.length > 0){		
			var params = app.module[app.active_module].getparams('excel', 'json', _what, _who)
			params.func = 'getValues';
			params.alias = '';
			params.name = app.module[app.active_module].titlepan;
			params.grid = '#pg_'+params.proj+'_'+params.what+'_'+params.who
			params.tabs = '#tabs_'+params.proj+'_'+params.what
			for (var i = 0; i < ck.length; i++){
				_param.push({dois: $(ck[i]).attr('doi')});
			}
			params.parm = _param;
			//
			// ### ##################################################################
			// ### achtung! 
			// ### das normale ermitteln der "checkboxen" funktioniert nicht, da das "grid-view" 2-mal existiert.
			// ### > die anzahl der "checkboxen" würde sich verdoppeln.
			// ### var ck = $(dv).find('input.checkbox.dataset');
			// ### ##################################################################
			// console.log('saveexcel(before)',params, ck);
			$.postJSON('', params, function(_data){
				// console.log('saveexcel(data):', params.what, 'received:', _data);
				app.message(_data.msg);
				if (_data.success == true){ 
					// nicht implementiert
				}
			},function(jqxhr, textStatus){
				//
			});
			}else{
			app.message({type:'alert', title:'Information', msg: 'Data selection: <br> . no values checked.'});
		}
		}else{
		app.message({type:'alert', title:'Error', msg: 'Fatal error: <br> . datagrid not found: "'+app.module[app.active_module].layout+'"'});
	}
}

app.module[app.active_module].func = app.module[app.active_module].func ||	function(_this, _func, _who, _params){
	// console.log("func:", _func, _who, _params, ' > element:', _this)
	switch (_func){
		case 'check':
		app.module[app.active_module].checkgroups(_this, _who);
		break;
		case 'expand':
		app.module[app.active_module].expandgroups(_this, _who);
		break;
		case 'search':{
			params = _params
			if (app.module[app.active_module].selected){
				if (app.module[app.active_module].selected.alias){
					params.push({subtree: app.module[app.active_module].selected.alias});
					}else{
					if (app.module[app.active_module].selparent){
						if (app.module[app.active_module].selparent.alias){
							params.push({subtree: app.module[app.active_module].selparent.alias});
							}else{
							params.push({subtree: ":root"});
						}
						}else{
						params.push({subtree: ":root"});
					}
				}
			}
			app.module[app.active_module].searchvalues(_this, 'propgrid', 'search', params);
			break;
		}
		case 'save':{
			params = []
			switch (_who){
				case "excel": // sichern als XLS
				app.module[app.active_module].saveexcel(_this, _func, _who, params);
				break;
				case "csv": // sichern als CSV
				app.module[app.active_module].savecsv(_this, _func, _who, params);
				break;
				case "params": // sichern der suchparameter
				app.module[app.active_module].saveparams(_this, _func, _who, params);
				break;
				default:
				app.message({type:'alert', title:'Error', msg: 'Fatal error: <br> . unknown type (who): "'+_who+'"'});
			}		
			break;
		}
		case 'load':{
			params = []
			switch (_who){
				case "params": // lesen der suchparameter
				app.module[app.active_module].loadparams(_this, _func, _who, params);
				break;
				default:
				app.message({type:'alert', title:'Error', msg: 'Fatal error: <br> . unknown type (who): "'+_who+'"'});
			}
 	 	 	break;
		}
 	 	default:
		app.message({type:'alert', title:'Error', msg: 'Fatal error: <br> . unknown type (func): "'+_func+'"'});
	}
}

app.module[app.active_module].opendialog = app.module[app.active_module].opendialog || function( _data, _layout, _dialog, _title){	
	app.message(_data.msg);
	if (_data.success == true){ 
		var shtml = unescape(_data.html);
		window.setTimeout(function (_html) {
			// niemals 2-mal einfügen, deshalb evtl. vorher löschen..
			$(_dialog).remove();
			$(_layout).append(shtml);// menü, grid ... usw. füllen
			app.easyui(_layout);
			var dialog = $(_dialog);
			$(dialog).dialog({
				title: _title,
				modal: true
			}).dialog('center').dialog('open').find("input.validatebox-text" ).first().focus();
			window.setTimeout(function () {
				app.bindKeyaction(_dialog);
				disableAnchor();
			}, 200);
		}(shtml), 50);
	}
}

app.module[app.active_module].login = app.module[app.active_module].login || function(_this){
	if (document.getElementById(app.module[app.active_module].layout) !== null){
		app.module[app.active_module].record = null;
		// 
		var params = app.module[app.active_module].getparams('db', 'json', 'login', '')
		params.func = 'getHtml';
		params.pref = 'archium';
		params.midl = '_';
		// 
		var laynam = '#layout_'+params.what;
		var dlgnam = '#dialog_'+params.what;
		// console.log(params.what, 'request:', dlgnam, params);
		var layout = $(laynam);
		if (layout.length > 0){
			var encrypted = CryptoJS.AES.encrypt('12345678', 'Klaus Wendel'); 
			var decrypted = CryptoJS.AES.decrypt(encrypted, 'Klaus Wendel'); 
			params.decrypted = decrypted.toString(CryptoJS.enc.Utf8);
			params.encrypted = encrypted.toString(CryptoJS.enc.Utf8);
			$.postJSON('', params, function(data){
				// console.log(params.what, 'received:', data);
				app.message(data.msg);
				if (data.success == true){ 
					app.module[app.active_module].opendialog(data, laynam, dlgnam, 'Login');
				}
			},function(jqxhr, textStatus){
				//
			});
		}
	}
};


app.module[app.active_module].logout = app.module[app.active_module].logout || function(_this){
	app.module[app.active_module].record = null;
	// 
 	var params = app.module[app.active_module].getparams('db', 'json', 'logout', '')
	params.func = 'routeToURL';
	params.refr = false;
	// 
	$.postJSON('', params, function(data){
		// console.log('data:', data);
		app.message(data.msg);
		if (data.success == true){
			app.sid = '';
			var route = data.route.trim();
			if (route.length > 0){
				window.open(route,"_self");
			}
		}
	},function(jqxhr, textStatus){
		// console.log('complete:', jqxhr, textStatus);
		//
	});
}

app.module[app.active_module].search = app.module[app.active_module].search || function(_this){
	if (document.getElementById(app.module[app.active_module].layout) !== null){
		app.module[app.active_module].record = null;
		// 
		var params = app.module[app.active_module].getparams('db', 'json', 'search', '')
		params.func = 'getHtml';
		params.pref = 'archium';
		params.midl = '_';
		params.parm = [];
		params.parm.push({meta: "subject"});
		// 
		var laynam = '#layout_'+params.what;
		var dlgnam = '#dialog_'+params.what;
		// console.log(params.what, 'request:', dlgnam, params);
		var layout = $(laynam);
		if (layout.length > 0){
			timestart = Date.now();
			$.postJSON('', params, function(data){
				// console.log(params.what, 'received:', data);
				app.message(data.msg);
				if (data.success == true){ 
					app.module[app.active_module].opendialog(data, laynam, dlgnam, 'Search');
				}
			},function(jqxhr, textStatus){
				//
			});
		}
	}
};

// behandlung vor der ausführung der funktion
app.module[app.active_module].execute = app.module[app.active_module].execute || function(_this, _func, _who){
	// console.log('execute:', _func, _who, _this);
	switch (_func){
		case 'search':{
			if ($(_this).length > 0){
				//aufbereiten der Formulardaten
				var params = []
				params.push({per_page: 1000});
				switch (_who){
					case 'dataverse':{
						params.push({type: "dataverse"});
						params.push({type: "dataset"});
						break;
					}
					case 'dataset':
					case 'file':{
						params.push({type: "dataset"});
						params.push({type: "file"});
						break;
					}
				}
				// echte eingabefelder im formular laden
				var inputs = $('#dialog_'+_func).find('input.textbox-f');
				for(var i=0; i<inputs.length; i++){				
					var value = $(inputs[i]).prop('value');
					if (value.length > 0){
						var field = $(inputs[i]).attr('field');
						params.push({search: field+'=['+value+']'});
					}
				}
				//
				var icheck = 0;
				var checks = $('#dialog_'+_func).find(".easyui-datalist");
				var field = checks.attr('field')
				var value = '';
				var rows = checks.datagrid('getChecked');
				// console.log('execute check(	 ):', field, rows);
				for(var i=0; i<rows.length; i++){
					if (icheck>0){
						value+=';';
					}
					value+='"'+$(rows[i]).prop('value')+'"';
					icheck+=1;
				}
				if (icheck>0){
					params.push({search: field+'=[{'+value+'}]'});
				}
				//
				params.push({_q_: '*'});
				// console.log('execute 1:', _func, _who, params);
				// besser nicht sortieren, weil die reihenfolge der "datasets" und "files" sonst durcheinander kommt.
				// bei getrennter bearbeitung (erst "datasets", dann "files" zuordnen) gibt es kein problem
				params.push({sort: "date"});
				params.push({order: "desc"});
				app.module[app.active_module].func(_this, _func, _who, params);
				}else{
				app.message({type:'alert', title:'Error', msg: 'Dialog error: <br> . dialog was not found: "dialog_search"'});
			}
			break;
		}
	}
}

app.module[app.active_module].getgrouptitle = app.module[app.active_module].getgrouptitle	|| function(_value){
	var slabel = ''
	if (_value.indexOf('&dataset;') > -1){
		valarr = _value.split('&')
		// array:
		// . 0 = name
		// . 1 = type (dataset)
		// . 2 = doi
		slabel = slabel + '<table style="width:100%;height:auto;line-height:normal;border:none;">';
		slabel = slabel + '		<tbody>';
		slabel = slabel + '			<tr>';
		slabel = slabel + '				<td style="border:none;padding:3px 0px 0px 0px;width:20px;"><input type="checkbox" name="' + valarr[0] + '" doi="' + valarr[2] + '" class="checkbox dataset" onclick="app.module[app.active_module].checkgroup(this, \'' + _value + '\',event)"></td>';
		slabel = slabel + '				<td class="icon-dataset" style="border:none;padding:3px 0px 0px 0px;color:#337ab7;">&nbsp;' + valarr[0] + '</td>';
		slabel = slabel + '				<td class="doi" style="display:none;">' + valarr[2] + '</td>';
		slabel = slabel + '			</tr>';
		slabel = slabel + '		</tbody>';
		slabel = slabel + '</table>';
		// console.log('getgrouptitle(dataset):', valarr);
		}else{
		valarr = _value.split('&')
		// array:
		// . 0 = name
		// . 1 = id
		// . 2 = type (file)
		// . 3 = content type (f.e. text/plain)
		content = valarr[3].split('/')
		switch (content[0]){
			case "text": {
				sicon= "icon-file"; 
				if (content.length > 1) {
					switch (content[1]) {
					case "tab-separated-values":
						sicon = "icon-tabular"; break;
					case "css":
						sicon = "icon-code"; break;
					case "html":
						sicon = "icon-code"; break;
					case "x-go":
						sicon = "icon-code"; break;
					case "x-tex":
						sicon = "icon-code"; break;
					case "javascript":
						sicon = "icon-code"; break;
					default:
						sicon = "icon-file";
					}
				}
				break;
			}
			case "image": sicon = "icon-image"; break;
			case "audio": sicon= "icon-audio"; break;
			case "video": sicon = "icon-video";break;
			case "application": {
				sicon= "icon-package"; 
				if (content.length > 1) {
					switch (content[1]) {
					case "json":
						sicon = "icon-code";
					}
				}
				break;
			}
			default: sicon= "icon-file";
		}
		// console.log('getgrouptitle(file):', valarr, content, sicon);
		slabel = slabel + '<table style="width:100%;height:auto;line-height:normal;border:none;">';
		slabel = slabel + '		<tbody>';
		slabel = slabel + '			<tr>';
		slabel = slabel + '				<td style="border:none;padding:3px 0px 0px 15px;width:35px;">&nbsp;</td>';
		slabel = slabel + '				<td class="'+sicon+'" style="border:none;padding:3px 0px 0px 0px;font-weight:300;width:20vW;">&nbsp;&minus;&nbsp;' + valarr[0] + '</td>';
		slabel = slabel + '				<td style="border:none;padding:3px 0px 0px 0px;font-weight:200;"><span style="font-weight:200;">&minus;</span>&nbsp;' + valarr[1] + '</td>';
		slabel = slabel + '			</tr>';
		slabel = slabel + '		</tbody>';
		slabel = slabel + '</table>';
		// console.log('getgrouptitle(file):', valarr);
	}
	return slabel;
}
