// ha szeretnénk debug üzeneteket kiíratni js függvényekkel, akkor 1.
var debug = 0;
// Beégetett, előre betöltött képek
var img_load= new Image();
img_load.src= "graphics/engine/load.gif";
var img_ok= new Image();
img_ok.src= "graphics/engine/ok.png";
var img_error= new Image();
img_error.src= "graphics/engine/error.png";
var img_imp= new Image();
img_imp.src= "graphics/engine/important.png";

// kiléptetés ennyi idő után
var session_start = new Date().getTime() / 1000.0;
var ctimeout;
var ctimeout_intv;
var timeout = (ctimeout==undefined ? 60 : ctimeout*60 );
var timeout_intv = (ctimeout_intv==undefined ? 120000 : ctimeout_intv*60*1000 );
var timeout_flag = 0;
// gyökér elérés
var url = document.location.href;
var xend = url.lastIndexOf("/") + 1;
var base_url = url.substring(0, xend);
//időzítő ellenőrzése
var statusmsg_timer=undefined; // statusbar időzítő állapota
var loadstb=null;

// kiléptetés időzítő
function reload(){
	if((session_start + 60 * timeout < (new Date().getTime() / 1000.0)) && timeout_flag==0){
		// timeout
		timeout_flag = 1;
		ajax_raw_do('login/logout.php');
	} else {
		// regenerate php session
		timeout_flag = 0;
		new Ajax.Request(base_url+'ajax/session-renew.php');
	}
}

setInterval("reload()", timeout_intv);


// paraméterek escape-elése object formába
function encode(item){
	return item;
	for (x in item)
	{
		if (Object.isString(item[x]))
			item[x]=Url.encode(item[x]);
		else
			item[x]=item[x];
	}
	return new Hash(item);
}

// js függvény csatolása fájlhoz
function include_js(destination) {
	var e=document.createElement('script');
	e.type = 'text/javascript';
	e.src=base_url+'js/'+destination + (destination.indexOf('?')!=false ? '&' : '?') +'rand=' + Math.random();
	//$('inlcudejs').update('<script>'+e.src+'</script>');
	//if (e) {
		window.document.body.appendChild(e);
	//}
}
// js forrás
function include_src(source) {
	var e=document.createElement('script');
	e.innerHTML=source;
	document.body.appendChild(e);
}
/**
 * statusbar-ra írás
 * content:	kiírandó szöveg
 * timer: 	az üzenet láthatósága másodpercben
 * 			ha 0, akkor nem tűnik el
 * img:		kép a szöveg előtt
 */
function statusmsg(content,timer,img){
	clearTimeout(statusmsg_timer);
	if (content == undefined) content='';
	$('statusbar').update((img != undefined ? '<span><img style="vertical-align:middle" src="'+img.src+'"></span> ' : '')+content);
	if (timer == undefined) timer=2;
	if (timer != 0)
		statusmsg_timer=setTimeout(function(){$('statusbar').update('');}, (timer*1000));
}
/**
 * statusbar-ra írás + ok kép a szöveg elején
 * content:	kiírandó szöveg
 * timer: láthatóság másodpercben
 */
function statusmsg_ok(content,timer){
	statusmsg(content,timer,img_ok);
}
/**
 * statusbar-ra írás + error kép a szöveg elején
 * content:	kiírandó szöveg
 * timer: láthatóság másodpercben
 */
function statusmsg_err(content,timer){
	statusmsg(content,timer,img_error);
}
/**
 * statusbar-ra írás + sys kép a szöveg elején
 * content:	kiírandó szöveg
 * timer: láthatóság másodpercben
 */
function statusmsg_sys(content,timer){
	statusmsg(content,timer,img_imp);
}
/**
 * statusbar-ra írás + throbber kép a szöveg elején
 * content:	kiírandó szöveg
 * a szöveg automatikusan nem tűnik el
 */
function statusmsg_load(content){
	statusmsg(content,0,img_load);
}

function statusmsg_(content,timer){
	content=white_space(content);
	if (content.substr(0,1)=='+'){
		statusmsg_ok(content.substr(1),timer);
	}
	else if (content.substr(0,1)=='-'){
		statusmsg_err(content.substr(1),timer);
	}
	else{
		statusmsg(content,timer);
	}
}

function logout(){
	ajax_raw_do('login/logout.php');
}
function regenerate_session(){
	session_start = new Date().getTime() / 1000.0;
    timeout_flag = 0;
}

function ajax_do(url,param){
if(1 == timeout_flag){
	logout();
} else{
    regenerate_session();
	ajax_raw_do(url,param);
}
}

/**
 * régi engine wrapper, du not júz
 */
function ajax_raw_do(url,pparam){
	statusmsg_load("Betöltés");
	var param=new Hash();
	if (url!=""){
		var hurl=url.substr(0,url.indexOf('.php'));
		var i;
		var postbase='';
	for(i=0;i<hurl.split('/').length;i++){
		postbase+='../';
	}
	if (url.indexOf('?')>0){
		param.update(url.parseQuery());
		url=url.substr(0,url.indexOf('?'));
	}
	if (pparam != undefined || pparam != ''){
		param.update(pparam);
	}
	param.set('base_url',postbase);
	param.set('rand',Math.random());
	include_js('jsload.php?file='+hurl);
	new Ajax.Request(base_url+'ajax/'+url,{
		method: 'get',
		parameters: param,
		onComplete: function(request){
			if (request.getResponseHeader('Content-Type').indexOf('javascript')>0){
				if ($('statusbar').innerHTML.indexOf('Betöltés')>0)
					statusmsg_ok('Betöltve');
			}
			else{
				$('tartalom').update(request.responseText);
				statusmsg_ok('Betöltve');
			}
		},
		onFailure: function(){
			statusmsg_err("Hálózati hiba, kérem próbálja meg később! ("+request.status+")",6);
		}
	});
	}
}

/**
 * új betöltő függvény
 * Használata:
 * 	url:	(string)	fájl urija, az ajax mappától viszonyítva
 * 	param:	(javascript objektum)	{ valtozo_neve: valtozo_erteke, valtozo2: ertek2}
 *	onsuccess:	(function)	function(request){...}
 *				ha nincs definiálva, akkor a tartalom-ba íródik az eredmény tartalma
 *				definiálás példa:
 *				function(request){
					$('masiktartalom_id').innerHTML=request.responsText; // eremény kiírása
					statusmsg('Sikerült betölteni...');
				}
 */
function ajax_request(url,pparam,onsuccess){
	var param=new Hash();
	if(1 == timeout_flag){
		logout();
	} else{
		regenerate_session();
		if (pparam != undefined || pparam != ''){
		param.update(pparam);
		}
		statusmsg_load("Betöltés");
		if (onsuccess == undefined || onsuccess==''){
			onsuccess= function(request){
				$('tartalom').update(request.responseText);
				statusmsg_ok('Betöltve');
			}
		}
		else{
			if (onsuccess != undefined && !Object.isFunction(onsuccess)){
				var ajdi=onsuccess;
				onsuccess= function(request){
				$(ajdi).update(request.responseText);
				statusmsg_ok('Betöltve');
			}
			}
		}
		var randparam;
		if (url.indexOf('?')>0){
			randparam="&rand=" + Math.random();
		}
		else{
			randparam="?rand=" + Math.random();
		}
		var hurl=url.substr(0,url.indexOf('.php'));
		var urltags=hurl.split('/');
		var i;
		var postbase='';
		for(i=0;i<urltags.length;i++){
			postbase+='../';
		}
		param.set('base_url',postbase);
				var head= document.getElementsByTagName('head')[0];
				var script= document.createElement('script');
				script.type= 'text/javascript';
				if (Prototype.Browser.IE){
				script.onreadystatechange= function () {
					if (this.readyState=='loaded'){
					new Ajax.Request(base_url+'ajax/'+url+randparam,{
						method: 'post',
						parameters: param,
						onSuccess: onsuccess,
						onFailure: function(request){
							statusmsg_err("Hálózati hiba, kérem próbálja meg később! ("+request.status+")",6);
						}
					});
					}
					}
				}
				else{
				script.onload= function () { new Ajax.Request(base_url+'ajax/'+url+randparam,{
						method: 'post',
						parameters: param,
						onSuccess: onsuccess,
						onFailure: function(request){
							statusmsg_err("Hálózati hiba, kérem próbálja meg később! ("+request.status+")",6);
						}
					});}
				}
				script.src= 'js/jsload.php?file='+hurl;
				head.appendChild(script);
		
	}
	
}

/**
 * új végrehajtó függvény, pl mentés,törlés, stb
 * Használata:
 * 	url:	(string)	fájl urija, az ajax mappától viszonyítva
 * 	param:	(javascript objektum)	{ valtozo_neve: valtozo_erteke, valtozo2: ertek2}
 *	before:	(function)	function(){...}
 *				betöltés előtt hívódik meg
 *				ha nincs definiálva, akkor a statusbarba Feldolgozás íródik ki
 *				definiálás példa:
 *				function(){
					statusmsg_load('mentés...');
				}
 *	after:	(function)	function(){...}
 *				sikeres betöltéskor hívódik meg
 *				ha nincs definiálva, akkor a végrehajtott fájl kimenete íródik a statusbar-ba
 *				definiálás példa:
 *				function(){
					statusmsg_ok('mentve');
				}
				vagy
				//feltéve, ha a generált kimenet első karaktere +, ha sikeres a végrehajtás
				function(request){
					if (request.responseText.substr(0,1)=="+"){
						statusmsg_ok(request.responseText.substr(1));
					}
					else{
						statusmsg_err(request.responseText);
					}
				}
 *	afterfail:	(function)	function(){...}
 *				sikertelen betöltéskor hívódik meg
 *				ha nincs definiálva, akkor a statusbar-ba "Hálózati hiba, kérem próbálja meg később!" íródik ki
 *				definiálás példa:
 *				function(){
					statusmsg_err('Túlterhelt szerver, időtullépés',6);
				}
 */
function ajax_update(url,pparam,before,after,afterfail){
	var param=new Hash();
	if(1 == timeout_flag){
		logout();
	} else{
		regenerate_session();
		if (pparam != undefined || pparam != ''){
		param.update(pparam);
		}
		if (before != undefined && before != ''){
			before();
		}
		else{
			statusmsg_load("Feldolgozás");
		}
		var randparam;
		if (url.indexOf('?')>0){
			randparam="&rand=" + Math.random();
		}
		else{
			randparam="?rand=" + Math.random();
		}
		var hurl=url.substr(0,url.indexOf('.php'));
		var urltags=hurl.split('/');
		var i;
		var postbase='';
		for(i=0;i<urltags.length;i++){
			postbase+='../';
		}
		param.set('base_url',postbase);
		var head= document.getElementsByTagName('head')[0];
		var script= document.createElement('script');
		script.type= 'text/javascript';
		if (Prototype.Browser.IE){
		script.onreadystatechange= function () {
			if (this.readyState=='loaded'){
			new Ajax.Request(base_url+'ajax/'+url+randparam,{
							method: 'post',
							parameters: param,
							onSuccess: function(request){
								if (after != undefined && after != ''){
									after(request);
								}
								else{
									statusmsg_(request.responseText);
								}
							},
							onFailure: function(request){
								statusmsg_err("Hálózati hiba, kérem próbálja meg később! ("+request.status+")",6);
								if (afterfail != undefined && afterfail != ''){
									afterfail();
								}
							}
						});
			}
			}
		}
		else{
		script.onload= function () { new Ajax.Request(base_url+'ajax/'+url+randparam,{
							method: 'post',
							parameters: param,
							onSuccess: function(request){
								if (after != undefined && after != ''){
									after(request);
								}
								else{
									statusmsg_(request.responseText);
								}
							},
							onFailure: function(request){
								statusmsg_err("Hálózati hiba, kérem próbálja meg később! ("+request.status+")",6);
								if (afterfail != undefined && afterfail != ''){
									afterfail();
								}
							}
						});}
		}
		script.src= 'js/jsload.php?file='+hurl;
		head.appendChild(script);
	}
}

function datepicker(id){
	if (id==undefined){
		$$('.date').each(function(item){
			datepicker(item.id);
		});
	}
	else{
	if (!($(id).disabled))
	var dpicker = new DatePicker({
	 relative : id,
	        keepFieldEmpty:true,
			language:  'hu',
			dateFormat: [ ["yyyy","mm","dd"], "-" ]
});
	}
//return dpicker;
}
//MD5 Kódolás
// használata "sztring".md5()
(function(){

	var md5 = 
	{
		hexcase : 0,  		/* hex output format. 0 - lowercase; 1 - uppercase        */
		b64pad  : "", 		/* base-64 pad character. "=" for strict RFC compliance   */
		chrsz   : 8, 		/* bits per input character. 8 - ASCII; 16 - Unicode      */

		/**
		* These are the functions you'll usually want to call
		* They take string arguments and return either hex or base-64 encoded strings
		*/
		'hex_md5' : function(s)
		{
			return this.binl2hex(this.core_md5(this.str2binl(s), s.length * this.chrsz));
		},
		
		'b64_md5' : function(s)
		{
			return this.binl2b64(this.core_md5(this.str2binl(s), s.length * this.chrsz));
		},
		
		'str_md5' : function(s)
		{
			return this.binl2str(this.core_md5(this.str2binl(s), s.length * this.chrsz));
		},
		
		'hex_hmac_md5' : function(key, data)
		{
			return this.binl2hex(this.core_hmac_md5(key, data));
		},
		
		'b64_hmac_md5' : function(key, data)
		{
			return this.binl2b64(this.core_hmac_md5(key, data));
		},
		
		'str_hmac_md5' : function(key, data)
		{
			return this.binl2str(this.core_hmac_md5(key, data));
		},
		
		/**
		* Calculate the MD5 of an array of little-endian words, and a bit length.
		*
		*/
		'core_md5' : function(x, len)
		{
			x[len >> 5] |= 0x80 << ((len) % 32);
			x[(((len + 64) >>> 9) << 4) + 14] = len;
			
			var a =  1732584193;
			var b = -271733879;
			var c = -1732584194;
			var d =  271733878;
			
			for(var i = 0; i < x.length; i += 16)
			{
				var olda = a;
				var oldb = b;
				var oldc = c;
				var oldd = d;
				
				a = this.md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
				d = this.md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
				c = this.md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
				b = this.md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
				a = this.md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
				d = this.md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
				c = this.md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
				b = this.md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
				a = this.md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
				d = this.md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
				c = this.md5_ff(c, d, a, b, x[i+10], 17, -42063);
				b = this.md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
				a = this.md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
				d = this.md5_ff(d, a, b, c, x[i+13], 12, -40341101);
				c = this.md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
				b = this.md5_ff(b, c, d, a, x[i+15], 22,  1236535329);
				
				a = this.md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
				d = this.md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
				c = this.md5_gg(c, d, a, b, x[i+11], 14,  643717713);
				b = this.md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
				a = this.md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
				d = this.md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
				c = this.md5_gg(c, d, a, b, x[i+15], 14, -660478335);
				b = this.md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
				a = this.md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
				d = this.md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
				c = this.md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
				b = this.md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
				a = this.md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
				d = this.md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
				c = this.md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
				b = this.md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
				
				a = this.md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
				d = this.md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
				c = this.md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
				b = this.md5_hh(b, c, d, a, x[i+14], 23, -35309556);
				a = this.md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
				d = this.md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
				c = this.md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
				b = this.md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
				a = this.md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
				d = this.md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
				c = this.md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
				b = this.md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
				a = this.md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
				d = this.md5_hh(d, a, b, c, x[i+12], 11, -421815835);
				c = this.md5_hh(c, d, a, b, x[i+15], 16,  530742520);
				b = this.md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
				
				a = this.md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
				d = this.md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
				c = this.md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
				b = this.md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
				a = this.md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
				d = this.md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
				c = this.md5_ii(c, d, a, b, x[i+10], 15, -1051523);
				b = this.md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
				a = this.md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
				d = this.md5_ii(d, a, b, c, x[i+15], 10, -30611744);
				c = this.md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
				b = this.md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
				a = this.md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
				d = this.md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
				c = this.md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
				b = this.md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
				
				a = this.safe_add(a, olda);
				b = this.safe_add(b, oldb);
				c = this.safe_add(c, oldc);
				d = this.safe_add(d, oldd);
			}
			return Array(a, b, c, d);
		},

		/**
		* These functions implement the four basic operations the algorithm uses.
		* 
		*/
		'md5_cmn' : function(q, a, b, x, s, t)
		{
			return this.safe_add(this.bit_rol(this.safe_add(this.safe_add(a, q), this.safe_add(x, t)), s),b);
		},
		
		'md5_ff' : function(a, b, c, d, x, s, t)
		{
			return this.md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
		},
		
		'md5_gg' : function(a, b, c, d, x, s, t)
		{
			return this.md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
		},
		
		'md5_hh' : function(a, b, c, d, x, s, t)
		{
			return this.md5_cmn(b ^ c ^ d, a, b, x, s, t);
		},
		
		'md5_ii' : function(a, b, c, d, x, s, t)
		{
			return this.md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
		},

		/**
		* Calculate the HMAC-MD5, of a key and some data.
		*
		*/
		'core_hmac_md5' : function(key, data)
		{
			var bkey = this.str2binl(key);
			if(bkey.length > 16)
				bkey = this.core_md5(bkey, key.length * this.chrsz);
			
			var ipad = Array(16), opad = Array(16);
			for(var i = 0; i < 16; i++) 
			{
				ipad[i] = bkey[i] ^ 0x36363636;
				opad[i] = bkey[i] ^ 0x5C5C5C5C;
			}
			
			var hash = this.core_md5(ipad.concat(this.str2binl(data)), 512 + data.length * this.chrsz);
			return this.core_md5(opad.concat(hash), 512 + 128);
		},


		/**
		* Add integers, wrapping at 2^32. This uses 16-bit operations internally
		* to work around bugs in some JS interpreters.
		*
		*/
		'safe_add' : function(x, y)
		{
			var lsw = (x & 0xFFFF) + (y & 0xFFFF);
			var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
			return (msw << 16) | (lsw & 0xFFFF);
		},
		
		/**
		* Bitwise rotate a 32-bit number to the left.
		*
		*/
		'bit_rol' : function(num, cnt)
		{
			return (num << cnt) | (num >>> (32 - cnt));
		},
		
		/**
		* Convert a string to an array of little-endian words.
		* If this.chrsz is ASCII, characters >255 have their hi-byte silently ignored.
		*
		*/
		'str2binl' : function(str)
		{
			var bin = Array();
			var mask = (1 << this.chrsz) - 1;
			for(var i = 0; i < str.length * this.chrsz; i += this.chrsz)
				bin[i>>5] |= (str.charCodeAt(i / this.chrsz) & mask) << (i%32);
			return bin;
		},
		
		/**
		* Convert an array of little-endian words to a string
		*
		*/
		'binl2str' : function(bin)
		{
			var str = "";
			var mask = (1 << this.chrsz) - 1;
			for(var i = 0; i < bin.length * 32; i += this.chrsz)
				str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
			return str;
		},
		
		/**
		* Convert an array of little-endian words to a hex string.
		*
		*/
		'binl2hex' : function(binarray)
		{
			var hex_tab = this.hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
			var str = "";
			for(var i = 0; i < binarray.length * 4; i++)
			{
				str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
				hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
			}
			return str;
		},
		
		/**
		* Convert an array of little-endian words to a base-64 string
		*
		*/
		'binl2b64' : function(binarray)
		{
			var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
			var str = "";
			for(var i = 0; i < binarray.length * 4; i += 3)
			{
				var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
				| (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
				|  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
				for(var j = 0; j < 4; j++)
				{
					if(i * 8 + j * 6 > binarray.length * 32)
						str += this.b64pad;
					else
						str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
				}
			}
			return str;
		}
	};

	/**
	* Returns the md5 hash of the given string.
	*
	* @example "JavaScript".md5();
	* @result "686155af75a60a0f6e9d80c1f7edd3e9"
	*
	* @name md5
	* @return String
	*/
	if(!String.prototype.md5)
		String.prototype.md5 = function()
		{
			return md5.hex_md5(this);
		}
})();

// URL encode/decode
var Url = {
 
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
 
	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function m4(url) {
	ajax_raw_do(url);
	ajax_raw_do('main/menu.php?p=0');
}
function logincall() {
	ajax_do('login/main.php')
	ajax_do('main/menu.php?q=3')
}

//multiple select
function multi_coll(a){
	thk=0;
	for(i=0;i<a.length;i++){
		if(a.options[i].selected){
			thk=Number(thk) + Number(a.options[i].value);
		}	
	}
	return thk;
}
function ecode(s) {
	/*
	s2="" 
	for (i=0;i<s.length;i++)
	 if (s.charAt(i)=='é') s2=s2+"%m"
	 else if (s.charAt(i)=='ö') s2=s2+"%o"
	 else if (s.charAt(i)=='ü') s2=s2+"%u"
	 else if (s.charAt(i)=='ó') s2=s2+"%z"
	 else if (s.charAt(i)=='á') s2=s2+"%q"
	 else if (s.charAt(i)=='ő') s2=s2+"%w"
	 else if (s.charAt(i)=='ú') s2=s2+"%s"
	 else if (s.charAt(i)=='ű') s2=s2+"%p"
	 else if (s.charAt(i)=='í') s2=s2+"%i"
	 else if (s.charAt(i)=='É') s2=s2+"%M"
	 else if (s.charAt(i)=='Ö') s2=s2+"%O"
	 else if (s.charAt(i)=='Ü') s2=s2+"%U"
	 else if (s.charAt(i)=='Ó') s2=s2+"%Z"
	 else if (s.charAt(i)=='Á') s2=s2+"%Q"
	 else if (s.charAt(i)=='Ő') s2=s2+"%W"
	 else if (s.charAt(i)=='Ú') s2=s2+"%S"
	 else if (s.charAt(i)=='Ű') s2=s2+"%D"
	 else if (s.charAt(i)=='Í') s2=s2+"%I"	 
	 else if (s.charAt(i)=='&') s2=s2+"%h"	 
	 else if (s.charAt(i)=='#') s2=s2+"%k"	 	 
	 else if (s.charAt(i)=="'") s2=s2+"%$"	
	 else if (s.charAt(i)=='\\') s2=s2+"/"		
	 else if (s.charAt(i)=='–') s2=s2+"-" 
	 else if (s.charAt(i)=='+') s2=s2+"%-" 
         else if (s.charAt(i)=='ä') s2=s2+"%g" 
	else if (s.charAt(i)) s2=s2+s.charAt(i)
	*/
	return s;
}
function deco(s) {
	/*
	s2="" 
	for (i=0;i<s.length;i++)
	 if (s.charAt(i)=='ę') s2=s2+'"'
	 else if (s.charAt(i)=='€') s2=s2+"'"
	 else if (s.charAt(i)=='¶') s2=s2+"\n" ;
	 else if (s.charAt(i)=='Ņ') s2=s2+"<"
	 else if (s.charAt(i)=='Ļ') s2=s2+">" ;
	 else if (s.charAt(i)=='•') s2=s2+"&" ;
	 else if (s.charAt(i)=='Ż') s2=s2+"#" ;
	 else if (s.charAt(i)=='∆') s2=s2+"+" ;	 
	 else if (s.charAt(i)) s2=s2+s.charAt(i)
	 */
	return s;
}
function co(s) {
	/*
	s2="" 
	for (i=0;i<s.length;i++)
	 if (s.charAt(i)=='"') s2=s2+'ę'
	 else if (s.charAt(i)=="'") s2=s2+'€'
	 else if (s.charAt(i)=="\n") s2=s2+'¶' ;
	 else if (s.charAt(i)=="<") s2=s2+'Ņ'
	 else if (s.charAt(i)==">") s2=s2+'Ļ' ;
	 else if (s.charAt(i)=="&") s2=s2+'•' ;
	 else if (s.charAt(i)=='#') s2=s2+"Ż" ;
	 else if (s.charAt(i)=='+') s2=s2+"∆" ;	 
	 else if (s.charAt(i)) s2=s2+s.charAt(i)
	 */
	return s;
}
function iekf(e) {
	if (e.keyCode==13) keres(document.getElementById('km').value)
}
function kept(s) {
	ajax_do('keptar/kept.php?dir=/'+s)
}
function doct(s) {
	ajax_do('doctar/doct.php?dir=/'+s)
}
function white_space(text)
{
     return text.replace(/^\s*|\s*$/g,'');
}
function validDate(str){
	return ((str.match(/^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])/))==null ? false : true);
}
var window_factory = function(container,options){
		var window_header = new Element('div',{
			className: 'window_header'
		});
		var window_title = new Element('div',{
			className: 'window_title'
		});
		var window_close = new Element('div',{
			className: 'window_close'
		});
		var window_contents = new Element('div',{
			className: 'window_contents'
		});
        options=new Hash(options);
        options.set('rand',Math.random());
		var w = new Control.Window(container,Object.extend({
			className: 'window',
			closeOnClick: true,
			draggable: window_header,
			insertRemoteContentAt: window_contents,
            parameters: options,
			afterOpen: function(){
				window_title.update(container.readAttribute('title'))
			},
            afterClose: function(){
                window_contents.update('');
				w.destroy();
				window_factory(container,options);
			}
		}));
		w.container.insert(window_header);
		window_header.insert(window_title);
		window_header.insert(window_close);
		w.container.insert(window_contents);
	};
	
	
	var modal_window = function(container,options,afterclose){
		if(typeof(container) == "string" && container.match(Control.Window.uriRegex)) container='ajax/'+container;
		if (afterclose == undefined) {
			afterclose=function(){ this.destroy(); };
		}
		var x=new Control.Modal(container,{  
     overlayOpacity: 0.75,
	 parameters: options || {},
     className: 'window',
	 afterClose: afterclose,
     fade: true
		});
		return x;
	}
	
	var static_window = function(container){
		var x=new Control.Window(container,{  
			className: 'simple_window',  
		    closeOnClick: 'overlay' 
		});
		return x;
	}
	
	function number_format(a, b, c, d) {
		 a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
		 e = a + '';
		 f = e.split('.');
		 if (!f[0]) {
		  f[0] = '0';
		 }
		 if (!f[1]) {
		  f[1] = '';
		 }
		 if (f[1].length < b) {
		  g = f[1];
		  for (i=f[1].length + 1; i <= b; i++) {
		   g += '0';
		  }
		  f[1] = g;
		 }
		 if(d != '' && f[0].length > 3) {
		  h = f[0];
		  f[0] = '';
		  for(j = 3; j < h.length; j+=3) {
		   i = h.slice(h.length - j, h.length - j + 3);
		   f[0] = d + i +  f[0] + '';
		  }
		  j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
		  f[0] = j + f[0];
		 }
		 c = (b <= 0) ? '' : c;
		 return f[0] + c + f[1];
		}

	function multiselect_value(id){
		return $(id).getValue().split(',').toJSON();
	}
	
	var floating_header = function() {

this.header = document.createElement('table');
this.header_height = 0;

this.getkeys = function(obj) {
    var keys = new Array();
    for ( var key in obj ) {
        keys.push(key);
    }
    return keys;
};

this.getXY = function( o ) {
    var y = 0;
    var x = 0;
    while( o != null ) {
        y += o.offsetTop;
        x += o.offsetLeft;
        o = o.offsetParent;
    }
    return { "x": x, "y": y };
}

this.setheader = function() {
        var win = window.pageYOffset ? window.pageYOffset : 0;
        var cel = document.documentElement ? document.documentElement.scrollTop : 0;
        var body = document.body ? document.body.scrollTop : 0;
        var result = win ? win : 0;
        if ( cel && ( ! result || ( result > cel ))) result = cel;
        var screenpos = body && ( ! result || ( result > body ) ) ? body : result;
        var theady_max = this.getXY(this.table_obj.getElementsByTagName('THEAD')[0]).y + this.table_obj.offsetHeight - this.header_height;
        if ( screenpos > this.theady && screenpos < theady_max ) {
            this.header.style.top=Math.round(screenpos);
            this.header.style.display = 'block';
            this.header_height = header.offsetHeight;
        }
        else {
            this.header.style.display = 'none';
        }
}

this.addclass = function(obj, newclass) {
    if ( obj.classes == null ) {
        obj.classes = new Array();
    }
    obj.classes[newclass] = 1;
    obj.className = this.getkeys(obj.classes).join(' ');
    return true;
};

this.theady = 0;

this.build_header = function() {
    this.table_obj = document.getElementsByTagName('THEAD');
    if ( ! this.table_obj ) {
        alert("you MUST have <thead> and </thead> tags wrapping the part of the table you want to keep on the screen");
        return;
    }
    this.table_obj = this.table_obj[0];
    while ( this.table_obj.tagName != 'TABLE' ) {
        if ( this.table_obj.tagName == 'BODY' ) {
            alert('The THEAD section MUST be inside a table - how did you do that???');
            return;
        }
        this.table_obj = this.table_obj.parentNode;
    }

    thead = this.table_obj.getElementsByTagName('THEAD')[0].cloneNode(1);
    thead.id = 'copyFTrow';
    this.header.style.position='absolute';
    this.header.style.display='none';
    this.header.appendChild(thead);
    this.header.style.width = this.table_obj.offsetWidth;
    var srcths = this.table_obj.getElementsByTagName('THEAD')[0].getElementsByTagName('*');
    var copyths = thead.getElementsByTagName('*');
    for ( var x = 0; x < copyths.length; x++ ) {
        copyths[x].className = srcths[x].className;
        copyths[x].align = srcths[x].align;
        copyths[x].background = srcths[x].background;
        copyths[x].bgColor = srcths[x].bgColor;
        copyths[x].colSpan = srcths[x].colSpan;
        copyths[x].height = srcths[x].height;
        copyths[x].rowSpan = srcths[x].rowSpan;
        pr = Math.round(srcths[x].style.paddingRight.split('px')[0]);
        pl = Math.round(srcths[x].style.paddingLeft.split('px')[0]);
        bl = ( Math.round(srcths[x].style.borderLeftWidth.split('px')[0]) ) ? Math.round(srcths[x].style.borderLeftWidth.split('px')[0]) : 0;
        br = ( Math.round(srcths[x].style.borderRightWidth.split('px')[0]) ) ? Math.round(srcths[x].style.borderRightWidth.split('px')[0]) : 0;
        pt = Math.round(srcths[x].style.paddingTop.split('px')[0]);
        pb = Math.round(srcths[x].style.paddingBottom.split('px')[0]);
        bt = Math.round(srcths[x].style.borderTopWidth.split('px')[0]);
        bb = Math.round(srcths[x].style.borderBottomWidth.split('px')[0]);
        if ( srcths[x].currentStyle ) {
            for ( var y in srcths[x].currentStyle ) {
                if ( y == 'font' || y == 'top' ) continue;
                copyths[x].style[y] = srcths[x].currentStyle[y];
            }
            pr = Math.round(srcths[x].currentStyle.paddingRight.split('px')[0]);
            pl = Math.round(srcths[x].currentStyle.paddingLeft.split('px')[0]);
            bl = ( Math.round(srcths[x].currentStyle.borderLeftWidth.split('px')[0]) ) ? Math.round(srcths[x].currentStyle.borderLeftWidth.split('px')[0]) : 0;
            pt = Math.round(srcths[x].currentStyle.paddingTop.split('px')[0]);
            pb = Math.round(srcths[x].currentStyle.paddingBottom.split('px')[0]);
            bt = Math.round(srcths[x].currentStyle.borderTopWidth.split('px')[0]);
        }
        if ( srcths[x].onclick ) copyths[x].onclick = srcths[x].onclick;
        var width = ( srcths[x].offsetWidth - pr - pl > 0 ) ? srcths[x].offsetWidth - pr - pl : 0;
        copyths[x].style.position = srcths[x].style.position;
        copyths[x].style.top = ( srcths[x].offsetTop - pt - pb > 0 ) ? srcths[x].offsetTop - pt - pb : srcths[x].offsetTop;
        copyths[x].style.top = srcths[x].style.top;
        copyths[x].style.height = srcths[x].offsetHeight;
        copyths[x].style.left = srcths[x].offsetLeft;
        if ( ! copyths[x].currentStyle ) {
            //copyths[x].style.width = Math.floor(document.defaultView.getComputedStyle(srcths[x],"").getPropertyValue("width").split('px')[0]);
            copyths[x].style.width = document.defaultView.getComputedStyle(srcths[x],"").getPropertyValue("width");
        }
        else {
            copyths[x].style.width = srcths[x].offsetWidth - pr - pl; // - bl;
            copyths[x].width = srcths[x].width;
        }
        if ( x == copyths.length - 1 ) {
            this.header.style.paddingBottom = pb;
            this.header.style.borderBottom = bb;
        }
    }
    this.addclass(this.header, 'main');
    document.body.appendChild(this.header);
    theady = this.getXY(this.table_obj.getElementsByTagName('THEAD')[0]).y;
}

this.build_header();
window.onscroll=this.setheader;

};
