//
//***********************************************************************
//																																			*
// 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.
**/
//
var local_ip = '0.0.0.0';
var local_port = '0';
var timeHandlerPassive = false;


var app = {
	sid: '',
	trans: {
		yes: 'Yes',
		no: 'No',
		ok: 'OK',
		cancel: 'Cancel',
		items: 'Item(s)',
		today: 'Heute',
		close: 'Schließen',
		weeks: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
		months: ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez']
	},
	lang: 'de',
	theme: 'default',
	user: null,
	user_id: null,
	user_group: null,
	user_bmson: null,
	schema: null,
	range: null,
	module: [],
	timestart: 0,
	timeend: 0,
	active_module: 'archium',
	characters:'ACBDFEGIHJLKMONPRQSUTVXWZY9876543210acbdfegihjlkmonprqsutvxwzy',
	easyui: function (id) {
		return $.parser.parse(id);
	},
	// declare all characters
	generateId(length) {
		let result = '';
		const charlength = app.characters.length;
		for ( let i = 0; i < length; i++ ) {
			result += app.characters.charAt(Math.floor(Math.random() * charlength));
		}
		return result;
	},
	createID: function () {
		var maxlen = 59
		var actlen = 0;
		var id = '';
		for (var i	=0; i<maxlen; i++){
			var ran = Math.random(5);
			id = id + app.generateId(ran);
			actlen = id.length;
			if (actlen >= maxlen){
				id = id.substr(0, maxlen);
			}
		}
		return 'sess_'+id;
	},
	getID: function (_new) {
		if (((app.sid).length == 0) || (_new)) {
			app.sid = app.createID();
			console.log('app.getId():', _new, app.sid);
		}
		return app.sid;
	},
	// locale IP ermitteln (2021.07.14)
	getLocalip: function(){
		// getlocalIp();
		var params 		= {};
		params.app 		= (app!=null)?((typeof app.sid === 'string')?app.sid:''):'null';
		params.caller	= 'app.getlocalIp()';
		params.fn			= 'getlocalIp';
		//
		//console.log('>>getlocalIp(params):', params);	
		$.postJSON('', params, function(data){
			app.message(data.msg);
			//console.log('>>getlocalIp(data):', data);	
			if (data.success == true){
				local_ip = data.ip;
			}
		});		
	},	isWindow: function (obj) {
		return obj != null && obj === obj.window;
	},
	isWindowJ: function (obj) {
		return (obj.length > 0);
	},
	// schliessen der dialoge auf ESC und ENTER
	bindKeyaction: function (_formname){	
		// console.log('bindKeyaction('+_formname+')');
		var dlg = $(_formname);
		if (dlg.length == 1){
			dlg.window('window').focus().bind('keyup', function(e){
				switch(e.keyCode){
					case 27:{	// ESCAPE
						dlg.window('close').panel('destroy');
						break;
					}
					case 13:{	// ENTER
						// console.log('bindKeyaction('+_formname+'):', dlg);
						if (app.module[app.active_module]){
							if (typeof(app.module[app.active_module].gosearch) == 'function'){
								app.module[app.active_module].gosearch($(dlg), dlg); // suche ausführen
							}else{
								if (typeof(app.module[app.active_module].gosave) == 'function'){
									app.module[app.active_module].gosave(); // ergebnis sichern
								}
							}
						}
						break;
					}
				}
			});
		}
	},
	iffileexistExecute: function(_src, _callback, _failed) {
		const xhr = new XMLHttpRequest(),
			method = "GET",
			url = _src;
		
		xhr.open(method, url, true);
		xhr.onreadystatechange = function() {
			if (this.readyState === this.DONE) {
				var status = xhr.status;
				if (status === 0 || (status >= 200 && status < 400)) {
					if (typeof _callback == 'function'){
						_callback();
					}
				} else {
					if (typeof _failed == 'function'){
						_failed();
					}
					console.log('error:', xhr.responseText);
				}
			}
		}
		xhr.send();
	},	
	makeStruct: function(_names) {
		var names = _names.split(' ');
		var count = names.length;
		function constructor() {
			for (var i = 0; i < count; i++) {
				this[names[i]] = arguments[i];
			}
		}
		return constructor;
	},
	message: function (msg) {
		if (msg) {
			switch (msg) {
				case 'close': {
					console.log('message.close:');
					return $.messager.close();
				}
				default: {
					//console.log('message.text:', msg.msg)
					if (!msg.type)
						msg.type = 'show';
					msg.width = '30%';
					msg.height = '25%';
					$.messager.defaults.ok = app.trans.ok;
					return $.messager[msg.type](msg);
				}
			}
		}
	},
	confirm: function(msg, _callback){
		if (msg) {
			switch (msg) {
				case 'close': {
					console.log('message.close:');
					return $.messager.close();
				}
				default: {
					//console.log('message.text:', msg.msg)
					if (!msg.type)
						msg.type = 'show';
					msg.width = '35%';
					msg.height = '25%';
					$.messager.defaults.yes = app.trans.yes;
					$.messager.defaults.cancel = app.trans.cancel;
					return $.messager.confirm('Information', msg.msg, _callback);
				}
			}
		}
	},
	msgcenter: function(_msg, _callback){
		var dlg = $.messager.show({
			title: '<span style="color:red;">'+_msg.title+'</span>',
			msg: _msg.msg,
			width: '25%',
			height: '20%',
			showType:'fade',
			closable: false,
			style:{
				right:'',
				bottom:''
			}
		});
		
		if (typeof _callback == 'function'){
			window.setTimeout(function(_callback){
				dlg.dialog('close');
				_callback();
			}, 3000, _callback);
		}
	},
	// #############################################################################################
	// get string between
	// #############################################################################################	
	getstringBetween: function (_string, _start, _end){
		var string = ' ' + _string;
		var ini = string.indexOf(_start);
		if (ini == 0) return '';
		ini += _start.length;
		string = string.substr(ini)
		var len = string.indexOf(_end);
		return string.substr(0, len);
	},
	getTimecompact: function(_time){
		var timestr =	
			_time.getUTCFullYear() + 
			("0" + (_time.getUTCMonth()+1)).slice(-2) + 
			("0" + _time.getUTCDate()).slice(-2) + 
			("0" + _time.getUTCHours()).slice(-2) + 
			("0" + _time.getUTCMinutes()).slice(-2) +
			("0" + _time.getUTCSeconds()).slice(-2);
		//
		return timestr;
	},
	setLogin: function (_this) {
		console.log('setLogin(): ', app.sid, _this)
		app.module[app.active_module].execute(_this, 'login', '');
	},
	themechange: function(_theme){
		if (typeof _theme != 'undefined'){
			var link = $('.theme').find('link');
			if (link.length == 1){
				app.theme = _theme;
				link.attr('href', ('jeasyui/themes/'+_theme+'/easyui.css').toLowerCase());
			}
		}
		var linkcloud = $('.cloud').find('link:first');
		if (linkcloud.length == 1){
			linkcloud.attr('href', ('css/cloud.css').toLowerCase());
		}
	},
	//
	win: null,
	waitpos: 0,
	waitint: 300,
	waitrun: false,
	waitmax: 100,
	wait_timer: false,
	wait: function(_title, _caption, _first){
		window.clearTimeout(app.wait_timer);
		if ((_first == true) | (app.waitpos == 0)){
			app.waitrun = true;
			app.waitpos = 0;
			app.win = $.messager.progress({
				title:_title
				,width:'350px'
				,msg: _caption.replace('%seconds%', Math.round(app.waitmax/10).toString())
				,interval: 0
			});
		}
		// console.log('wait-close:', app.waitpos, app.waitmax, app.wait_timer, app.waitrun);
		//
		if ((app.waitrun == false) || (app.waitpos >= app.waitmax)){
			app.waitclose();
			return;
		}
		app.wait_timer = window.setTimeout(function(){
			app.waitpos++;
			app.waitprogress(app.waitpos, 'app.wait()', app.waitpos);
			app.wait(_title, _caption, false);
		}, app.waitint);
	},
	waittitle: function(_title, _caption, _first){
		app.waitrun = true;
		if (_first){
			app.timestart = Date.now()
			$.messager.progress('close');
			app.win = $.messager.progress({
				title:_title,
				msg:_caption,
				//value: false,
				interval: 0
			});
			if (app.win != null){
				app.win.dialog('setTitle', _title);
				app.win.find('.messager-p-msg').html(_caption);
			}else{
				app.win = $.messager.progress({
					title:_title,
					msg:_caption,
					interval: 0
				});
			}
		}
	},
	waitprogress: function(_progress, _func, _what){
		app.waitpos = _progress;
		if (app.win != null){
			//console.log('wait-progress:', _progress, _func, _what, app.waitpos, app.waitmax, app.win);
			app.win.find('.messager-p-bar').progressbar('setValue', Math.round((app.waitpos*100)/app.waitmax).toString());
		}
	},
	waitclose: function(){
		if (app.wait_timer){
			window.clearTimeout(app.wait_timer);
		}
		app.wait_timer = false;
		app.waitprogress(100);
		app.waitpos = 0;
		app.waitrun = false;
		app.wait_timer = window.setTimeout(function(){
			$.messager.progress('close');
			app.timeend = Date.now()
			// console.log('wait-close:', ', dauer(ms):', app.timeend-app.timestart, app.waitpos, app.waitmax);
			app.win = null;
		}, app.waitint);
		return;
	}
	//
}

var sids = [];

function block(_message, _width, _caption){
	var message = _message;
	if (_caption){
		message = message.replace('%caption%', '"'+_caption+'"');
	}
	$.blockUI({
		message: message, 
		css:{ 
			width: ''+_width,
			border: 'none', 
			padding: '10px', 
			backgroundColor: '#808080', '-webkit-border-radius': '5px',	'-moz-border-radius': '5px', 
			opacity: .5, 
			color: 'white'
		}
	});
}

function unblock(){
	$.unblockUI();
}

$.postJSON = function (url, params, _success, _complete){
	// console.log('(POST) postJSON-request:', params);
	jQuery.ajax({
		'type': 'POST',
		'url': url,
		'data': params,
		'async': true,
		'dataType': params.type,
		'success': function(data){
			if (typeof _success == 'function'){
				//console.log('postJSON received data: ', params.type, params.what, data);
				// umwandlung sting in JSON-array bzw. object
				var obj = undefined;
				// data = data.replace('&#34;', '"');
				switch (params.type){
					case 'json':{
						if (typeof data === 'object'){ 
							obj = data; 
						}else{
							obj = JSON.parse(data);
						}
					}
					case 'html':{
						if (typeof data === 'string'){ 
							obj = data; 
						}else{
							if (typeof data === 'object'){ 
								obj = JSON.stringify(data);
							}
						}
						obj = JSON.stringify(data);
					}
					default: obj = data;
				}
				if (typeof data === 'object'){ 
					if (data.released == true){
						window.setTimeout(function(_msg){
							_msg.title = 'Session timed out..';
							console.log(_msg);
							app.msgcenter(_msg, function(){
								app.module[app.active_module].logout();
							});
						}, 100, data.msg);
						data.msg = null;
					}
					if (data.success == false){
						app.waitclose();
					}
				}
				_success(obj);
			}
		},
		'complete': _complete
	}).fail(function(jqxhr, textStatus, error){
		console.log('postJSON fail: ', jqxhr, textStatus, error, jqxhr.responseText);
		app.message({type:'alert', title:'ERROR postJSON in "'+params.func+'"', msg:textStatus + ", " + error});
		app.waitclose();
	});
};

$.toJSON = function (o){
	if (typeof(JSON) == 'object' && JSON.stringify)
		return JSON.stringify(o);
	var type = typeof(o);
	if (o === null)
		return "null";
	if (type == "undefined")
		return undefined;
	if (type == "number" || type == "boolean")
		return o + "";
	if (type == "string")
		return $.quoteString(o);
	if (type == 'object'){
		if (typeof o.toJSON == "function")
			return $.toJSON(o.toJSON());
		if (o.constructor === Date){
			var month = o.getUTCMonth() + 1;
			if (month < 10)
				month = '0' + month;
			var day = o.getUTCDate();
			if (day < 10)
				day = '0' + day;
			var year = o.getUTCFullYear();
			var hours = o.getUTCHours();
			if (hours < 10)
				hours = '0' + hours;
			var minutes = o.getUTCMinutes();
			if (minutes < 10)
				minutes = '0' + minutes;
			var seconds = o.getUTCSeconds();
			if (seconds < 10)
				seconds = '0' + seconds;
			var milli = o.getUTCMilliseconds();
			if (milli < 100)
				milli = '0' + milli;
			if (milli < 10)
				milli = '0' + milli;
			return '"' + year + '-' + month + '-' + day + 'T' + hours + ':' + minutes + ':' + seconds + '.' + milli + 'Z"';
		}
		if (o.constructor === Array){
			var ret = [];
			for (var i = 0; i < o.length; i++)
			ret.push($.toJSON(o[i]) || "null");
			return "[" + ret.join(",") + "]";
		}
		var pairs = [];
		for (var k in o){
			var name;
			var type = typeof k;
			if (type == "number")
				name = '"' + k + '"';
			else if (type == "string")
				name = $.quoteString(k);
			else
				continue; //skip non-string or number keys
			if (typeof o[k] == "function")
				continue; //skip pairs where the value is a function.
			var val = $.toJSON(o[k]);
			pairs.push(name + ":" + val);
		}
		return "{" + pairs.join(", ") + "}";
	}
};
