/* Ajax v1.6 */
Ajax = {};
Ajax.createRequest = function(method, url, async, callback) {
	this.request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP");
	if (async) {
		this.request.onreadystatechange = callback;
	}
	this.request.open(method, url, async);
	this.request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-2');
	this.request.send(url);
}

Ajax.checkReadyState = function(boxId) {
	var box;
	var text = (window.form && form.LANG_FILES_PROGRESS) ? form.LANG_FILES_PROGRESS.value : 'Töltés';
	switch (this.request.readyState) {
		case 1:
			text += '.';
			break;
		case 2:
			text += '..';
			break;
		case 3:
			text += '...';
			break;
		case 4:
//			(boxId == null || boxId == undefined || boxId == '') ? window.status = '' : document.getElementById(boxId).innerHTML = '';
			(box = document.getElementById(boxId)) ? box.innerHTML = '' : window.status = '';
			AjaxUpdater.isUpdating = false;
			return this.request.status;
			break;
		default: text = 'An unexpected error has occured!';
	}
	(box = document.getElementById(boxId)) ? box.innerHTML = text : window.status = text;
	return 0;
}

Ajax.getResponse = function() {
	if (this.request.getResponseHeader('Content-Type').indexOf('xml') != -1) {
		return this.request.responseXML.documentElement;
	} else {
		return this.request.responseText;
	}
}

/* Ajax Updater */
AjaxUpdater = {};

AjaxUpdater.init = function() {
	this.isUpdating = false;
}

AjaxUpdater.update = function(method, url, async, callback) {
	if (callback == undefined || callback == '') {
		callback = this.onResponse;
	}
	Ajax.createRequest(method, url, async, callback);
	this.isUpdating = true;
}

AjaxUpdater.onResponse = function() {
	var s = Ajax.checkReadyState('requestStatus');
	if (s == 200) {
		var r = Ajax.getResponse();
		if (r != '') {
			alert(r);
		}
	} else if (s > 0) {
		alert(HTTP.status(s));
	}
}

AjaxUpdater.init();

/* DOMEditor v2.1 */
DOMEditor = {};

DOMEditor.createElement = function(tag, obj) {
	var property;
	var	element = document.createElement(tag);

	if (obj != undefined && obj != '') {
		/*@cc_on @if (@_jscript)
		// IE BUG
		if (obj['name'] || obj['type']) {
			var html = '<' + tag;
			var attr = ['name', 'type'];
			for(var i=0; i<attr.length; ++i){
				if (obj[attr[i]]) {
					html +=  ' ' + attr[i] + '="' + obj[attr[i]] + '"';
					delete(obj[attr[i]]);
				}
			}
			html += '>';
			if (tag == 'select' || tag == 'textarea' || tag == 'a' || tag == 'iframe' || tag == 'button') {
				html += '</' + tag + '>';
			}
			element = document.createElement(html);

		}
		/*@end @*/

		for (property in obj) {
			try {
				element[property] = obj[property];
			} catch(e) {
				//alert("DOMEditor.createElement : objektum tulajdonság megadása nem megengedett!\n" + element.tagName + '.' + property);
				element.setAttribute(property, obj[property]);
			}
		}
	}
	return element;
}

DOMEditor.checkNode = function(value) {
	if (typeof value == "string") {
		return document.getElementById(value);
	}
	return value;
}

DOMEditor.append = function(target) {
	if (arguments.length > 1) {
		target = this.checkNode(target);
		if (target == null) {
			return null;
		}
		for (var i=1; i<arguments.length; i++) {
			if (arguments[i]) {
				target.appendChild(arguments[i]);
			}
		}
		return target;
	} else {
		return null;
	}
}

DOMEditor.removeChildren = function(node) {
	node = this.checkNode(node);
	if (node == null) {
		return null;
	}
	while (node.hasChildNodes()) {
		node.removeChild(node.firstChild);
	}
}

DOMEditor.remove = function(node) {
	node = this.checkNode(node);
	if (node == null) {
		return null;
	}
	node.parentNode.removeChild(node);
}

DOMEditor.replace = function(node, target, newAsClone) {
	target = this.checkNode(target);
	node = this.checkNode(node);
	if (!target || !node) { return null; };
	if (newAsClone) {
		node = node.cloneNode(true);
		if (node.id) {
			node.removeAttribute('id');
		}
	}
	return target.parentNode.replaceChild(node, target);
}

DOMEditor.move = function(node, target, newAsClone, insertBefore) {
	target = this.checkNode(target);
	node = this.checkNode(node);
	if (!target || !node) { return null; };
	var removed = (!newAsClone) ? node.parentNode.removeChild(node) : node.cloneNode(true);
	return (insertBefore) ? target.parentNode.insertBefore(removed, target) : target.appendChild(removed);
}

DOMEditor.swap = function(node1, node2) {
	node1 = this.checkNode(node1);
	node2 = this.checkNode(node2);
	if(!node1 || !node2) { return null; };
	var clone1 = node1.cloneNode(true);
	var clone2 = node2.cloneNode(true);
	var replaced1 = node1.parentNode.replaceChild(clone2, node1);
	var replaced2 = node2.parentNode.replaceChild(clone1, node2);
}



/* HTTP */
HTTP = {};

HTTP.status = function(statusNr) {
	var txt;
	switch (statusNr) {
		// Tájékoztató
		case 100 : txt = 'Continue';			break; //folytatás
		case 101 : txt = 'Switching Protocol';	break; //protokoll váltás
		// Sikeres
		case 200 : txt = 'OK';							break; //rendben
		case 201 : txt = 'Created';						break; //létrehozva
		case 202 : txt = 'Accepted';					break; //elfogadva
		case 203 : txt = 'Non-Authorative Information';	break; //nem hiteles tájékoztató
		case 204 : txt = 'No Content';					break; //nincs tartalom
		case 205 : txt = 'Reset Content';				break; //visszaállított tartalom
		case 206 : txt = 'Partial Content';				break; //részleges tartalom
		// Átirányítás
		case 300 : txt = 'Multiple Choices';		break; //több választás
		case 301 : txt = 'Moved Permanently';		break; //tartósan áthelyezve
		case 302 : txt = 'Found';					break; //megtalálva
		case 303 : txt = 'See Other';				break; //lásd másik
		case 304 : txt = 'Not Modified';			break; //nincs módosítva
		case 305 : txt = 'Use Proxy';				break; //proxy kiszolgáló
		case 307 : txt = 'Temporary Redirected';	break; //átmeneti átirányítás
		// Ügyfélhiba
		case 400 : txt = 'Bad Request';						break; //hibás kérelem
		case 401 : txt = 'Unauthorized';					break; //nincs jóváhagyva
		case 402 : txt = 'Payment Required';				break; //fizetés szükséges
		case 403 : txt = 'Forbidden';						break; //tiltott
		case 404 : txt = 'File Not Found';					break; //a fájl nem található
		case 405 : txt = 'Method Not allowed';				break; //a függvény nem engedélyezett
		case 406 : txt = 'Not Accaptable';					break; //nem elfogadható
		case 407 : txt = 'Proxy Authentication Required';	break; //proxy kiszolgáló hitelesítése szükséges
		case 408 : txt = 'Request Timeout';					break; //időtúllépés
		case 409 : txt = 'Conflict';						break; //ütközés
		case 410 : txt = 'Gone';							break; //
		case 411 : txt = 'Length Required';					break; //hosszúság szükséges
		case 412 : txt = 'Precondition Failed';				break; //egy előfeltétel nem teljesült
		case 413 : txt = 'Request Entity Too Large';		break; //a kérelem túl nagy
		case 414 : txt = 'Request-URI Too Long';			break; //a kérelem uri túl hosszú
		case 415 : txt = 'Unsupported Media Type';			break; //nem támogatott médiatípus
		case 416 : txt = 'Requested Range Not Satisfiable';	break; //a kérelmezett tartomány nem kielégíthető
		case 417 : txt = 'Exception Failed';				break; //egy feltétel nem teljesült
		// Kiszolgálóhiba
		case 500 : txt = 'Internal Server Error';		break; //belső kiszolgálóhiba
		case 501 : txt = 'Not Implemented';				break; //nincs megvalósítva
		case 502 : txt = 'Bad Gateway';					break; //hibás átjáró
		case 503 : txt = 'Service Unavailable';			break; //a szolgáltatás nem elérhető
		case 504 : txt = 'Gateway Timeot';				break; //átjáró időtúllépés
		case 504 : txt = 'HTTP Version Not Supported';	break; //nem támogatott HTTP verzió

		default: txt = 'An unexpected error has occured';
	}
	return statusNr + ': ' + txt;
}

/* DEMO
AjaxUpdater.update(method, url, assyncroneBoolean, responseFunction);

function responseFunction() {
	var s = Ajax.checkReadyState('requestStatus');
	if (s == 200) {
		var r = Ajax.getResponse();
		eval('var obj=' + r + ';'); // Json
	} else if (s > 0) {
		alert(HTTP.status(s));
	}
}
*/
/* @version 2.0.1 */
function errorHandler(text, url, lineNr) {
	var txt = 'Hiba: ' + text + "\n Sor: " + lineNr + "\n";
	txt += "\n" + url;

	var E = new MyError(txt);
	if (document.forms[0].DEBUGGING) {
		E.alert();
	} else {
		if (url && url.indexOf('inc/js/') >= 0) {
			E.errorFeedback();
		}
	}
	return true;
}
window.onerror = errorHandler;


function MyError(message){
    this.message = (message) ? message : '';
    this.sysAlert = (!window.ModalWindow);
    if (!(this.sysAlert || Error.prototype.EWin)) {
		Error.prototype.EWin = new ModalWindow('_ErrorWindow');
    }
}
MyError.prototype = new Error();

Error.prototype.isError = false;
Error.prototype.errList = [];
Error.prototype.EWin = false;
Error.prototype.errorFeedback = function() {
	if (window.AjaxUpdater) {
		AjaxUpdater.update('POST', '_error/feedback.php?msg=' + escape(this.message.replace(/\n/gm, '<br/>')), true);
	}
}
Error.prototype.add = function(txt, input) {
	this.errList.push([txt, input]);
	this.isError = true;
}
Error.prototype.show = function() {
	if (this.errList.length > 0) {
		var err;
		for(var i=0; i<this.errList.length; i++) {
			err = this.errList[i];
			this.message += err[0] + "\n";
			if (err[1]) {
				try {
					err[1].className += " error";
					if (i == 0) {
						try{err[1].focus();} catch(e){};
					}
				} catch(e) {}
			}
		}

		this.alert();
	}
}
Error.prototype.alert = function(msg) {
	if (this.sysAlert) {
		alert(this.message);
	} else {
		Error.prototype.EWin.openWithVeil(this.message.replace(/\n/gm, '<br/>'), 'Hiba!', 0, 0);
		Error.prototype.EWin.show();
	}
}
Error.prototype.clear = function() {
	var err;
	for(var i=0; i<this.errList.length; i++) {
		err = this.errList[i];
		if (err[1] && typeof err[1].className == 'string') {
			err[1].className = err[1].className.replace(" error", '');
		}
	}
	this.isError = false;
	this.errList = [];
	this.message = '';
}
/* Demo:
	Validálás előtt, a legfelsőbb ellenőrző szinten, a korábbi hibák törlése:
	E.clear();

	validálás után:
	if (E.isError) {
		E.show();
	} else {
		//submit
	}
*/
/*
    * Error - base type for all errors. Never actually thrown by the engine.
    * EvalError - thrown when an error occurs during execution of code via eval()
    * RangeError - thrown when a number is outside the bounds of its range. For example, trying to create an array with -20 items (new Array(-20)). These occur rarely during normal execution.
    * ReferenceError - thrown when an object is expected but not available, for instance, trying to call a method on a null reference.
    * SyntaxError - thrown when the code passed into eval() has a syntax error.
    * TypeError - thrown when a variable is of an unexpected type. For example, new 10 or "prop" in true.
    * URIError - thrown when an incorrectly formatted URI string is passed into encodeURI, encodeURIComponent, decodeURI, or decodeURIComponent.


    if (E instanceof TypeError){
        //handle the error
    } else if (E instanceof ReferenceError){
        //handle the error
    } else {
        //handle all others
    }
*/function addEvent(obj, evType, fn) {
	try { 
		if (window.addEventListener) { //FF
			obj.addEventListener(evType, fn, true);
			return true;
		} else { //IE
			var r = obj.attachEvent("on" + evType, fn);
			return r;
		}  	
	} catch(err) {
	  	err = 'addEvent hiba : ' + err.message + "\n";
	  	if (obj) {
	  		err += 'Objektum : { name:' + obj.name +' id:' + obj.id + ' tag:' + obj.tagName + ' }';
	  	}
	  	err += "\nEsemény: " + evType;
	  	err += "\nFüggvény: " + fn;
	  	errorHandler(err, '', '');
	  	return false;
	}
}

function removeEvent(obj, evType, fn) {
	try {
		if (obj.removeEventListener) {
			obj.removeEventListener(evType, fn, true);
			return true;
		} else if (obj.detachEvent) {
			var r = obj.detachEvent("on" + evType, fn);
			return r;
		}
	} catch(err) {
	  	err = 'removeEvent hiba : ' + err.message + "\n";
	  	if (obj) {
	  		err += 'Objektum : { name:' + obj.name +' id:' + obj.id + ' tag:' + obj.tagName + ' }';
	  	}
	  	err += "\nEsemény: " + evType;
	  	err += "\nFüggvény: " + fn;
	  	errorHandler(err, '', '');
	  	return false;
	}
}

function getObj(ev) {
	ev || (ev = window.event);
	if (typeof ev.target != 'undefined') {
    	return ev.target;
	} else if (typeof ev.srcElement != 'undefined') {
    	return ev.srcElement;
    } else { 
    	return(false); 
    }
}

function killEvent(ev) {
	if (ev.preventDefault) {
    	ev.preventDefault(); 
    	ev.stopPropagation();
   	} else {
    	ev.cancelBubble = true; 
    	ev.returnValue = false;
  	}
  	return false;
}

/*
function DEMO(ev) {
	var obj;
	if (obj = getObj(ev)) {
		
	}
	return killEvent(ev);
}
*/
$addDOMLoadEvent = (function(){
    // create event function stack
    var load_events = [],
        load_timer,
        script,
        done,
        exec,
        old_onload,
        init = function () {
            done = true;

            // kill the timer
            clearInterval(load_timer);

            // execute each function in the stack in the order they were added
            while (exec = load_events.shift())
                exec();

            if (script) script.onreadystatechange = '';
        };

    return function (func) {
        // if the init function was already ran, just run this function now and stop
        if (done) return func();

        if (!load_events[0]) {
            // for Mozilla/Opera9
            if (document.addEventListener)
                document.addEventListener("DOMContentLoaded", init, false);

            // for Internet Explorer
            /*@cc_on @*/
            /*@if (@_win32)
                document.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>");
                script = document.getElementById("__ie_onload");
                script.onreadystatechange = function() {
                    if (this.readyState == "complete")
                        init(); // call the onload handler
                };
            /*@end @*/

            // for Safari
            if (/WebKit/i.test(navigator.userAgent)) { // sniff
                load_timer = setInterval(function() {
                    if (/loaded|complete/.test(document.readyState))
                        init(); // call the onload handler
                }, 10);
            }

            // for other browsers set the window.onload, but also execute the old window.onload
            old_onload = window.onload;
            window.onload = function() {
                init();
                if (old_onload) old_onload();
            };
        }

        load_events.push(func);
    }
})();

function $globalOnLoad() {
	E = new MyError();
	form = document.forms[0];
	var obj, i;

	if (obj = document.getElementById('spamdetect')) {
		form.robot_email.value = 'yes';
		obj.style.display = 'none';
	}

	obj = document.getElementsByTagName('a');
	for (i=0; i<obj.length; ++i) {
		obj[i].onfocus = function() {
			this.blur();
		}
		if (obj[i].lang) {
			$mailHideFromSpam(obj[i]);
		}
	}
	obj = form.elements;
	var focus = false;
	for (i=0; i<obj.length; ++i) {
		if (focus && (obj[i].type == 'text' || obj[i].type == 'textarea')) {
			try {
				obj[i].focus();
				focus = false;
			} catch(err) {
				continue;
			}
		} else if  (obj[i].type == 'button' ||
					obj[i].type == 'reset' ||
					obj[i].type == 'submit' ||
					obj[i].type == 'image' ||
					obj[i].type == 'radio' ||
					obj[i].type == 'checkbox') {

			if (obj[i].hideFocus) {
				obj[i].hideFocus = true;
			} else {
				obj[i].onfocus = function() {
					this.blur();
				}
			}
            if (obj[i].type == 'checkbox') {
				obj[i].$groupChecked = function() {
					var group = $gebtn(form, 'input');
                    var found = false;
					for (var i=0; i<group.length; i++) {
						if (group[i].checked && group[i].name == this.name) {
							found = true;
							break;
						}
					}
					return found;
				}
			}
		}
	}
	if (window.$onLoadEvents) {
		$onLoadEvents();
	}

	//document.onmousemove = mouseMove;
	return true;
}

$addDOMLoadEvent($globalOnLoad);

function $loadScript(script) {
	var obj =  {
		type	: 'text/javascript',
		language: 'JavaScript',
		src		: '/inc/js/' + script
	};
	DOMEditor.append(document.getElementsByTagName('head')[0], DOMEditor.createElement('script', obj));
}

String.prototype.$isEmpty = function() {
	return (this == null) ? true : (this.replace(/\s+/, '') == '');
}
String.prototype.$isNum = Number.prototype.$isNum = function() {
	return !(isNaN(this) || this == '' || this == null);
}
Array.prototype.$indexOf = function(v) {
	for(var i=0; i<this.length; ++i) {
		if (this[i] === v) {
			return i;
		}
	}
	return -1;
}
RegExp.prototype.$execAll = function(str) {
	var m = (this.multiline) ? 'm' : '';
	var i = (this.ignoreCase) ? 'i' : '';
    this.compile(this.source, 'g' + i + m);
    var m_all = [];
	while ((m = this.exec(str)) != null) {
        m_all.push(m);
	}
	return (!m_all.length) ? m : m_all;
}
String.prototype.$trim = function() {
	return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
};

function $preloader(list, path) {
	$preloadedPictures   = new Array();
    for (var i=0; i<list.length; i++) {
		$preloadedPictures[i]     = new Image();
		$preloadedPictures[i].src = path + list[i];
	}
	return true;
}
function $emailValidator(email) {
	var RE = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,4})/;
	return RE.test(email);
}


function $mailHideFromSpam(a) {
	try {
		var user = a.id.split('_');
		user = user[user.length - 1];
		var mail = user + '@' + a.name + '.' + a.lang;
		a.href = 'mailto:' + mail;
		a.innerHTML = a.innerHTML.replace(/\[\*mailholder\*\]/g, mail);
		if (!a.title || a.title == '') {
			a.title = mail;
		}
	} catch(e) {}
}

function $findPos(obj) {
	 var curleft = 0;
	 var curtop  = 0;

	 if (obj.offsetParent) {
	 	while (obj.offsetParent) {
	 		curleft += obj.offsetLeft;
	 		curtop  += obj.offsetTop;
	 		obj = obj.offsetParent;
	 	}
	 } else if (obj.x) {
	 	curleft += obj.x;
	 	curtop  += obj.y;
	 }

	 return {
	 	left	: curleft,
	 	top		: curtop
	 };
}

function $windowSizes() {
	var body = (document.compatMode && document.compatMode == "CSS1Compat") ? document.documentElement : document.body;
	return {
		win		: (window.innerWidth) ? {w : innerWidth, h : innerHeight} : {w : body.clientWidth, h : body.clientHeight},
		scroll	: (window.pageXOffset) ? {l : pageXOffset, t : pageYOffset} : {l : body.scrollLeft, t : body.scrollTop},
		html	: {w : body.scrollWidth, h : body.scrollHeight}
	}
}

function $gebid(id) {
	return document.getElementById(id);
}
function $gebtn(obj, name) {
	return obj.getElementsByTagName(name);
}

function $mousePos(ev) {
	var x = ev.clientX ? ev.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) : ev.pageX;
	var y = ev.clientY ? ev.clientY + (document.documentElement.scrollTop || document.body.scrollTop) : ev.pageY;
	return {x:x, y:y}
}
/* version: 1.1 */
function ModalWindow(id, isLoader) {
	// konstruktor
	if (!window.DOMEditor) {
		alert('Hiányzó osztály: DOMEditor !');
		return false;
	}
	if (!window.addEvent) {
		alert('Hiányzó globális függvény: addEvent !');
		return false;
	}
	var obj;

	/* képernyő takaró beállításai */
	if (!ModalWindow.prototype.interVeil) {
		var veil = DOMEditor.createElement('div', {id : "interVeil"});
		veil.style.position	= 'absolute';
		veil.style.zIndex	= 999;
		veil.style.left		= 0;
		veil.style.top		= 0;
		veil.style.width	= '100%';
		veil.style.display	= 'none';

		DOMEditor.append(document.body, veil);
		addEvent(window, 'resize', function() { ModalWindow.prototype.resizeVeil() });
		ModalWindow.prototype.interVeilRef = veil;
		ModalWindow.prototype.interVeil = true;
	}

	/* ablak létrehozása */
	if (ModalWindow.prototype.winIds[id]) {
		alert('Duplikált azonosító: ' + id + ' \nMinden ablaknak egyedi azonosító kell!');
		return false;
	} else {
		// ablakok közös konténere
		if (ModalWindow.prototype.firstRun) {
			var cont = DOMEditor.createElement('div', {id : "modalWindowContainer"});
			cont.style.display	= 'none';
			ModalWindow.prototype.containerRef = cont;
			(document.forms && document.forms.length > 0) ? DOMEditor.append(document.forms[0], cont) : DOMEditor.append(document.body, cont);
			ModalWindow.prototype.firstRun 	= false;
		}
		if (obj = document.getElementById(id)) {
			if (!isLoader) {
				// html-ben előre definiált ablak felhasználása
				var content = obj.innerHTML;
				obj.innerHTML = '';
				this.createWindow(obj);
				this.winRef.mw_contentArea.innerHTML = content;
				this.winRef.mw_contentArea.className += ' ' + this.winRef.className;
				this.winRef.className = 'modalWindow';
			}
		} else {
			if (isLoader) {
				obj = DOMEditor.createElement('div', {id:id});
				DOMEditor.append(obj, DOMEditor.createElement('div', {id:'mw_percent'}));
			} else {
				// üres ablak
				obj = DOMEditor.createElement('div', {
					id			: id,
					className	: 'modalWindow'
				});
				this.createWindow(obj);
			}
		}
		ModalWindow.prototype.winIds[id] = true;
		if (isLoader) {
			obj.className				= 'mw_loader';
			obj.style.display 			= 'none';
			obj.hidden 					= true;
			this.winRef 				= obj;
			this.winRef.style.position	= 'absolute';
			this.isLoader 				= true;
			DOMEditor.append(ModalWindow.prototype.containerRef, obj);
			return true;
		}
		// stíluselemek
		this.winRef.style.position					= 'absolute';
		this.winRef.mw_dragArea.style.cursor		= 'move';
		this.winRef.mw_dragArea.style.overflow		= 'hidden';
		this.winRef.mw_dragArea.style.whiteSpace	= 'nowrap';
		this.winRef.mw_dragControls.style.position	= 'absolute';
		this.winRef.mw_dragControls.style.right		= 0;
		this.winRef.mw_dragControls.style.top		= 0;
		this.winRef.mw_dragControls.style.cursor	= 'pointer';
		this.winRef.mw_resizeArea.setAttribute('style', "float: right; font-size:1px; cursor: nw-resize");
		this.winRef.mw_minimizeBtn.setAttribute('style', 'float: right');
		this.winRef.mw_closeBtn.setAttribute('style', 'float: right');

		//események
		addEvent(this.winRef, 'mousedown', this.setFocus);
		addEvent(this.winRef.mw_dragArea, 'mousedown', this.startDrag);
		addEvent(this.winRef.mw_resizeArea, 'mousedown', this.startDrag);
		addEvent(this.winRef.mw_minimizeBtn, 'click', this.minimize);
		addEvent(this.winRef.mw_closeBtn, 'click', this.hide);
	}


}

ModalWindow.prototype = {
	/* @var static */
//	bodyRef		: false,
//	ie			: false,
	firstRun	: true,
	interVeil	: false,
	interVeilRef: false,
	winIds		: {},		//Ablak azonosítók listája
	//winShowed	: 0,		//Látható ablakok száma
	index		: 1000,
	activeRef	: null,		//Jelenleg aktív ablak referenciája
	startCoords	: {},		//Induló értékek ablak mozgatásakor/átméretezésekor
	eTarget		: null,		//referencia egéreseménykor
	language	: { mini : 'Minimalizálás', restore : 'Visszaállítás', close : 'Bezárás', resize : 'Átméretezés' },
	bar			: [false],	//"taskbar", a minimalizált ablakok számontartása
	/* end */
	screen		: {sizes : {w:0, h:0}, scroll : {x:0, y:0}},
	winRef		: null,		//Referencia az ablakra
	centered	: {forced:false, x:0, y:0},		//Ablakot valamelyik irányban középre kell igazítani
	isloader	: false,

	createWindow : function(box) {
		var drag 	= DOMEditor.createElement('div', {className	: 'mw_dragArea'});
		drag.innerHTML = '[TitleHolder]';
		var control	= DOMEditor.createElement('div', {className	: 'mw_dragControls'});
		var btn1	= DOMEditor.createElement('div', {className	: 'mw_minimizeBtn', title : this.language.mini});
		var btn2	= DOMEditor.createElement('div', {className	: 'mw_closeBtn', title : this.language.close});
		control		= DOMEditor.append(control, btn2, btn1);
		drag		= DOMEditor.append(drag, control);
		var content = DOMEditor.createElement('div', {className	: 'mw_contentArea'});
		var status	= DOMEditor.createElement('div', {className	: 'mw_statusArea'});
		var resize	= DOMEditor.createElement('div', {className	: 'mw_resizeArea', title : this.language.resize});
		status		= DOMEditor.append(status, resize);
		box			= DOMEditor.append(box, drag, content, status);
		box.style.display = 'none';
		box.hidden  = true;

		// referenciák
		this.winRef 				= box;
		this.winRef.mw_dragArea 	= drag; 	//title
		this.winRef.mw_dragControls	= control;  //minimize & close
		this.winRef.mw_contentArea 	= content;
		this.winRef.mw_statusArea 	= status;
		this.winRef.mw_resizeArea 	= resize;
		this.winRef.mw_minimizeBtn 	= btn1;
		this.winRef.mw_closeBtn 	= btn2;

		DOMEditor.append(this.containerRef, box);

	},

	open 		: function(content, title, x, y, w, h, isResize, isScrollbar) {
		var contentArea = this.winRef.mw_contentArea;
		if (typeof(content) == 'object') {
			DOMEditor.removeChildren(contentArea);
			DOMEditor.append(contentArea, content);
		} else if (content && content != '') {
			contentArea.innerHTML = content;
		}
		if (title === false) {
			this.winRef.mw_dragArea.style.display = 'none';
		} else {
			this.winRef.mw_dragArea.firstChild.nodeValue = title;
		}
		if (!isResize) {
			this.winRef.mw_statusArea.style.display = 'none';
		}
		if (!isScrollbar) {
			contentArea.style.overflow   = 'hidden';
		} else {
			contentArea.style.overflow	= 'auto';
		}

		this.setSize(w, h);
		if (x == 'center' || y == 'center') {
			this.centered.forced = true;
			this.centered.x = x;
			this.centered.y = y;
		} else {
			this.move(x, y);
		}
		//this.winRef.mw_dragArea.style.height = this.winRef.mw_closeBtn.clientHeight + 'px';
		this.winRef.isResize = isResize;
		this.winRef.isScrollbar = isScrollbar;

	},

	openWithVeil : function(content, title, w, h) {
		//this.loadVeil();
		this.winRef.withVeil = true;
		this.winRef.mw_minimizeBtn.style.display = 'none';
		this.open(content, title, 'center', 'center', w, h, false, true);
	},

	openLoader : function(image) {
		var img = DOMEditor.createElement('img', {src:image});
		this.loadVeil();
		this.winRef.withVeil = true;
		DOMEditor.append(this.winRef, img);
		this.centered.forced = true;
		this.centered.x = 'center';
		this.centered.y = 'center';
		this.winRef.style.zIndex = ModalWindow.prototype.index++;
		this.show();
		ModalWindow.prototype.loader = {tID:null, ref:this, percent:document.getElementById('mw_percent')};
		GlobalProgress = {count:0, _max:0}
		ModalWindow.prototype.loader.tID = setInterval('ModalWindow.prototype.updateLoader()', 50);
	},
	updateLoader : function(closing) {
		if (closing || GlobalProgress.count == GlobalProgress._max) {
			clearInterval(this.loader.tID);
			this.loader.ref.hide(false);
		} else {
			this.loader.percent.innerHTML = 'Töltés: ' + GlobalProgress._max + '/' + GlobalProgress.count;
		}
	},

	show		: function() {
		if (!this.winRef.hidden) {
			return
		}
		this.containerRef.style.display = 'block';
		this.winRef.style.display = 'block';
		this.winRef.hidden = false;
		if (this.centered.forced) {
			this.move(this.centered.x, this.centered.y);
		}

		if (this.winRef.withVeil) {
			this.loadVeil();
			var box;
			for (var id in this.winIds) {
				box = document.getElementById(id);
				if (!box.hidden && !box.withVeil) {
					box.style.display = 'none';
					box.hideFromVeil = true;
				}
			}
		}
		if (!this.isLoader) this.setFocus(false);
	},

	hide		: function(ev) {
		var box;
		if (!ev) {
			box = this.winRef;
		} else {
			box = getObj(ev);
			while (!box.className || box.className != 'modalWindow') {
				box = box.parentNode;
			}
		}
		if (box.hidden) {
			return
		}
		box.style.display = 'none';
		box.hidden = true;
		if (box.withVeil) {
			ModalWindow.prototype.closeVeil();
			for (var id in ModalWindow.prototype.winIds) {
				box = document.getElementById(id);
				if (!box.hidden && box.hideFromVeil) {
					box.style.display = 'block';
					box.hideFromVeil = false;
				}
			}
		} else {
			if (box.mini) {
				ModalWindow.prototype.minimize(ev);
			}
		}
	},

	minimize	: function(ev) {
		var box = getObj(ev);
		while (!box.className || box.className != 'modalWindow') {
			box = box.parentNode;
		}
		if (box.mw_minimizeBtn.title == ModalWindow.prototype.language.mini) {
			// minimalizálás
			box.lastSettings = {
				left	: box.style.left,
				top		: box.style.top,
				width	: box.style.width
			};
			box.mini = true;
			box.mw_minimizeBtn.className 		= 'mw_restoreBtn';
			box.mw_minimizeBtn.title 			= ModalWindow.prototype.language.restore;
			box.mw_contentArea.style.display 	= 'none';
			box.mw_statusArea.style.display 	= 'none';
			box.style.width = '200px';
			var win = ModalWindow.prototype.getSizes();
			var scr = ModalWindow.prototype.getScroll();
			box.style.top = (win.h + scr.y - box.offsetHeight) + 'px';
			var bar = ModalWindow.prototype.bar;
			var found = false;
			for (var i=0; i<bar.length; i++) {
				if (!bar[i]) {
					bar[i] = box.id;
					found = true;
					break;
				}
			}
			if (!found) {
				i = bar.length;
				bar[i] = box.id;
			}
			ModalWindow.prototype.bar = bar;
			box.style.left = (i * 205) + 'px';
		} else {
			// visszaállítás
			var i = parseInt(box.style.left) / 205;
			if (ModalWindow.prototype.bar[i] == box.id) {
				ModalWindow.prototype.bar[i] = false;
			}

			box.style.left 	= box.lastSettings.left;
			box.style.top 	= box.lastSettings.top;
			box.style.width = box.lastSettings.width;
			box.mini = false;

			box.mw_minimizeBtn.className 		= 'mw_minimizeBtn';
			box.mw_minimizeBtn.title 			= ModalWindow.prototype.language.mini;
			box.mw_contentArea.style.display 	= 'block';
			if (box.isResize) {
				box.mw_statusArea.style.display 	= 'block';
			}
		}
	},

	// ablak poziccionálása (szám vagy "center")
	move		: function(x, y) {
		this.getScreen();
		if (x == 'center') {
			this.winRef.style.left = (this.screen.scroll.x + Math.round((this.screen.sizes.w - this.winRef.offsetWidth) / 2)) + 'px';
		} else {
			this.winRef.style.left = (this.screen.scroll.x + parseInt(x)) + "px";
		}
		if (y == 'center') {
			this.winRef.style.top = (this.screen.scroll.y + Math.round((this.screen.sizes.h - this.winRef.offsetHeight) / 2)) + 'px';
		} else {
			this.winRef.style.top = (this.screen.scroll.y + parseInt(y)) + "px";
		}
	},

	// ablak mozgatása egérrel
	moveTo		: function(x, y) {
		var scroll = this.getScroll();
		x = (this.startCoords.winX +  parseInt(x) + (scroll.x - this.startCoords.scrollLeft));
		y = (this.startCoords.winY +  parseInt(y) + (scroll.y - this.startCoords.scrollTop));
		if (x < 0) {
			x = 0;
		}
		if (y < 0) {
			y = 0;
		}

		this.eTarget.parentNode.style.left = x + "px";
		this.eTarget.parentNode.style.top  = y + "px";
	},

	// ablak átméretezése, ha nulla, akkor automatikus
	setSize		: function(w, h) {
		if (w > 0) {
			w = w + 'px';
		} else {
			w = 'auto';
		}
		if (h > 0) {
			h = h + 'px';
		} else {
			h = 'auto';
		}
		this.winRef.style.width = w;
		this.winRef.mw_contentArea.style.height = h;
	},

	// ablak előtérbehozása
	setFocus	: function(ev) {
		var box;
		if (!ev) {
			//objektumon belüli hívás
			box = this.winRef;
		} else {
			//egéreseményből hívás
			box = getObj(ev);
			while (!box.className || box.className != 'modalWindow') {
				box = box.parentNode;
			}
		}
		if (!ModalWindow.prototype.activeRef || ModalWindow.prototype.activeRef.id != box.id) {
			if (ModalWindow.prototype.activeRef) {
				// az inaktív ablakok címsora halványabb lesz
				var preBox = ModalWindow.prototype.activeRef.mw_dragArea;
				preBox.style.filter = 'alpha(opacity=70)';
				preBox.style.opacity= '0.7';
			}

			box.style.zIndex = ModalWindow.prototype.index++;
			ModalWindow.prototype.activeRef = box;

			box = box.mw_dragArea;
			box.style.filter = '';
			box.style.opacity= '1';
		}
	},

	startDrag	: function(ev) {
		ModalWindow.prototype.setFocus(ev);
		var target = getObj(ev);
		var box = target;
		while (!box.className || box.className != 'modalWindow') {
			box = box.parentNode;
		}

		var scroll = ModalWindow.prototype.getScroll();

		ModalWindow.prototype.startCoords = {
			mouseX 		: ev.clientX,
			mouseY 		: ev.clientY,
			winX   		: parseInt(box.offsetLeft),
			winY   		: parseInt(box.offsetTop),
			winW   		: parseInt(box.offsetWidth),
			winH   		: 0,
			scrollLeft	: scroll.x,
			scrollTop	: scroll.y
		}
		if (target.className == 'mw_dragArea') {
			// az ablak mozgatása
			box.style.opacity= '0.7';
			box.mw_dragControls.style.filter = "alpha(opacity=70)";
			box.style.filter = "alpha(opacity=70)";

			var i = parseInt(box.style.left) / 205;
			if (ModalWindow.prototype.bar[i] == box.id) {
				ModalWindow.prototype.bar[i] = false;
			}
		} else if (target.className == 'mw_resizeArea') {
			// az ablak átméretezése húzással
			ModalWindow.prototype.startCoords.winH = parseInt(box.mw_contentArea.offsetHeight);
		} else {
			return killEvent(ev);
		}

		// az egér mozgásának figyelése
		ModalWindow.prototype.eTarget = target;
		addEvent(document, 'mousemove', ModalWindow.prototype.getDistance);
		addEvent(document, 'mouseup', ModalWindow.prototype.stopDrag);
		return killEvent(ev);
	},

	setLanguage	: function(mini, restore, close, resize) {
		var box;
		for(var id in this.winIds) {
			if (this.winIds[id]) {
				box = document.getElementById(id);
				box.mw_minimizeBtn.title	=	(box.mw_minimizeBtn.title == this.language.mini) ? mini : restore;
				box.mw_closeBtn.title		=	close;
				box.mw_resizeArea.title		=	resize;
			}
		}
		ModalWindow.prototype.language = { mini : mini, restore : restore, close : close, resize : resize };
	},

	stopDrag	: function(ev) {
		ModalWindow.prototype.eTarget.parentNode.style.filter = '';
		ModalWindow.prototype.eTarget.parentNode.style.opacity= '1';
		ModalWindow.prototype.eTarget = null;
		removeEvent(document, 'mousemove', ModalWindow.prototype.getDistance);
		removeEvent(document, 'mouseup', ModalWindow.prototype.stopDrag);
	},

	// az egér elmozdulásának mérése
	getDistance	: function(ev) {
		ev = ev || (ev = window.event);
		var target = ModalWindow.prototype.eTarget;
		var distanceX = ev.clientX - ModalWindow.prototype.startCoords.mouseX;
		var distanceY = ev.clientY - ModalWindow.prototype.startCoords.mouseY;
		if (target.className == 'mw_dragArea') {
			// ablak mozgatása
			ModalWindow.prototype.moveTo(distanceX, distanceY);
		} else {
			// ablak átméretezése
			ModalWindow.prototype.resize(distanceX, distanceY);
		}
		return killEvent(ev);
	},

	resize		: function(w, h) {
		this.eTarget.parentNode.parentNode.style.width  = Math.max(this.startCoords.winW + w, 150) + "px";
		this.eTarget.parentNode.parentNode.mw_contentArea.style.height = Math.max(this.startCoords.winH + h, 100) + "px";
	},

	/* háttér betakarása */
	loadVeil 	: function() {
		var win = this.getWinSizes();
		this.interVeilRef.style.height	= win.h + "px";
		this.interVeilRef.style.display	= "block";
	},

	/* takarás újrarajzolása ha a böngészőt átméretezik */
	resizeVeil	: function() {
		if (this.interVeil && this.interVeilRef.style.display == "block") {
			this.loadVeil();
		}
	},

	/* háttér takarás megszüntetése */
	closeVeil	: function() {
		this.interVeilRef.style.display = "none";
	},

	getSizes	: function() {
		var myWidth = 0, myHeight = 0;
		 if ( typeof( window.innerWidth ) == 'number' ) {
			//Non-IE
			myWidth = window.innerWidth;
			myHeight = window.innerHeight;
		} else if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			//IE 6+ in 'standards compliant mode'
			myWidth = document.documentElement.clientWidth;
			myHeight = document.documentElement.clientHeight;
		} else if ( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			//IE 4 compatible
			myWidth = document.body.clientWidth;
			myHeight = document.body.clientHeight;
		}
		return { w:myWidth, h:myHeight };
	},

	getWinSizes	: function() {
		var w = 0, h = 0;
		var d = (document.compatMode=="CSS1Compat") ? document.documentElement : document.body;
		var test1 = d.scrollHeight;
		var test2 = d.offsetHeight
		if (test1 > test2) {// all but Explorer Mac
			w = d.scrollWidth;
			h = d.scrollHeight;
		} else { // Explorer Mac; would also work in Explorer 6 Strict, Mozilla and Safari
			w = d.offsetWidth;
			h = d.offsetHeight;
		}
		return { w:w, h:h };
	},

	getScroll	: function() {
		var scrOfX = 0, scrOfY = 0;
		if ( typeof( window.pageYOffset ) == 'number' ) {
			//Netscape compliant
			scrOfY = window.pageYOffset;
			scrOfX = window.pageXOffset;
		} else if ( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
			//DOM compliant
			scrOfY = document.body.scrollTop;
			scrOfX = document.body.scrollLeft;
		} else if ( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
			//IE6 standards compliant mode
			scrOfY = document.documentElement.scrollTop;
			scrOfX = document.documentElement.scrollLeft;
		}
		return { x:scrOfX, y:scrOfY };
	},

	getScreen	: function() {
		this.screen.sizes = this.getSizes();
		this.screen.scroll = this.getScroll();
	}



}

// todo 3 -c BUG :window resizenál nem rakja középre (modal)
// todo 3 -c BUG :modal ablaknál scrollozáskor az ablak is scrollozódik, nem marad középen
// TODO 4:árnyék az ablakoknak
// TODO 3:ablakok a "taskbar"-ban mindig legyenek szemelőtt

