/*

	Copyright (c) 2008 Efficenter Kft. http://efficenter.hu/

		Kódolásban fasza gyerekek vagyunk. Te is? Csatlakozz hozzánk!
		Ha vágod az alábbiakat: PHP, mysql, javascript, bash script,
		MySQL, XHTML, CSS, alapvető Linux rendszergazdai ismeretek
		és otthon vagy weblapok tervezésében, profi programozásban,
		nagy terheltségű weblapok fejlesztésében (Smarty és más
		gyerekjátékok kizárva) illetve szeretsz napi 10-12 órában dolgozni
		akkor gyere hozzánk! A benedek@efficenter.hu címre küld el a
		linkedin profilod címe mellett azokat a projecteket vagy trükköket,
		amikre szakmailag büszke vagy és egy legalább ezer, de maximum
		háromezer karakteres írást "Szemantikus web" címmel, ami a
		személyes meglátásaidat	tartalmazza a témában!

	Some parts also:
		Copyright (c) 2006 Wish Internet Consulting http://wish.hu
		Copyright (c) 2006-2008 Blogter Kft. http://blogter.hu

	Also used:
		MD4 Javascript library
			(c) 1998 - 2008 Paul Johnston http://pajhome.org.uk/crypt/md5/
			distributed under the BSD License
		Prototype Javascript framework
			(c) 2006-2007 Prototype Core Team http://www.prototypejs.org/
			distributed under the MIT License
		script.aculo.us
			(c) 2005, 2006 Thomas Fuchs http://script.aculo.us
			distributed under the MIT License
		TrimPath Template
			(c) 2004, 2005 Steve Yen http://trimpath.com/
			distributed under the Apache License (v. 2.0)
		JavaScript tooltip library
			(c) 2006 Jonathan Weiss http://blog.innerewut.de/tooltip
			distributed under the BSD License
		Ajile (Advanced JavaScript  Importing & Loading Extension)
			(c) 2003-2008 Michael A. I. Lee, iSkitz.com http://ajile.iskitz.com/
			distributed under the Mozilla Public License Version 1.1

	The Apache Licese can be found at http://www.apache.org/licenses/LICENSE-2.0
	The MIT License can be found at http://www.opensource.org/licenses/mit-license.php
	The GPL License can be found at http://www.gnu.org/copyleft/gpl.html
	The MPL License can be found at http://www.mozilla.org/MPL/

	This is a copyrighted application. All rights reserved.
	You're not allowed to reverse engineer, reuse or modify
	any part of it, except where the particular licence says else.

	Open source libraries or parts created or modified in this project
	can be found at http://gpl.efficenter.hu/

		"Szeretném megköszönni apukámnak és anyukámnak és küldöm
		mindenkinek, aki szereti!"

				Benedek

*/
var user;
var storage;
var layout;
var cookies;
var tooltip;
var bubblebox;
var widgets = {};
var apps = {};
var dologloaded = false;
var fullloaded = false;
var tboxnum = 0;
var maxitemdisplay = 100;
var aktivtab = 0;
var topment = 0;
var olvasatlanok = {};

var iehackstr = '';
if (navigator.userAgent.toLowerCase().indexOf("msie")>0) {
	iehackstr = ' &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'; // Ne kérdezzétek...
}





function replaceall (str, rep, nc) {
			// nemigaz, hogy erre nekem kell fgt írnom... primitív szar dolog ez a javascript
	while (str.indexOf(rep)>0)
		str = str.replace(rep, nc);
	return str;
}

function rand (mins, maxs) {
			// á la php
	var e= mins + Math.floor(Math.random()*(maxs-mins+1));
	if (e>maxs) { e=maxs; }
	if (e<mins) { e=mins; }
	return e;
}
var Tooltip = Class.create();
Tooltip.prototype = {
	initialize: function() {
	},

	positionTooltip: function(event, item){
		var e = this.e;
		if (!e) { this.e = e = $('tooltip'); }
		var dimensions = Element.getDimensions( e );
		var tooltip_x = Event.pointerX(event);
		var tooltip_y = Event.pointerY(event);
		var tooltip_width = dimensions.width;
		var tooltip_height = dimensions.height;
		var delta_x = 0-dimensions.width/3;
		var delta_y = dimensions.height/2+22;
		var item_width = 0;
		var item_height = 0;
		var inner_width = document.body.clientWidth || window.innerWidth;
		var inner_height = document.body.clientHeight || window.innerHeight;
		var position = 'top';
		Event.stop(event);

		if (item) {
			var pos = Position.cumulativeOffset(item);
			tooltip_x = pos[0];
			tooltip_y = pos[1];
			delta_x = 0;
			delta_y = 0;
			item_width = item.offsetWidth;
			item_height = item.offsetHeight/2;
		}

		if (tooltip_width + tooltip_x + item_width + delta_x >= inner_width-5 || tooltip_x + delta_x <= 5) {

			if (tooltip_width + tooltip_x + item_width + delta_x >= inner_width-5) {
				tooltip_x = inner_width - tooltip_width - 5;
			} else {
				tooltip_x = 5;
			}

		} else {
			tooltip_x = tooltip_x + delta_x + item_width;
		}

		tooltip_y = tooltip_y - tooltip_height / 2 + delta_y + item_height;
		e.className = position;
		try {
			e.style.top = tooltip_y + 'px';
			e.style.left = tooltip_x + 'px';
		}
		catch(err) {
		}
	},

	showTooltip: function(event, message, item, l){
		if (message == '') return;
		if (!l) { l = 238; }
		var tooltip = $('tooltip');
		if (message.length > l+2) { message = message.substring(0, l) + '...'; }
		$('tooltip-content').innerHTML = message;
		tooltip.style.display = 'block';
		this.positionTooltip(event, $(item));
		if (!item) document.onmousemove = this.positionTooltip;
	},

	hideTooltip: function(event){
		var tooltip = $('tooltip');
		tooltip.style.display = 'none';
		document.onmousemove = null;
	}

}

Object.extend(Event, {
	_domReady : function() {
		if (arguments.callee.done) return;
		arguments.callee.done = true;

		if (this._timer)  clearInterval(this._timer);

		Event._readyCallbacks.each(function(f) { f() });
		Event._readyCallbacks = null;
	},
	onDOMReady : function(f) {
		if (!this._readyCallbacks) {
			var domReady = this._domReady.bind(this);

			if (document.addEventListener)
				document.addEventListener("DOMContentLoaded", domReady, false);

			// Image preload
			if (document.addEventListener)
				document.addEventListener("DOMContentLoaded", preloadimagessdf, false);
				
			document.documentElement.scrollTop = 0; // Indulásnál legyen felül...

			// Tüntessük el a cumót, ha betöltődik... whatatrükkössrácvagyok
			Event.observe(window, 'load', function () {
				if (dologloaded==true) {
					$('loadingw').style.display='none';
					$('loadingwb').style.display='none';
					fullloaded = true;
				} else {
					new PeriodicalExecuter(function(pe) {
						if (dologloaded==true) {
							$('loadingw').style.display='none';
							$('loadingwb').style.display='none';
							fullloaded = true;
							pe.stop();
						}
					}, 0.5);
				}
			});

			// Őszintén szólva a következő pár sort én se értem
			// de nálam okosabb emberek szerint (igen, ilyenek léteznek)
			// ezt így kell és meglepő módon működik

			/*@cc_on @*/
			/*@if (@_win32)
					document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
					document.getElementById("__ie_onload").onreadystatechange = function() {
							if (this.readyState == "complete") domReady();
					};
			/*@end @*/

			if (/WebKit/i.test(navigator.userAgent)) {
				this._timer = setInterval(function() {
					if (/loaded|complete/.test(document.readyState)) domReady();
				}, 10);
			}

			Event.observe(window, 'load', domReady);
			Event._readyCallbacks =  [];
		}
		Event._readyCallbacks.push(f);
	}
});

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/, ''); };

Function.prototype.andThen = function(g) {
	var f = this;
	return function() {
		f(); g();
	};
};

function fixDroppables() {
	window.Position.withinVertically = function(element, x, y) {
		if (this.includeScrollOffsets)
			return this.withinIncludingScrolloffsets(element, x, y);
		this.xcomp = x;
		this.ycomp = y;
		this.offset = this.cumulativeOffset(element);

		return (x >= this.offset[0] && x <  this.offset[0] + element.offsetWidth);
	};

	window.Droppables.isAffectedVertically = function(point, element, drop) {
		return (
			(drop.element!=element) &&
			((!drop._containers) ||
				this.isContained(element, drop)) &&
			((!drop.accept) ||
				(Element.classNames(element).detect(
					function(v) { return drop.accept.include(v); } ) )) &&
			Position.withinVertically(drop.element, point[0], point[1]) );
	};

	window.Droppables.show = function(point, element) {
		if(!this.drops.length) { return; }
		var affected = [];

		point = Position.cumulativeOffset(element);
		point[0] += element.offsetWidth/2;

		if(this.last_active) { this.deactivate(this.last_active); }
		this.drops.each( function(drop) {
			if (drop.element.nodeName=='UL' && Droppables.isAffectedVertically(point, element, drop)) { affected.push(drop); }
			if (drop.element.nodeName=='LI' && Droppables.isAffected(point, element, drop)) { affected.push(drop); }
		});

		if(affected.length>0) {

			drop = Droppables.findDeepestChild(affected);
			Position.within(drop.element, point[0], point[1]);
			if(drop.onHover) {
				drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
			}

			Droppables.activate(drop);

			point = Position.cumulativeOffset(element);
			margin = 5;
			var p = [ parseInt(Element.getStyle(element,'left') || '0', 10),
								parseInt(Element.getStyle(element,'top') || '0', 10)];
			$('dropindicator').style.left = point[0] - p[0] + margin + 'px';
			$('dropindicator').style.top = point[1] - p[1] + margin + 'px';
			$('dropindicator').style.width = element.offsetWidth - (2*margin+6) + 'px';
			$('dropindicator').style.height = element.offsetHeight - (2*margin+6) + 'px';
			$('dropindicator').style.display = 'block';
		}
	};
}

var User = Class.create();
User.prototype = {

	initialize: function() {
		this.id = '';
		this.getId();
	},

	getId: function() {
		if (cookies.get('session')) {
			this.id = cookies.get('session');
		} else {
			this.setId(this.generateId());
		}
	},

	setId: function(id) {
			this.id = id;
			cookies.set("session", id);
	},

	generateId: function () {
			// ezt csak sessionnél használjuk... amúgy MD4-elünk valamiből
		var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
		var strlen = 64;
		var letters = [];
		for (var i=0; i<strlen; i++) {
			var rnum = Math.floor(Math.random() * chars.length);
			letters.push(chars.substr(rnum,1));
		}
		return letters.join('');
	},

	logout: function() {
		this.username = 'guest'; // Primitív bunkó állatok vagyunk
		this.id = cookies.get('oldsession');
		cookies.set("oldsession", null);
		cookies.set("session", this.generateId());
		cookies.set("username", this.username);
		document.location = document.location;
		this.draw();
	},

	login: function(session, username) {
		cookies.set("oldsession", this.id);
		cookies.set("session", session);
		cookies.set("username", username);
		this.id = session;
		this.username = username;
		document.location = document.location; // ne kérdezzétek...
		this.draw();
	},

	loginResponse: function(response) {
		// progress.remove('loading');
		eval("var r = " + response.responseText);
		if (r.error) {
			alert(r.error); // gyakrabban kéne kivinni az sqlt sétálni, mert folyton maga alá szarik
		} else {
			this.login(r.session, r.username);
			hidedpage();
		}
	},

	registerResponse: function(response) {
		eval("var r = " + response.responseText);
		if (r.error) {
			alert(r.error);
		} else {
			alert(r.ok);
			this.username = r.username;
			this.login(this.id, r.username);
			this.draw();
		}
		hidedpage();
	},

	draw: function() {
		if (this.username || this.username == 'guest') {
			$('header-login').innerHTML = 'Bejelentkezés / Regisztráció';
			$('header-login').onclick = function() { DisplayPage('http://www.hirfigyelo.hu/inline_login.php', 'Bejelentkezés / Regisztráció', '760px', '450px', '50px', '#fff', 'http://www.hirfigyelo.hu/js/includes/login.js'); }
		} else {
			$('header-login').innerHTML = 'Kijelentkezés';
			$('header-login').onclick = function() { User.prototype.logout(); }
		}
	}

};

var Storage = Class.create();
Storage.prototype = {
	initialize: function() {
		this.saving = 0;
		this.data = {};
		this.data.layout = {};
		this.timer = null;
		this.buffer = [];
	},

	load: function(name, handler) {
		new Ajax.Request(
			'getData.php', { method: 'post', postBody: 'name='+name, onComplete: handler }
		);
		// Ez a függvény korábban bonyolult volt, de praktikusnak éreztem
		// 450 sorról egyre redukálni... :)
	},

	save: function(name, value) {
			// Na ez a módszer szexibb mint egy tucat playmate,
			// ahogy Helly Kittys bugyiban Battlestar Galacticát néz
		this.buffer.unshift({name: name, value: value !== null ? value.toJSON() : null});
		if (this.timer) { window.clearTimeout(this.timer); }
		this.timer = window.setTimeout( this.groupsave.bind(this), 1500 );
	},

	groupsave: function() {
		if (++this.saving == 1) {
			if (this.buffer.length > 0) {
				var data = [];
				while (this.buffer.length > 0) {
					data.push(this.buffer.pop());
				}
				new Ajax.Request(
					'setData.php', { method: 'post', postBody: 'data='+encodeURIComponent(data.toJSON())+'&rand='+Math.random(), onComplete: this.finished, onFailure: this.finished2 });
			}
		}
		this.saving--;
	},

	// Felesleges callbackek
	finished: function() {
	},

	finished2: function() {
	}

};

var Layout = Class.create();
Layout.prototype = {

	initialize: function() {
		this.dragdrop = [];
		this.columns = [];
		this.keyHandlers = [];
		storage.load('', this.initialize_2);
		this.templates = {}
		Event.observe(document, 'keydown', this.keyDown);
	},

	initialize_2: function(response) {
		// Bring it on!

		// mentett adatok
		if (response.responseText != 'null') {
			eval("storage.data = " + response.responseText);

		// alapbeállítás
		} else {
			// Ez a függvény azért kell, hogy az üzemeltetést
			// végző diplomás, jól fizetett egységsugarú
			// programozók, akikkel dolgoznom kellett legalább
			// az alapbeállításokat meg tudják változtatni anélkül,
			// hogy az több hetes leállással járna...
			// (nem, még így se fogják tudni...)
			alapbeallitasbetoltese();
			storage.save('', storage.data);
		}

		// title
		if (!document.oldtitle) { document.oldtitle = document.title; }
		document.title = storage.data.layout.title + ' - ' + document.oldtitle;
		$('header-page-title-text').innerHTML = storage.data.layout.title;

		var boxes = [];
		for(box in storage.data.boxes) {
			var boxo = storage.data.boxes[box];
			if (box.match(/^box\d+$/)) {
				boxes.push({id: box, row: boxo.row});
			}
		}

		for(var i=0; i<boxes.length; i++) {
			for(var j=i+1; j<boxes.length; j++) {
				if ( boxes[i].column > boxes[j].column ||
						(boxes[i].column == boxes[j].column && boxes[i].row > boxes[j].row) ) {
					var tmp = boxes[i];
					boxes[i] = boxes[j];
					boxes[j] = tmp;
				}
			}
		}

		var tabs = storage.data.layout.tabs;

		var container = $('container-static');
		var columns = 3;
		var columnWidth = Math.floor(100 / columns * 100) / 100;
		var width = 0;
		var containment = [];
		var k = 0;
		// Na... Ez az a pont, ahol OS-től, böngészőktől és a
		// dobozok számától függően a rendszer a haldoklás tüneteit
		// kezdi mutatni...

		// agyonterhelünk mindent mint az állat
		// [Erre rímelő klasszikus CPG sor]

		for (var t = 0; t < tabs.length; t++) { if (tabs[t].id != 'static') {
			var tab = tabs[t];
			layout.newTab(tab.id, tab.title, true);
			for (var i = 0; i < boxes.length; i++) {
				if (storage.data.boxes[boxes[i].id].column>=(100+tab.id)*10 && storage.data.boxes[boxes[i].id].column<=(100+tab.id)*10+9 &&
						storage.data.boxes[boxes[i].id].id &&
						storage.data.boxes[boxes[i].id].type) {
					k++;
					new Box(storage.data.boxes[boxes[i].id]);
				}
			}
			layout.initDragDrop(100+tab.id);
		}}

		layout.pageSwitch.call($('header-tabs-0'));

		// Betöltődéscsekkoló géniuszom éber...
		new PeriodicalExecuter(function(pe) { $('loadingw').style.display='none'; $('loadingwb').style.display='none'; fullloaded=true; pe.stop(); }, 6);

		dologloaded = true;
	},

	newTab: function(tabId, title, nochange) {
		if ($('header-tabs-'+tabId)) { return; }
		if (!title) { title = 'Új fül'; }
		var newtab = document.createElement('li');
		newtab.id = 'header-tabs-'+tabId;
		var span = document.createElement('span');
		span.innerHTML = '&nbsp;';
		newtab.appendChild(span);
		var b = document.createElement('b');
		b.innerHTML = title;
		newtab.appendChild(b);
		var input = document.createElement('input');
		input.type="text";
		newtab.appendChild(input);
		var em = document.createElement('em');
		em.innerHTML = ' ';
		newtab.appendChild(em);
		$$('#header .tabs ul')[0].appendChild(newtab);
		newtab.onclick = layout.pageSwitch;
		layout.newContainer(100+tabId);
		if (!nochange) {
			layout.initDragDrop(100+tabId);
			layout.pageSwitch.call($('header-tabs-'+tabId));
		}
		var tabs = storage.data.layout.tabs;
		var found = -1;
		for (var t = 0; t < tabs.length; t++) {
			if (tabs[t].id == tabId) { found = t; }
		}
		if (found<0) {tabs.push({
				id: tabId, title: title
		})}
		$('container-'+(100+tabId)).addClassName('page-container-ures');
		$('container-'+(100+tabId)).addClassName('page-container');
		storage.save('layout.tabs', storage.data.layout.tabs);
		return(newtab);
	},

	newContainer: function(tabId) {
		// Pakoljuk a konténereket
		if ($('container-'+tabId)) { return; }
		var container = document.createElement('div');
		container.className = 'page-container';
		container.id = 'container-'+tabId;
		var containment = [];
		var columns = storage.data.layout.columns;
		var columnWidth = Math.floor(100 / columns * 100) / 100;
		var width = 0;
		for (var i = 0; i < columns; i++) {
			var col = document.createElement('UL');
			col.id = 'column-' + (tabId*10 + i);
			layout.columns[tabId*10 + i] = col;
			containment.push(col.id);
			col.className = 'column';
			if (i==columns-1) {
				col.className += ' column-last';
			}
			col.style.width = columnWidth + '%';
			col.style.height = '1px';
			container.appendChild(col);
			width += columnWidth;
			columnWidth = Math.floor((100-width) / (columns-i-1) * 100) / 100 - 0.01;
		}
		$('tabs-containers').appendChild(container);
		return containment;
	},

	initDragDrop: function(prefix) {
		if (prefix == 'static') { prefix = 10; }
		var columns = storage.data.layout.columns;

		for (var i = 0; i < columns; i++) {
			if (this.dragdrop[i]) {
				this.dragdrop[i].destroy();
			}
		}

		var containment = [];
		for (var i = 0; i < columns; i++) {
			containment.push('column-'+ prefix + i);
		}
		for (var i = 0; i < columns; i++) {
			this.dragdrop[i] = Sortable.create('column-'+ prefix + i, {
				dropOnEmpty: true,
				constraint: false,
				containment: containment,
				reverteffect: function(element) {
					element.style.top  = 0;
					element.style.left = 0;
					$('dropindicator').style.display = 'none';
				},
				onUpdate: function() {
					for(var i=0, num=this.element.childNodes.length; i<num; i++) {
						var box = BoxCommon.getBox(this.element.childNodes[i].id.replace(/^box_|-columnitem$/g, ''));
						box.column = this.element.id.replace(/^column-/,'');
						box.row = i;
						storage.save('boxes.box'+box.id+'.column', box.column);
						storage.save('boxes.box'+box.id+'.row', box.row);
					}
				}
			});
		}
	},

	keyDown: function(e) {
		if (!e && window.event) { e = window.event; }
		if (e && e.srcElement) { // ie
			var keycode = e.keyCode;
			var element = e.srcElement;
		} else { // mozilla
			var keycode = e.which;
			var element = e.target;
		}
		if (element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') { return; }
		layout.keyHandlers.each(function(item){
			if (keycode==item.code) { item.handler(); }
		});
	},

	keyAddHandler: function(code, handler) {
		this.keyHandlers.push({code: code, handler: handler});
	},

	keyRemoveHandler: function(code, handler) {
		this.keyHandlers = this.keyHandlers.findAll(
			function(item) {
				return item.handler != handler;
			}
		);
	},

	updateLayout: function() {
	},

	modalShow: function() {
		var modal = $('modal');
		modal.style.display = 'block';
		var scrolltop = 0;
		if (typeof(document.documentElement.scrollTop)=="number") {
			scrolltop = document.documentElement.scrollTop;
		} else if (typeof(document.body.scrollTop)=="number") {
			scrolltop = document.body.scrollTop;
		} else if (typeof(window.pageYOffset)=="number") {
			scrolltop = window.pageYOffset;
		}
		if (scrolltop < 1) {
			scroll(0,0); // god, I love Safari (not)
		}
		
		
		modal.style.top = scrolltop  + 'px';
				
		topment = scrolltop;
		if (document.body.currentStyle) {
				this.html_position   = document.documentElement.currentStyle.position;
				this.html_overflow_x = document.documentElement.currentStyle.overflowX;
				this.html_overflow_y = document.documentElement.currentStyle.overflowY;
				this.body_position   = document.body.currentStyle.position;
				this.body_overflow_x = document.body.currentStyle.overflowX;
				this.body_overflow_y = document.body.currentStyle.overflowY;
				document.documentElement.style.overflow = 'hidden';
			} else {
				this.html_position   = document.defaultView.getComputedStyle(document.documentElement,null).getPropertyValue('position');
				this.html_overflow_x = document.defaultView.getComputedStyle(document.documentElement,null).getPropertyValue('overflow-x');
				this.html_overflow_y = document.defaultView.getComputedStyle(document.documentElement,null).getPropertyValue('overflow-y');
				this.body_position   = document.defaultView.getComputedStyle(document.body,null).getPropertyValue('position');
				this.body_overflow_x = document.defaultView.getComputedStyle(document.body,null).getPropertyValue('overflow-x');
				this.body_overflow_y = document.defaultView.getComputedStyle(document.body,null).getPropertyValue('overflow-y');
				document.body.style.overflow = 'hidden';
				document.body.style.overflow = 'hidden';
			}
		document.documentElement.scrollTop = scrolltop;
		document.documentElement.style.position = 'absolute';
		document.documentElement.style.height = '100%';
		document.documentElement.style.width = '100%';
		document.body.overflowY = 'scroll';
		document.body.style.position = 'absolute';
		document.body.style.height = '100%';
		document.body.style.width = '100%';
		$('modal').style.height = '100%';
		$('modal').style.width = document.body.clientWidth; // IE6 Bugfix... fogalmam sincs, mi a baja a 100%-al

	},

	modalHide: function() {
		$('modal').style.display = 'none';
		document.body.style.overflowX = layout.body_overflow_x;
		document.body.style.overflowY = layout.body_overflow_y;
		document.documentElement.style.overflowX = layout.html_overflow_x;
		document.documentElement.style.overflowY = layout.html_overflow_y;
	},

	addBox: function(column, position, box) {
		$('container-'+(Math.floor(column/10))).removeClassName('page-container-ures');
		var colitem = document.createElement('LI');
		box.element = colitem;
		colitem.id= 'box_' + box.id + '-columnitem';
		colitem.className = 'box-columnitem';
		layout.columns[column].appendChild(colitem);
		var bc = document.createElement("div");
		bc.id = "box_"+box.id;
		if (box.data.isstatic) {
			bc.className = "box box-static"
		} else {
			bc.className = "box"
		}

		var bch = document.createElement("div");
		bch.className = "box-header";
		bch.id = "box_"+box.id+"-header";
		bch.onmouseover = layout.boxHoverOn;
		bch.onmouseout  = layout.boxHoverOff;

		var bchi = document.createElement("span");
		bchi.className = "icon";
		bchi.id = "box_"+box.id+"-icon";
		bchi.style.backgroundImage = "url("+box.icon+")";
		bch.appendChild(bchi);

		var bchc = document.createElement("span");
		bchc.className = "controls";
		bchc.id = "box_"+box.id+"-controls";

		for (var i=0; i<box.controls.length; i++) {
			var bchcc = document.createElement("span");
			bchcc.className = "control";
			var bchcci;
			if (box.controls[i].icon == '') {
				bchcci = document.createElement("span");
				var bchccic = document.createTextNode(box.controls[i].name);
				bchcci.appendChild(bchccic);
			} else {
				bchcci = document.createElement("img");
				bchcci.src = box.controls[i].icon;
				bchcci.alt = box.controls[i].name;
				bchcci.title = box.controls[i].name;
			}
			bchcci.id = "box_"+box.id+"-control-"+box.controls[i].name;
			bchcci.onclick = box.controls[i].action;
			bchcc.appendChild(bchcci);
			bchc.appendChild(bchcc);
		}
		bch.appendChild(bchc);

		var bcht = document.createElement("div");
		bcht.className = "box-title";
		bcht.id = "box_"+box.id+"-title";
		var bchtc = document.createTextNode(box.title);
		bcht.appendChild(bchtc);
		bch.appendChild(bcht);

		bc.appendChild(bch);

		var bce = document.createElement("div");
		bce.className = "box-edit";
		bce.id = "box_"+box.id+"-edit";
		bc.appendChild(bce);

		var bcc = document.createElement("div");
		bcc.className = "box-content";
		bcc.id = "box_"+box.id+"-content";
		if (!typeof(box.data.open)=='undefined' && !box.data.open) {
			bcc.style.display = "none";
		}
		bc.appendChild(bcc);

		colitem.appendChild(bc);

		tboxnum++;

		// Ha épp töltjük be az oldalt és több, mint 10 dobozunk van,
		//akkor inkább csak másodpercenként maximum 10-et töltsünk be,
		// nehogy megöljük a böngészőt... ami azért így is elég sanszos

		if (tboxnum>10 && fullloaded==false ) {
			//window.setTimeout(box.init(), 100);
			new PeriodicalExecuter(function(pe) {
				box.init();
				pe.stop();
			}, ((tboxnum/10)-0.5));
		} else {
			box.init();
		}

	},

	removeBox: function(box) {
		// Az IE kompatibilitás csupa élmény 's kacagás...
		if (typeof(box) == "object") {
			var element = box;
			var no = true;
			var nok;
			while (no==true) {
				if (typeof(element.parentNode.id)=="string") {
					nok = element.parentNode.id;
				}
				if (nok.substr(0, 6)=='column' && no==true) {
					no = false;
				} else {
					element = element.parentNode;
				}
			}

			if (element.id!='body') {
				element.style.display = "none";
				element.parentNode.removeChild(element);
				delete element;
				// if only forgetting were
				// this easy for me

				/* assert "it's going to be okay"; */
			}
		}

	},

	setTitle: function(id, title) {
		$('box_' + id + '-title').innerHTML = title+iehackstr;
		// yo chokito!
	},

	setEdit: function(id, content) {
		$('box_' + id + '-edit').innerHTML = content;
	},

	setContent: function(id, content) {
		$('box_' + id + '-content').innerHTML = content;
	},

	boxHoverOn: function() {
		var element = this;
		while (element != document.body && !Element.hasClassName(element, 'box')) { element = element.parentNode; }
		if (element != document.body) {
			Element.addClassName(element, 'box-hover');
		}
	},

	boxHoverOff: function(event) {
		var element = this;
		while (element != document.body && !Element.hasClassName(element, 'box')) { element = element.parentNode; }
		if (element != document.body) {
			Element.removeClassName(element, 'box-hover');
		}
	},

	itemHoverOn: function(event) {
		if (!event) { return; }
		var element = Event.element(event);
		Element.addClassName(element, 'item-hover');
		if (Element.hasClassName(element, 'current'))
			Element.addClassName(element, 'current-hover');
	},

	itemHoverOff: function(event) {
		if (!event) { return; }
		var element = Event.element(event);
		Element.removeClassName(element, 'item-hover');
		Element.removeClassName(element, 'current-hover');
	},

	pageSwitch: function() {
		var clicked = this;
		var tabs = $$('#header .tabs li');
		$('hovermenutab').style.display="none";
		for (var i = 0; i < tabs.length; i++) {
			var tab = tabs[i];
			var tid = tab.id.replace(/^header-tabs-/,'');
			tid = '10'+tid;
			if (tab.id == clicked.id) {
				tab.addClassName('active');
				$('container-'+tid).style.display='block';
				$('container-'+tid).style.border = '1px solid #fff';
				layout.currentTab = tid -100;
				aktivtab = i;
			} else {
				tab.removeClassName('active');
				$('container-'+tid).style.display='none';
				$(tab.id).onclick = layout.pageSwitch;

			}
		}

		$('header-tabs-'+layout.currentTab).onclick=function() {
			var tabs = $$('#header .tabs li');
			var tab = tabs[aktivtab];
			if ($('hovermenutab').style.display=="none") {
				var tidx = tab.id.replace(/^header-tabs-/,'');
				var tabtitle = tab.getElementsByTagName('b')[0].innerHTML;
				var c = "<img onclick=\"$('hovermenutab').style.display= 'none';\" class=\"klikkelheto\" align=\"right\" src=\"/static/reader_close_btn.gif\">";
				c += "<ul>";
				c += "<li onclick=\"$('hovermenutab').style.display= 'none'; DisplayPage('http://www.hirfigyelo.hu/hozzaad.php', 'Tartalom hozzáadása', '760px', '450px', '50px', '#fff', 'http://www.hirfigyelo.hu/js/includes/addcontent.js');\"><img src=\"http://www.hirfigyelo.hu/static/plus.gif\"> Új tartalom</li>";
				c += "<li onclick=\"tabmindetkinyit('"+tidx+"')\"><img src=\"http://www.hirfigyelo.hu/static/open.gif\"> Mindet kinyit</li>";
				c += "<li onclick=\"tabmindetbezar('"+tidx+"')\"><img src=\"http://www.hirfigyelo.hu/static/close.gif\"> Mindet bezár</li>";
				c += "<li onclick=\"tabatnevez('"+tidx+"')\"><img src=\"http://www.hirfigyelo.hu/static/document.gif\"> Átnevez</li>";
				c += "<li onclick=\"tabtorol('"+tidx+"')\"><img src=\"http://www.hirfigyelo.hu/static/remove.gif\"> Töröl</li>";
				c += "</ul>";
				$('hovermenutab').innerHTML = c;
				$('hovermenutab').style.left = GetX($('header-tabs-'+tidx))+"px";
				$('hovermenutab').style.display= "block";
				disph = true;
			} else {
				$('hovermenutab').style.display="none";
			}
		}
		
		gtrack('tabvaltas/'+layout.currentTab);
	}

};

var BoxCommon = {
	boxes: [],
	serial: 1000,
	getSerial: function() {
		return(BoxCommon.serial++);
	},
	getBox: function(id) {
		return BoxCommon.boxes.detect(function(item){return item.id==id;});
	}
};
var Box = Class.create();
Box.prototype = {

	initialize: function(init) {
		var newbox = false;
		if (!init.id) {
			init.id = BoxCommon.getSerial();
			this.open = true;
			newbox = true;
		} else {
			if (BoxCommon.serial <= init.id) {
				BoxCommon.serial = init.id + 1;
			}
		}
		this.id = init.id;
		this.icon = 'static/icon-working.gif';
		this.title = init.title || 'noname box';
		this.controls = [];
		if (this.open==false) {
			this.controls.push({ icon: 'static/open.gif', name: 'kibe', action: this.boxOpenClose });
		} else {
			this.controls.push({ icon: 'static/close.gif', name: 'kibe', action: this.boxOpenClose });
		}
		this.controls.push({ icon: 'static/remove.gif', name: 'Bezár', action: this.boxRemove });
		this.content = 'box content';
		this.data = init;
		if (typeof this.open == 'undefined') { this.open = true; }
		this.init = function(){};
		switch (init.type) {
			case 'rss':
				DefineBoxRSS(this);
				break;

			case 'wgt':
				DefineBoxWidget(this);
				break;
			case 'swgt': // Ideiglenes megoldás TODO
				DefineBoxSWidget(this);
				break;
		}
		layout.addBox(init.column, rand(0,2), this); // Mindig a legszélére rakja TODO

		BoxCommon.boxes.push(this);
		if (newbox) {
			storage.data.boxes['box'+this.id] = this.data;
			storage.save('boxes.box'+this.id, this.data);
			layout.initDragDrop(layout.currentTab == 'static' ? layout.currentTab : layout.currentTab+100);
		}

	},

	updateIcon: function() {
		$('box_'+this.id+'-icon').style.backgroundImage = 'url('+escape(this.icon)+')';
	},

	editShowHide: function(box) {
		if ($('box_' + box.id + '-edit').style.display == 'block') {
			$('box_' + box.id + '-edit').style.display = 'none';
		} else {
			$('box_' + box.id + '-edit').style.display = 'block';
		}
	},

	boxRemove: function() {
		if (!this || !this.id || typeof(this.id)!="string") { return; }
		var id = this.id.replace(/[^0-9]+/g, '');
		//var remurl = storage.data.boxes['box'+id].data.source;
		if (storage.data.boxes['box'+id].type=="rss") {
			olvasatlanok[id] = 0;
			storage.data.boxes['box'+id].readed = '111111111111111';
			// Micsoda triki-trüki
		}
		storage.save('boxes.box'+id, null);
		layout.removeBox(this);
		
		//gtrack('removebox/'+remurl);
		// murderers!!
	},

	boxOpenClose: function(state) {
		var id = this.id; if (typeof id != 'number') { id = this.id.replace(/[^0-9]+/g, ''); }
		var box = apps.RSSReader.current = BoxCommon.getBox(id);
		if (typeof state != 'boolean') { state = !($('box_' + id + '-content').style.display != 'none'); }
		if (state) {
			var content = $('box_' + id + '-content');
			if (content) { content.style.display = 'block'; }
			$('box_' + id + '-control-kibe').src="/static/close.gif";
			box.open = true;
		} else {
			var content = $('box_' + id + '-content');
			if (content) { content.style.display = 'none'; }
			$('box_' + id + '-control-kibe').src="/static/open.gif";
			var edit = $('box_' + id + '-edit');
			if (edit) { edit.style.display = 'none'; }
			box.open = false;
		}
		storage.save('boxes.box'+id+'.open', box.open);
	},

	boxOpenCloseAll: function(state) {
		BoxCommon.boxes.each(function(box){
			box.boxOpenClose.call(box, state);
		});
	}

};

function DefineBoxRSS(box) {

	box.load = function() {
	var ncim = box.data.source;
		// A felesleges izék a címből repülnek a kukába
	if (ncim.indexOf('?')>0) {
		ncim = ncim.substr(0, ncim.indexOf('?'));
	}
	if (ncim.indexOf('index.php')>0) {
		ncim = ncim.substr(0, ncim.indexOf('index.php'));
	}
	if (ncim.indexOf('.php')>0) {
		ncim = ncim.substr(0, ncim.indexOf('.php'));
	}
	if (ncim.indexOf('rss/')>0) {
		ncim = ncim.substr(0, ncim.indexOf('rss/'));
	}
	if (ncim.indexOf('rss')>0) {
		ncim = ncim.substr(0, ncim.indexOf('rss'));
	}
	if (ncim.indexOf('feed')>0) {
		ncim = ncim.substr(0, ncim.indexOf('feed'));
	}
	if (ncim.indexOf('feed/')>0) {
		ncim = ncim.substr(0, ncim.indexOf('feed/'));
	}
	if (ncim.length > 40) {
		ncim = ncim.substr(0, 35)+"...";
	}

	$('box_' + box.id + '-title').innerHTML = '<em>'+ncim+'</em>'+iehackstr;
		// yo chokito!
		new Ajax.Request(
			'readRSS.php',
			{
				method: 'get',
				parameters: 'rssURL=' + escape(box.data.source) + '&elso=true&rand=' + Math.random(),
				onComplete: function(request){
					//alert ('complete'+request.responseText);
					box.onload(request, box, true);
				},
				onFailure: function(){  }
			}
		);
		if (!layout.templates.rssbox_edit) layout.templates.rssbox_edit = TrimPath.parseDOMTemplate('t_rssbox_edit');
		$('box_' + box.id + '-edit').innerHTML = layout.templates.rssbox_edit.process({box: box, data: box.data});
		Event.observe($('box_' + box.id + '-edit-source-save'), 'click', function(){box.dataSourceSave(box)});
		Event.observe($('box_' + box.id + '-edit-maxitems-save'), 'click', function(){box.dataMaxitemsSave(box)});
		Event.observe($('box_' + box.id + '-edit-refresh-save'), 'click', function(){box.dataRefreshSave(box)});
	};

	box.refresh = function(param) {
		// maybe next time baby
		if (typeof($('box_'+box.id+'-icon'))!="object") return;
		$('box_'+box.id+'-icon').style.backgroundImage = 'url(/static/icon-working.gif)';

		new Ajax.Request(
			'readRSS.php',
			{
				method: 'get',
				parameters: 'rssURL=' + escape(box.data.source) + (param?'&'+param+'=true':'') + '&rand=' + Math.random(),
				onComplete: function(request){
					box.onload(request, box, false);
				},
				onFailure: function(){  }
			}
		);
	};

	box.onload = function(response, box, initialload) {
		// mutimeg
		eval("data = " + response.responseText);
		box.rssdata = data;
		var favico = data.link;
		var pos = favico.lastIndexOf("/");
		if (pos > 6) {
			favico = favico.substr(0, pos);
		}
		favico += '/favicon.ico';
		box.icon =favico;

		$('box_'+box.id+'-icon').style.backgroundImage = 'url(http://www.hirfigyelo.hu/iconcache.php?'+escape(box.icon)+')';

		if (data.items[0]) {
			var idx = 0;
			var elozo = box.data.readed;

			while (idx<data.items.length && typeof(data.items[idx])=="object" && data.items[idx].link != box.data.readedFirst) {
				box.data.readed = '0' + box.data.readed;
				idx++;
			}
			while (box.data.readed.length < box.rssdata.items.length) {
				box.data.readed+='1';
			}
			if (box.data.readed.length > box.rssdata.items.length) {
				// Na ide sztem nem kell semmi...
				box.data.readed = box.data.readed.substr(0,box.rssdata.items.length)
			}
			box.data.readedFirst = data.items[0].link;
			if (elozo != box.data.readed) {
				storage.save('boxes.box'+box.id+'.readed', box.data.readed);
				storage.save('boxes.box'+box.id+'.readedFirst', box.data.readedFirst);
			}
		}
		box.draw(box);
		if (initialload) {
			//window.setTimeout(box.draw, rand(100, 2000));
		}
	};

	box.draw = function(box) {
		var ncim = box.rssdata.title;
		if (ncim.length<1) {
			ncim = box.data.source;
			if (ncim.indexOf('?')>0) {
				ncim = ncim.substr(0, ncim.indexOf('?'));
			}
			if (ncim.indexOf('index.php')>0) {
				ncim = ncim.substr(0, ncim.indexOf('index.php'));
			}
			if (ncim.indexOf('.php')>0) {
				ncim = ncim.substr(0, ncim.indexOf('.php'));
			}
			if (ncim.indexOf('rss/')>0) {
				ncim = ncim.substr(0, ncim.indexOf('rss/'));
			}
			if (ncim.indexOf('rss')>0) {
				ncim = ncim.substr(0, ncim.indexOf('rss'));
			}
			if (ncim.indexOf('feed')>0) {
				ncim = ncim.substr(0, ncim.indexOf('feed'));
			}
			if (ncim.indexOf('feed/')>0) {
				ncim = ncim.substr(0, ncim.indexOf('feed/'));
			}
			if (ncim.length > 40) {
				ncim = ncim.substr(0, 35)+"...";
			}
			ncim = '<em style="color:red; font-weight:normal;">'+ncim+'</em>';
		}
		$('box_' + box.id + '-title').innerHTML = ncim+iehackstr;
		// yo chokito
		if (!layout.templates.rssbox) layout.templates.rssbox = TrimPath.parseDOMTemplate('t_rssbox');
		$('box_' + box.id + '-content').innerHTML = layout.templates.rssbox.process({box: box, data: box.rssdata});
		//alert(box.rssdata.items.length);
		box.rssdata.items.each(function(item){
			element = $('box_'+box.id+'-item-'+item.no);
			if (typeof(element)=="object") { // nem biztos, hogy látszik az item limit miatt
				Event.observe(element, 'mouseover', function(event) {
					var title = '<strong>'+item.title+'</strong>';
					var message = item.description.replace(/<br\s*\/?>/g, ' ').replace(/<.*?>/g, '');
					tooltip.showTooltip.call(tooltip, event, title+'<br />'+message);
				;$('box_'+box.id+'-icon').style.backgroundImage = 'url(/iconcache.php?'+escape(box.icon)+')';
				});
				Event.observe(element, 'mouseout', tooltip.hideTooltip );
				Event.observe(element, 'click', function(e) {
					apps.RSSReader.show(box.id, item.no);
					tooltip.hideTooltip();
				});
			}
		});
		var olvt = 0;
		
		for (var j=0; j<box.data.readed.length; j++) {
			if (box.data.readed.substr(j,1) == 0) {
				olvt++;
			}
		}
		olvasatlanok[box.id] = olvt;
		window.clearTimeout(box.timer);
		box.data.refresh = 15; // whata genius am i
		box.timer = window.setTimeout(box.refresh, 1000*rand(500, 1200)); // 15-20 percenként keressen újat
	};

	box.dataSourceSave = function(box) {
		// ... and they actions will be remembered by the sessions of the upcoming generations
		box.editShowHide(box);
		box.data.source = $('box_' + box.id + '-edit-source-value').value;
		storage.save('boxes.box'+box.id+".source", box.data.source);
		box.refresh();
	}

	box.dataMaxitemsSave = function(box) {
		box.editShowHide(box);
		box.data.maxitems = Math.floor( $('box_' + box.id + '-edit-maxitems-value').value );
		storage.save('boxes.box'+box.id+".maxitems", box.data.maxitems);
		box.draw(box);
	}

	box.dataRefreshSave = function(box) {
		box.editShowHide(box);
		box.data.refresh = Math.floor( $('box_' + box.id + '-edit-refresh-value').value );
		if (box.data.refresh < 1) { box.data.refresh = 1; }
		$('box_' + box.id + '-edit-refresh-value').value = box.data.refresh;
		storage.save('boxes.box'+box.id+".refresh", box.data.refresh);
		box.refresh();
	}

	box.setReaded = function(box, item, state, quick) {
		// Ez az IE bugok miatt ilyen gáz, ti. az IE időnként
		// elszámolja a tömb elemeinek a számát.
		var i = 0;
		while (typeof(box.rssdata.items[i])=="object") {
			i++;
		}

		while (i<box.rssdata.items.length) {
			box.rssdata.items.pop();
		}

		var elozo = box.data.readed;
		while (box.data.readed.length < box.rssdata.items.length) {
			box.data.readed+='1';
		}
		if (box.data.readed.length > box.rssdata.items.length) {
			// Na ide sztem nem kell semmi...
			box.data.readed = box.data.readed.substr(0,box.rssdata.items.length)
		}
		while (box.data.readed.length-1<item) {
			box.data.readed += '0';
		}
		box.data.readed = box.data.readed.substr(0,item) + (state?'1':'0') + box.data.readed.substr(item+1);
		box.draw(box);
		if (elozo != box.data.readed) {
			storage.save('boxes.box'+box.id+'.readed', box.data.readed);
			storage.save('boxes.box'+box.id+'.readedFirst', box.data.readedFirst);
		}
	}

	box.getReaded = function(box, item) {
		// deprecated
	}

	box.init = box.load;
	box.title = box.data.source;

	box.data.refresh =  15;
	box.data.maxitems =  10;
	box.data.readed = box.data.readed || '';
	box.data.readedFirst = box.data.readedFirst || '';

	box.controls.unshift( { icon: 'static/back-forth.gif', name: 'Frissít', action: function(){box.refresh()} } );
	//box.controls.unshift( { icon: 'static/icon-edit.png', name: 'szerk.', action: function() { box.editShowHide(box) } } );
	// who the fuck cares about user opinion.

}

function DefineBoxWidget(box) {
	box.load = function() {
		widgets[box.iframeid] = box.id;

		if (box.url.indexOf('?')<0) {
			box.fullurl = box.url+'?hf_sid='+box.iframeid+'&hf_uid='+box.userid;
		} else {
			box.fullurl = box.url+'&hf_sid='+box.iframeid+'&hf_uid='+box.userid;
		}
		layout.setTitle(box.id, '');
		$('box_'+box.id+'-icon').style.backgroundImage = 'url(/static/icon-working.gif)';
		$('box_' + box.id + '-content').innerHTML = '<iframe width="100%" height="1" src="'+box.fullurl+'" class="widget_iframe" id="'+box.iframeid+'"></iframe>';
		$('box_' + box.id + '-content').style.margin="0 1px 1px 0";
		$('box_' + box.id + '-content').style.padding="0";
	};

	box.refresh = function() {

		if (box.url.indexOf('?')<0) {
			box.fullurl = box.url+'?hf_sid='+box.iframeid+'&hf_uid='+box.userid;
		} else {
			box.fullurl = box.url+'&hf_sid='+box.iframeid+'&hf_uid='+box.userid;
		}
		layout.setTitle(box.id, box.url);
		$('box_'+box.id+'-icon').style.backgroundImage = 'url(/static/icon-working.gif)';
		$('box_' + box.id + '-content').innerHTML = '<iframe width="100%" height="1" src="'+box.fullurl+'" class="widget_iframe" id="'+box.iframeid+'"></iframe>';
		$('box_' + box.id + '-content').style.margin="0 1px 1px 0";
		$('box_' + box.id + '-content').style.padding="0";
	};

	box.url = box.data.source;
	box.iframeid = 'W'+Math.floor(Math.random()*1000000);
	box.userid = 'U'+hex_md4(box.url+user.id);
	// Az md4 miatt én kérek elnézést...
	box.init = box.load;
	box.icon = 'static/icon-box.png';
	box.title = box.data.source+iehackstr;

	box.controls.unshift( { icon: 'static/back-forth.gif', name: 'Újratölt', action: function(){ box.refresh(); } } );

}


function DefineBoxSWidget(box) {
	box.load = function() {	
		layout.setTitle(box.id, '');
		$('box_'+box.id+'-icon').style.backgroundImage = 'url(/static/icon-working.gif)';

		try { // IE
		  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		} catch(e) { // Normális böngészők
				xmlDoc=document.implementation.createDocument("","",null);
		}
		try {
			xmlDoc.async=false;
			xmlDoc.load(box.data.source);
			var xmlobject = xmlDoc;
		
			var widget = xmlobject.getElementsByTagName('widget')[0];
			var body = widget.getElementsByTagName('content')[0].getElementsByTagName('body')[0];
			box.title = body.getElementsByTagName('title')[0].firstChild.nodeValue;
		
			layout.setTitle(box.id, box.title);
			box.icon = body.getElementsByTagName('icon')[0].firstChild.nodeValue;
			$('box_'+box.id+'-icon').style.backgroundImage = 'url('+box.icon+')';
			$('box_' + box.id + '-content').innerHTML = body.getElementsByTagName('content')[0].firstChild.nodeValue;
		} catch(e) {
			box.title  = '<em style="color:red; font-weight:normal;">'+box.title+'</em> '+iehackstr;
		}
	};

	box.refresh = function() {
		box.load();
	};

	box.url = box.data.source;
	box.init = box.load;
	box.icon = 'static/icon-box.png';
	box.title = box.data.source+iehackstr; // TODO

	box.controls.unshift( { icon: 'static/back-forth.gif', name: 'Újratölt', action: function(){ box.refresh(); } } );

}


apps.RSSReader = {
	// Na ez az érdekes rész
	current: null,
	lastno: -1,
	ritems: Array(),
	gktab: 0,
	gurtab:0,
	basicshow: function(ktab, urtab) {
		// Megnyitjuk
		apps.RSSReader.gktab = ktab;
		apps.RSSReader.gurtab = urtab;
		if ($('modal').style.display != "block") {
			layout.modalShow();
		}
		if ($('rssreader').style.display != 'block') {
			$('rssreader').style.display = 'block';
			$('rssreader').style.top = document.documentElement.scrollTop + 20 + 'px';
			$('rssreader').style.height = document.documentElement.offsetHeight - 40 + 'px';
			$('rssreader').style.width = document.documentElement.offsetWidth - 60 + 'px';
		}
		
		var contentwidth = Element.getDimensions('rssreader-content').width;

		layout.keyRemoveHandler(27, apps.RSSReader.hide);     // ESC
		layout.keyRemoveHandler(38, apps.RSSReader.previous); // UP
		layout.keyRemoveHandler(37, apps.RSSReader.previous); // LEFT
		layout.keyRemoveHandler(39, apps.RSSReader.next);     // RIGHT
		layout.keyRemoveHandler(32, apps.RSSReader.next);     // RIGHT
		layout.keyRemoveHandler(40, apps.RSSReader.next);     // DOWN
		layout.keyAddHandler(27, apps.RSSReader.hide);     // ESC

		Event.observe($('rssreader-close'), 'click', apps.RSSReader.hide);
		$('rssreader-list').innerHTML = '';
		$('rssreader-content-text').innerHTML = '';
		
		if (ktab=='start') {
			// Csak simán elindítjuk
			apps.RSSReader.displayMSG(getszoveg('rsskezdolap')); // Külön fájlból, mert az jó
			
			maxitemdisplay = 100;
				// Kell egy max, mert elég nagy a gépigénye a dolognak, ezért limitáljuk
				// úgy, hogy a felhasználónak a lehető legkevesebb problémát okozza
			$('rssreader-title').innerHTML = '<ul><li class="passive"><div class="passive">Hírolvasó</div></li></ul>';
			var tabs = storage.data.layout.tabs;
			if (tabs.length < 2) {
				// Ha csak egy tabunk van, nem szórakozunk azok listázásával
				apps.RSSReader.basicshow(tabs[0].id);
				return;
			}
			var vm = '<ul>';
			vm += '<li id="rssreader-list-ur" class="unreaded mark"><img src="/static/reader_star_icon.gif" />Olvasatlan</li>';
			for (var t = 0; t < tabs.length; t++) {
				vm += '<li id="rssreader-list-'+tabs[t].id+'" class="unreaded"><img src="/static/reader_folder_icon.gif" />'+tabs[t].title+'</li>';
			}
			vm += '</ul>';
			$('rssreader-list').innerHTML = vm;

			element = $('rssreader-list-ur');
			Event.observe(element, 'click', function(e) { apps.RSSReader.basicshow('unread', false); });

			tabs.each(function(item){
				element = $('rssreader-list-'+item.id);
				Event.observe(element, 'click', function(e) { apps.RSSReader.basicshow(item.id, false); });
			});

		}
		if (ktab=='unread') {
			// Ha az olvasatlaokat keressük
			rtab = urtab-1; // hülye javascript néha keveri a NULL-t a 0-lal... Ezért a hack
			layout.keyAddHandler(38, apps.RSSReader.previous); // UP
			layout.keyAddHandler(37, apps.RSSReader.previous); // LEFT
			layout.keyAddHandler(39, apps.RSSReader.next);     // RIGHT
			layout.keyAddHandler(40, apps.RSSReader.next);     // DOWN
			layout.keyAddHandler(32, apps.RSSReader.next);     // Space

			if (urtab==false) {
				// Ha az összes olvasatlanra van szükség
				$('rssreader-title').innerHTML = '<ul><li class="cactive kp"><div class="cactive kattinthato" onclick="apps.RSSReader.basicshow(\'start\', false);">Hírolvasó</div></li><li class="passive"><div class="passive">Olvasatlanok</div></li></ul>';
			} else {
				// Ha csak egy tabról keressük
				$('rssreader-title').innerHTML = '<ul><li class="cactive"><div class="kattinthato cactive" onclick="apps.RSSReader.basicshow(\'start\', false);">Hírolvasó</div></li><li class="cactive kp"><div class="cactive kattinthato" onclick="apps.RSSReader.basicshow('+rtab+');">'+getTabTitleFromID(rtab)+'</div></li><li class="passive"><div class="passive">Olvasatlanok</div></li></ul>';
			}

			var boxes = [];
			for(box in storage.data.boxes) {
				// Na ez egy szép if lesz, hogy eldöntsük az
				// object az egy olvasatlan elem-e vagy sem.
				if (
					box.match(/^box\d+$/) &&
					typeof(storage.data.boxes[box])=="object" &&
					storage.data.boxes[box].id &&
					storage.data.boxes[box].type=='rss' &&
					storage.data.boxes[box].readed.indexOf('0')>=0
					&&
					(
						(
							urtab==false
						) || (
							urtab !=false &&
							storage.data.boxes[box].column>=(100+rtab)*10 &&
							storage.data.boxes[box].column<=(100+rtab)*10+9
						)
					)
				) {
					boxes.push(box);
				}
			}
			var k = 0;
			var tadded = 0;
			apps.RSSReader.ritems = Array();
			var vegleges = new Array;
			var elso = new Array;
			var vm = "";
			var marallasreadstr = '';
			for (var i = 0; i < boxes.length; i++) {
				// Lássuk a medvét
				var bid = storage.data.boxes[boxes[i]].id;
				var boxxx = BoxCommon.getBox(bid);
				if (typeof(boxxx.rssdata)=="object") {
					for (j in boxxx.rssdata.items) {
						if (storage.data.boxes[boxes[i]].readed.substr(j, 1)!='1' && typeof(boxxx.rssdata.items[j])=="object" && typeof(boxxx.rssdata.items[j].title)=="string") {
							k++;
							if (k<=maxitemdisplay) {
								// tényleg meg akarjuk jeleníteni...
								tadded++;
								var x = new Array;
								x['id'] = boxes[i];
								x['j'] = j;
								x['k'] = k;
								vegleges.push(x);
								apps.RSSReader.ritems[k] = Array(boxes[i], j);
								vm += '<li id="rssreader-list-'+k+'" class="unreaded"><img src="'+getBoxIcon(bid)+'" />'+boxxx.rssdata.items[j].title+'</li>';
								if (k==1) {
									elso = x;
								}
								if (marallasreadstr=='') {
									marallasreadstr = '<li id="rssreader-list-marallasread" class="mark"><img src="/static/markasread.gif" /><strong>Mindet megjelöl olvasottnak</strong></li>';
								}
							}
						}
					}
				}
			}

			if (k<1) {
				if (urtab == false) {
					apps.RSSReader.basicshow('start', false);
				} else {
					apps.RSSReader.basicshow(rtab);
				}
					apps.RSSReader.displayMSG(szovegek['nincsolvasatlan']);
				return;
			}

			var vantovabb = false;
			if (k>maxitemdisplay) {
				vm += '<li id="rssreader-list-tovabb" class="topmark"><img src="/static/plus.gif" /><strong>További elemek</strong> (még '+ (k-maxitemdisplay) +')</li>';
				vantovabb = true;
			}
			vm+='</ul>';
			$('rssreader-list').innerHTML = '<ul>'+marallasreadstr+vm;
			if (vantovabb == true) {
				element = $('rssreader-list-tovabb');
				Event.observe(element, 'click', function(e) {
					maxitemdisplay += 100;
					apps.RSSReader.basicshow(ktab, urtab);
					var current = apps.RSSReader.lastno;
					var t = apps.RSSReader.ritems[current];
					if (!t) { return; }
					apps.RSSReader.showSItem(t[0], t[1], current);
				});
			}

			if (marallasreadstr != '') { // Ha nem minden elem jelent meg.
				element = $('rssreader-list-marallasread');
				Event.observe(element, 'click', function(e) {
					var elozodoboz ='';
					var current = null;
					for (var i=1; i<=tadded; i++) {
						var t = apps.RSSReader.ritems[i];
						current = BoxCommon.getBox(t[0].substring(3,7));
						current.setReaded(current, t[1], true, true);
						if (elozodoboz != t[0] && i>1) { current.draw(current); }
						elozodoboz = t[0];
					}
					if (current) { current.draw(current); }
					apps.RSSReader.basicshow(ktab, urtab);
				});
			}

			vegleges.each(function(item){
				// Feldolgozzuk az egyes elemeket
				element = $('rssreader-list-'+item.k);
				Event.observe(element, 'click', function(e) {
				apps.RSSReader.showSItem(item.id, item.j, item.k); });
			});

			if (elso['id']) { // Jelenítsük meg az elsőt.
				apps.RSSReader.showSItem(elso['id'], elso['j'], elso['k']);
			}

		}

		if (ktab !='unread' && ktab!='start') {
			// Egy dobozra vagyunk kíváncsiak
			$('rssreader-title').innerHTML = '<ul><li class="cactive kp"><div class="cactive kattinthato" onclick="apps.RSSReader.basicshow(\'start\', false);"><span class="szovegtarto">Hírolvasó</span></div></li><li class="passive"><div class="passive">'+getTabTitleFromID(ktab)+'</div></li></ul>';
			var dobozok = getRSSBoxesForTab(ktab);
			var vm = '<ul>';
			vm += '<li id="rssreader-list-ur" class="unreaded mark"><img src="/static/reader_star_icon.gif" />Olvasatlan</li>';

			var dobozr = [];

			for (var t = 0; t < dobozok.length; t++) {
				var doboz = dobozok[t];
				var cim = getBoxTitle(doboz.id);
				if (typeof(cim)=="string" && cim.length>0 && cim.indexOf('<em')<0) {
					dobozr.push(doboz);
					vm += '<li id="rssreader-list-'+doboz.id+'" class="unreaded"><img src="'+getBoxIcon(doboz.id)+'" />'+cim+'</li>';
				}
			}
			vm += '</ul>';
			$('rssreader-list').innerHTML = vm;

			element = $('rssreader-list-ur');
			Event.observe(element, 'click', function(e) { apps.RSSReader.basicshow('unread', ++ktab); });

			dobozr.each(function(item){
				element = $('rssreader-list-'+item.id);
				Event.observe(element, 'click', function(e) { apps.RSSReader.show(item.id, 0); });
			});
		}
		if ($('rssreader-content-text').innerHTML == '') {
			apps.RSSReader.displayMSG(getszoveg('rsskezdolap'));
		}
		gtrack('rssolvaso/'+ktab+'/'+urtab);
	},

	show: function(id, no) {
		// Egy adott elemre kattintott
		var box = apps.RSSReader.current = BoxCommon.getBox(id);
		if ($('modal').style.display != "block") {
			layout.modalShow();
		}
		if ($('rssreader').style.display != 'block') {
			$('rssreader').style.display = 'block';
			$('rssreader').style.top = document.documentElement.scrollTop + 20 + 'px';
			$('rssreader').style.height = document.documentElement.offsetHeight - 40 + 'px';
		}
		var contentwidth = Element.getDimensions('rssreader-content').width;
		layout.keyAddHandler(27, apps.RSSReader.hide);     // ESC
		layout.keyAddHandler(38, apps.RSSReader.previous); // UP
		layout.keyAddHandler(37, apps.RSSReader.previous); // LEFT
		layout.keyAddHandler(39, apps.RSSReader.next);     // RIGHT
		layout.keyAddHandler(40, apps.RSSReader.next);     // DOWN
		layout.keyAddHandler(32, apps.RSSReader.next);     // Space
		Event.observe($('rssreader-close'), 'click', apps.RSSReader.hide);

		var ktab = getParentTab(id);

		$('rssreader-title').innerHTML = '<ul><li class="cactive"><div class="cactive kattinthato" onclick="apps.RSSReader.basicshow(\'start\');">Hírolvasó</div></li><li class="cactive kp"><div class="cactive kattinthato" onclick="apps.RSSReader.basicshow('+ktab+');">'+getTabTitleFromID(ktab) +'</div></li><li class="passive"><div class="passive">'+box.rssdata.title+'</div></li></ul>';

		if (!layout.templates.rssreader_list) layout.templates.rssreader_list = TrimPath.parseDOMTemplate('t_rssreader_list');
		box.rssdata.icon = getBoxIcon(id);
		$('rssreader-list').innerHTML = layout.templates.rssreader_list.process({box: box, data: box.rssdata});
		apps.RSSReader.ritems = Array();

		var i = 0;

		// IE bugfix. Nem tudja megszámolni egy tömb elemeit mert szutyok szar.
		while (typeof(box.rssdata.items[i])=="object") {
			i++;
		}

		while (i<box.rssdata.items.length) {
			box.rssdata.items.pop();
		}

		box.rssdata.items.each(function(item){
				apps.RSSReader.ritems.push(Array('box'+id, item.no));
				element = $('rssreader-list-'+item.no);
				Event.observe(element, 'click', function(e) { apps.RSSReader.showSItem('box'+id, item.no, item.no); });
		});
		apps.RSSReader.showSItem('box'+id, no, no);
	},

	displayMSG: function (szoveg) {
		// Szöveget tesz a központi területre.
		$('rssreader-content-text').innerHTML = szoveg;
	},

	showSItem: function(boxid, boxnum, wnum) {
	
		// Egy adott elemet mutat meg. Bármilyen szituációban.
		// (Irreálisan összetett lett... kedvem lenne előlről
		// újraírni az egészet csak emiatt...)
		var current = BoxCommon.getBox(boxid.substring(3,7));
		var no = wnum-1;
		var lastno = apps.RSSReader.lastno;
		var content = $('rssreader-content-text');

		var html = [];
		if (lastno>=0) {
			Element.removeClassName($('rssreader-list-'+lastno), 'current');
			Element.removeClassName($('rssreader-list-'+lastno), 'current-hover');
		}
		current.setReaded(current, boxnum, true);

		var nok = no+1;
		apps.RSSReader.lastno = nok;
		$('rssreader-list-'+nok).removeClassName('unreaded');
		$('rssreader-list-'+nok).addClassName('readed');
		html.push('<div class="title"><a href="',current.rssdata.items[boxnum].link,'">',current.rssdata.items[boxnum].title,'</a></div>');
		// html.push('<div class="bookmark"><img src="static/book-green-mark.png" /></div>'); // TODO
		if (current.rssdata.items[boxnum].date != '1970-01-01 01:00:00' && current.rssdata.items[boxnum].date != '')
			html.push('<div class="date">',current.rssdata.items[boxnum].date,'</div>');

		html.push('<div class="body">',current.rssdata.items[boxnum].description,'</div>');
		
		html.push('<hr class="vegeszep" />');
		html.push('<div id="contenttovabb"><a href="'+current.rssdata.items[boxnum].link+'" target="_blank">Tovább a weblapra</a>  &raquo;</div>')
		
		if (current.rssdata.items[boxnum].author != '')
			html.push('<div class="author">Szerző: ',current.rssdata.items[boxnum].author,'</div>');
		if (current.rssdata.items[boxnum].category != '')
			html.push('<div class="category">Címkék: ',current.rssdata.items[boxnum].category,'</div>');

		html.push('<div id="vege"></div>');
		content.innerHTML = html.join('');
		// Minden link targetje legyen "_blank"
		var x = content.getElementsByTagName('a');
		for (var i=0; i<x.length; i++) { x[i].target = '_blank'; }

		Element.addClassName($('rssreader-list-'+nok), 'current');
		apps.RSSReader.lastno = nok;
		gtrack('show/s/'+current.rssdata.items[boxnum].link);
	},

	previous: function() { // Előző... szintén irreálisan összetett
		var current = apps.RSSReader.lastno - 1;
		if (!$('rssreader-list-'+current)) { return; }
		var t = apps.RSSReader.ritems[current];
		if (!t) { return; }
		apps.RSSReader.showSItem(t[0], t[1], current);
		apps.RSSReader.current = current;
		apps.RSSReader.gorget();

	},

	next: function() { // Előző... pláne irreálisan összetett
		var current = apps.RSSReader.lastno + 1;
		if (!$('rssreader-list-'+current)) {
			if ($('rssreader-list-tovabb')) {
				maxitemdisplay += 100;
				apps.RSSReader.basicshow(apps.RSSReader.gktab, apps.RSSReader.gurtab);
			} else {
				return;
			}
			
		} 
		var t = apps.RSSReader.ritems[current];
		if (!t) { return; }
		apps.RSSReader.showSItem(t[0], t[1], current);
		apps.RSSReader.current = current;
		apps.RSSReader.gorget();

	},
	hide: function() {
		// Bezárjuk az olvasót... NEEEE
		apps.RSSReader.lastno = -1;
		apps.RSSReader.current = null;
		$('rssreader').style.display = 'none';
		layout.modalHide();
		layout.keyRemoveHandler(27, apps.RSSReader.hide);     // ESC
		layout.keyRemoveHandler(38, apps.RSSReader.previous); // UP
		layout.keyRemoveHandler(37, apps.RSSReader.previous); // LEFT
		layout.keyRemoveHandler(39, apps.RSSReader.next);     // RIGHT
		layout.keyRemoveHandler(40, apps.RSSReader.next);     // DOWN
		layout.keyRemoveHandler(32, apps.RSSReader.next);     // Space
		//Event.stopObserving($('rssreader-notepad'), 'change');
		window.clearTimeout(apps.RSSReader.timer);
		gtrack('rssolvasobezar/');
	},
	gorget: function() {
		var despos = findPosY($('rssreader-list-'+apps.RSSReader.current)) - 200;
		if (despos<0) { despos = 0; }
		$('rssreader-list').scrollTop = despos;
	}

}

apps.ImageView = {
	// Most éppen deprecated, de később lesz még comebackje ;)
	boxid: null,
	lastno: -1,
	max: 0,

	show: function(id, no) {
		var box = BoxCommon.getBox(id);
		apps.ImageView.boxid = id;
		apps.ImageView.lastno = no;
		apps.ImageView.max = box.rssdata.items.length;
		$('imageview-previous').className = (no == 0) ? 'disabled' : '';
		$('imageview-next').className = (no < box.rssdata.items.length - 1) ? '' : 'disabled';
		layout.modalShow();
		$('imageview').style.display = 'block';
		layout.keyAddHandler(27, apps.ImageView.hide);     // ESC
		layout.keyAddHandler(38, apps.ImageView.previous); // UP
		layout.keyAddHandler(37, apps.ImageView.previous); // LEFT
		layout.keyAddHandler(39, apps.ImageView.next);     // RIGHT
		layout.keyAddHandler(40, apps.ImageView.next);     // DOWN
		Event.observe($('imageview-close'), 'click', apps.ImageView.hide);
		Event.observe($('imageview-previous'), 'click', apps.ImageView.previous);
		Event.observe($('imageview-next'), 'click', apps.ImageView.next);
		$('imageview-title').innerHTML = box.rssdata.title + ' - ' + box.rssdata.items[no].title;
		$('imageview-content').innerHTML = box.rssdata.items[no].description;
		box.setReaded(box, no, true);
	},

	previous: function() {
		var current = apps.ImageView.lastno - 1;
		if (current < 0) { return; }
		apps.ImageView.show(apps.ImageView.boxid, current);
		return false;
	},

	next: function() {
		var current = apps.ImageView.lastno + 1;
		if (current >= apps.ImageView.max) { return; }
		apps.ImageView.show(apps.ImageView.boxid, current);
		return false;
	},

	hide: function() {
		$('imageview').style.display = 'none';
		layout.modalHide();
		layout.keyRemoveHandler(27, apps.ImageView.hide);     // ESC
		layout.keyRemoveHandler(38, apps.ImageView.previous); // UP
		layout.keyRemoveHandler(37, apps.ImageView.previous); // LEFT
		layout.keyRemoveHandler(39, apps.ImageView.next);     // RIGHT
		layout.keyRemoveHandler(32, apps.ImageView.next);     // RIGHT
		layout.keyRemoveHandler(40, apps.ImageView.next);     // DOWN
	}

}

apps.BoxManager = {
	// Tóték dobozolnak... yeah
	show: function() {
		layout.modalShow();
		$('boxmanager').style.display = 'block';
		layout.keyAddHandler(27, apps.BoxManager.hide);
		Event.observe($('boxmanager-close'), 'click', apps.BoxManager.hide);
		Event.observe($('boxmanager-button'), 'click', function(e) {
			var input = $('boxmanager-rssurl');
			if (input.value != '') {
				var box = new Box({column: 10*(layout.currentTab+100), type: 'rss', source: input.value});
				input.value = '';
				apps.BoxManager.hide();
			}
		});

		var items = $('boxmanager').getElementsByTagName('a');
		for (var i = 0; i<items.length; i++) {
			var item = items[i];
			if (item.rel && item.rel == 'feed' && !item.onclick) {
				item.onclick = function(){
					var box = new Box({column: 10*(layout.currentTab+100), type: 'rss', source: this.href});
					apps.BoxManager.hide();
					return false;
				};
			}
		}

	},

	hide: function() {
		$('boxmanager').style.display = 'none';
		layout.modalHide();
		layout.keyRemoveHandler(27, apps.BoxManager.hide);
	}

}

function setupBehaviours(area) {
	if (!area) { area='body'; }

	$$(area+' .b-defaultvalue').each(function(item){
		item.onfocus = function(){
			if (item.value == item.defaultValue) {
				item.value = '';
			}
		}
		item.onblur = function(){
			if (item.value == '') {
				item.value = item.defaultValue;
			}
		}
	});
	$$(area+' ul.b-radioitems').each(function(item){
		var items = item.childNodes;
		for(var i=0; i<items.length; i++) { if (items[i].nodeType==1) {
			var oldonclick = items[i].onclick;
			items[i].onclick = function () {
				setRadioItem(this, items);
				if (oldonclick) oldonclick.call(this, i);
			}
		}}
	});
}

setRadioItem = function(e, items){
				for(var j=0; j<items.length; j++) { if (items[j].nodeType==1) {
					if (e != items[j]) {
						Element.removeClassName(items[j], 'active');
						if (items[j].id.match(/^radioitem-/)) {
							Element.removeClassName($(items[j].id.replace(/^radioitem-/, 'radiocontent-')), 'active');
						}
						if (matches = items[j].className.match(/\bfor-([^ ]+)/g)) {
							for (var i=0; i<matches.length; i++) {
								Element.removeClassName($(matches[i].substr(4)), 'active');
							}
						}
					} else {
						Element.addClassName(items[j], 'active');
						if (items[j].id.match(/^radioitem-/)) {
							Element.addClassName($(items[j].id.replace(/^radioitem-/, 'radiocontent-')), 'active');
						}
						if (matches = items[j].className.match(/\bfor-([^ ]+)/g)) {
							for (var i=0; i<matches.length; i++) {
								Element.addClassName($(matches[i].substr(4)), 'active');
							}
						}
					}
				}}
			};

function BookmarkPage() {
	// Tedd el... légyszilégyszilégyszi
	// Bár én ezt nem tartom annyira faszának.
	title = "Hírfigyelő";
	url = "http://hirfigyelo.hu";
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url, "");
	} else if (window.external) { // IE Favorite
		window.external.AddFavorite( url, title);
	} else if (window.opera && window.print) { // Opera Hotlist...
								 // nem mintha az Opera per pill támogatott lenne
		return true; }
	}

Event.onDOMReady(function() {
	// és megy.
	fixDroppables();
	cookies = new Cookies();
	user = new User();
	storage = new Storage();
	layout = new Layout();
	tooltip = new Tooltip();
	setupBehaviours('body');
	/*
	$('header-add-content-personalized').onclick = function() {
		$$('#radiocontent-settings input').each(function(checkbox){
			checkbox.checked = false;
			for(box in storage.data.boxes) {
				var boxo = storage.data.boxes[box];
				if (boxo && boxo.column && boxo.column>=100 && boxo.column<=109) {
					if (boxo.type == 'rss' && boxo.source == checkbox.value) {
						checkbox.checked = true;
					}
					if (boxo.type != 'rss' && boxo.type == checkbox.value) {
						checkbox.checked = true;
					}
				}
			}
		});
		$('addcontent-static').style.display = 'none';
	}
	*/
	$('header-add-content-personalized').onclick = function() {
		// Új tartalom rulez
		DisplayPage('http://www.hirfigyelo.hu/hozzaad.php', 'Tartalom hozzáadása', '760px', '450px', '50px', '#fff', 'http://www.hirfigyelo.hu/js/includes/addcontent.js');
	}

	// Mert a logónak klikkelhetőnek kell lennie... mégha nem is csinál semmit.
	$('focim').onclick = function() { hidedpage(); layout.pageSwitch.call($('header-tabs-0')); }

	$('header-close-all').onclick = function() { Box.prototype.boxOpenCloseAll(false); }
	$('header-open-all').onclick = function() { Box.prototype.boxOpenCloseAll(true); }

	if (cookies.get('username') && cookies.get('username') != 'guest') {
		// Be vagy jelentkezve
		$('header-login').innerHTML = 'Kijelentkezés';
		$('header-login').onclick = function() { User.prototype.logout(); }
	} else {
		// Noname senki vagy
		$('header-login').innerHTML = 'Bejelentkezés / Regisztráció';
		$('header-login').onclick = function() { DisplayPage('http://www.hirfigyelo.hu/inline_login.php', 'Bejelentkezés / Regisztráció', '720px', '400px', '60px', '#fff', 'http://www.hirfigyelo.hu/js/includes/login.js'); }
	}
	var inplace = new Ajax.InPlaceEditor('header-page-title-text', 'url',{
					highlightcolor: '#303030',
					highlightendcolor: "#303030",
					clickToEditText: "Szerkeszt",
					okText: "OK",
					cancelText: "mégsem"
	});
	inplace.onSubmit = function(){
		value = inplace.editField.value;
		storage.data.layout.title =	value;
		$('header-page-title-text').innerHTML =  value;
		document.title = value + ' - ' + document.oldtitle;
		storage.save('layout.title', storage.data.layout.title);
		inplace.onclickCancel.call(inplace);
		return false;
	};
	$('header-tabs-new').onclick = function() {
		// új tab.
		var newid = 0;
		var tabs = $$('#header .tabs li');
		// drágám, hogy hívjuk a gyereket?
		for (var tab = 0; tab < tabs.length; tab++) {
			var id = tabs[tab].id; id = id.replace(/[^0-9]/g, '');
			if (id!='') {
				id = id * 1;
				if (id >= newid) { newid = id + 1; }
			}
		}
		layout.newTab(newid);
	}
	$$('#radiocontent-settings input').each(function(checkbox){
		checkbox.onfocus = function() {
			this.blur();
		}
		checkbox.onchange = function() {
			if (this.checked) {
				if (checkbox.value.match(/^http/)) {
					new Box({column: 100, type: 'rss', source: checkbox.value, isstatic: true});
				} else {
					new Box({column: 100, type: checkbox.value, isstatic: true});
				}
			} else {
				for(box in storage.data.boxes) {
					var boxo = storage.data.boxes[box];
					if (boxo && boxo.column && boxo.column>=100 && boxo.column<=109) {
						if (boxo.type == 'rss' && boxo.source == checkbox.value) {
							Box.prototype.boxRemove.call($('box_'+boxo.id))
							storage.data.boxes[box] = null;
						}
						if (boxo.type != 'rss' && boxo.type == checkbox.value) {
							Box.prototype.boxRemove.call($('box_'+boxo.id))
							storage.data.boxes[box] = null;
						}
					}
				}
			}
		}
	});
});

function getTabs() {
	// compatibility rulez
	return storage.data.layout.tabs;
}

function getRSSBoxes () {
	// RSS dobozok listája
	var rssboxes = new Array();
	for(box in storage.data.boxes) {
		var boxo = storage.data.boxes[box];
		if (box.match(/^box\d+$/)) {

			if (
				typeof(boxo)=="object" &&
				boxo.id &&
				boxo.type=='rss'
			) {
					rssboxes.push(boxo);

			}

		}
	}
	return rssboxes;
}

function getRSSBoxesForTab (tabid) {
	// Adott tabhoz tartozó RSS dobozok
	var rssboxes = new Array();
	for(box in storage.data.boxes) {
		var boxo = storage.data.boxes[box];
		if (box.match(/^box\d+$/)) {

			if (
				typeof(boxo)=="object" &&
				boxo.column>=(100+tabid)*10 &&
				boxo.column<=(100+tabid)*10+9 &&
				boxo.id &&
				boxo.type=='rss'
			) {
					rssboxes.push(boxo);

			}

		}
	}
	return rssboxes;
}

function getBoxesForTab (tabid) {
	// Adott tabhoz tartozó összes doboz
	// Szerintem ezt nem használjuk per pill
	// de tervben volt... de nem ment
	var rssboxes = new Array();
	for(box in storage.data.boxes) {
		var boxo = storage.data.boxes[box];
		if (box.match(/^box\d+$/)) {

			if (
				typeof(boxo)=="object" &&
				boxo.column>=(100+tabid)*10 &&
				boxo.column<=(100+tabid)*10+9 &&
				boxo.id
			) {
					rssboxes.push(boxo);

			}

		}
	}
	return rssboxes;
}

function getTabTitleFromID(ktab) {
	// Mi a tab címe
	var tabs = storage.data.layout.tabs;
	for (var t = 0; t < tabs.length; t++) {
		var tab = tabs[t];
		if (tab.id == ktab) {
			return tab.title;
		}
	}
	return '[hibás fülnév]';
}

function getBoxTitle (bid) {
	// Mi a doboz címe
	if (typeof($('box_' + bid + '-title'))!="object") { return ''; }
	var x = $('box_' + bid + '-title').innerHTML;
	x = x.replace(/ &nbsp;/gi, '');
	return x;
}

function getBoxIcon (bid) {
	// Mi a doboz ikonja?
	var x = "/static/icon-box.png";
	if (typeof(BoxCommon.getBox(bid).icon)=="string") {
		x = '/iconcache.php?'+escape(BoxCommon.getBox(bid).icon);
	}
	return x;
}

function getParentTab(bid) {
	// Hogy hívják az anyádat doboz?
	var element = $('box_'+bid);
	var no = true;
	var nok;
	while (no==true) {
		if (typeof(element.parentNode.id)=="string") {
			nok = element.parentNode.id;
		}
		if (nok.substr(0, 10)=='container-' && no==true) {
			no = false;
		} else {
			element = element.parentNode;
		}
	}
	return (nok.substr(11, 2)*1);
}

// Hülyén néz ki, de néma praktikus lehet, amikor kell callback függvény...
function kamu () {
	return;
}

function hidedpage() {
	// Valami nem tetszik?
	layout.modalHide();
	$('modalcframetrick').style.display='none';
	layout.keyRemoveHandler(27, hidedpage);     // ESC
}

function DisplayPage (url, cim, w, h, top, bg, js) {
	// Na ez faszaság... nagyon faszaság
	// Tulajdonképpen egy ablakot nyitunk, amibe bármit belerakhatunk

	if (url) {
		$('modalcframetrick').style.display='block';
		$('modalcframetrick').style.top = document.documentElement.scrollTop  + 'px';
		layout.modalShow();
		$('modal').innerHTML = '<div id="framecontent"><div id="frametitle"><div id="close-btn"><img src="/static/reader_close_btn.png"  onclick="hidedpage();" /></div><span>'+cim+'</span></div><div style="width:90px; margin-top: 25px; margin-left:auto; margin-right:auto; font-weight: bold; font-size:1.2em; background: #fff url(/static/icon-working.gif) no-repeat top left; padding-left: 20px;">töltődik...</div></div>';
		$('framecontent').style.width = "300px";
		$('modalcframetricki').style.width =  "300px";
		$('framecontent').style.height = "100px";
		$('modalcframetricki').style.height = "100px";

		layout.keyAddHandler(27, hidedpage);     // ESC

	new Ajax.Request(url, {
			method:'get',
			onSuccess: function(transport){
				$('modal').innerHTML = '<div id="framecontent"><div id="frametitle"><div id="close-btn"><img src="/static/reader_close_btn.gif"  onclick="hidedpage();" /></div><span>'+cim+'</span></div><div id="framemaincontent">'+transport.responseText+'</div></div>';

				if (js) { Load(js); } // Na ez az igazán fasza

				if (typeof(w)=="string") {
					$('modalcframetricki').style.width = w;
					$('framecontent').style.width = w;
				} else {
					$('modalcframetricki').style.width =  "400px";
					$('framecontent').style.width = "400px";
				}
				if (typeof(h)=="string") {
					$('modalcframetricki').style.height = h;
					$('framecontent').style.height = h;
				} else {
					$('modalcframetricki').style.height = "300px";
					$('framecontent').style.height = "300px";
				}
				if (typeof(top)=="string") {
					$('modalcframetricki').style.marginTop = top;
					$('framecontent').style.marginTop = top;
				} else {
					$('modalcframetricki').style.marginTop = "90px";
					$('framecontent').style.marginTop = "90px";
				}
				if (typeof(bg)=="string") {
					$('framecontent').style.backgroundColor = bg;
					$('modalcframetricki').style.backgroundColor = bg;
				} else {
					$('framecontent').style.backgroundColor = "#fff";
					$('modalcframetricki').style.backgroundColor = "#fff";
				}
				$('modalcframetricki').style.marginRight = "auto";
				$('modalcframetricki').style.marginLeft = "auto";
				$('framecontent').style.marginRight = "auto";
				$('framecontent').style.marginLeft = "auto";
				
			},
			onFailure: hidedpage // Ha hiba van, mintha mi sem történt volna...
		});
	}
	gtrack('loadpage/'+url);
}

function preloadimagessdf(n) {
	// Előtöltjük a képeket... lehet arról hitvitát tartani, hogy rekurzió-e
	if (typeof(n)!="number") {
		n = 0;
	}
	if (document.images) {
		var preloadimagesdf;
		var preloadimagessdf=new Array(	// TODO Frissíteni kéne a listát
			'/static/header_bg.png',
			'/static/footer_logo.gif',
			'/static/footer_bg.png',
			'/static/header_logo.gif',
			'/static/rss_icon.gif',
			'/static/header_menu_tab_active_left.png',
			'/static/header_menu_tab_active_right.png',
			'/static/header_menu_tab_inactive_left.png',
			'/static/header_menu_tab_inactive_right.png',
			'/static/header_menu_bg.png',
			'/static/plus.gif',
			'/static/box-bottom-bg.png',
			'/static/back-forth.gif',
			'/static/close.gif',
			'/static/remove.gif',
			'/static/icon-item.gif',
			'/static/mini_logo.gif',
			'/static/back-forth.gif',
			'/static/reader_close_btn.gif',
			'/static/plus.gif',
			'/static/open.gif',
			'/static/reader_folder_icon.gif',
			'/static/close.gif',
			'/static/document.gif',
			'/static/remove.gif',
			'/static/reader_brc_active_double_right.png',
			'/static/reader_brc_inactive_single_left.png',
			'/static/reader_brc_active_right.png',
			'/static/reader_brc_active_left.png',
			'/static/reader_close_btn.gif',
			'/static/markasread.gif',
			'/static/bubble-arrow.gif',
			'/static/icon-close.png',
			'/static/icon-closeapp.png',
			'/static/arrow-right.png',
			'/static/arrow-left.png',
			'/static/icon-working.gif',
			'/static/footer_bg.png',
			'/static/footer_logo.gif'
		);
		if (n < preloadimagessdf.length && typeof(preloadimagessdf[n])=="string") {
			for (var i = 0; i<document.images.length;i++) {
				if (document.images[i].src == "http://www.hirfigyelo.hu"+preloadimagessdf[n]) {
					setTimeout("preloadimagessdf("+(n+1)+")",10);
					return;
				}
			}
			setTimeout("preloadimagessdf("+(n+1)+")",120);
			var preloadimagesdf = new Image();
			preloadimagesdf.src = preloadimagessdf[n];
		}
	}
}

function IsBoxVisible (bid) {
	// Látható a doboz? Szintén nem használjuk, mert a tervem befuccsolt ezzel kapcsolatban
	var tab = getParentTab(bid);
	if ($('header-tabs-'+tab).hasClassName('active')) {
		return true;
	}
	return false;
}

function tabtorol (tidx) {
	// Öld meg!
	$('hovermenutab').style.display= "none";
	var tab = $('header-tabs-'+tidx);

	var tabtitle = tab.getElementsByTagName('b')[0].innerHTML;
	var tid = tidx*1+100;
	if(confirm("Biztosan be szeretnéd zárni az alábbi fület: "+tabtitle+"?\nMinden ezen lévő tartalom el fog veszni!")) {
		for (var i=0; i<BoxCommon.boxes.length; i++) {
			var box = BoxCommon.boxes[i];
			if (box.data.column>=tid*10 && box.data.column<=tid*10+9) {
				Box.prototype.boxRemove.call($('box_'+box.data.id));
			}
		}
		tab.parentNode.removeChild(tab);
		delete tab;
		var tabs = storage.data.layout.tabs;
		var t = 0;
		while (t < tabs.length && tabs[t].id != tid-100) { t++; }
		if (t < tabs.length) { tabs.splice(t, 1); }
		$('container-'+((tidx*1)+100)).removeClassName('page-container-ures');
		$('container-'+((tidx*1)+100)).removeClassName('page-container');
		storage.save('layout.tabs', storage.data.layout.tabs);
		gtrack('tabtorol/'+tidx);
		layout.pageSwitch.call($('header-tabs-0'));
	}
}

function tabatnevez (tidx) {
	// Átnevezés
	$('hovermenutab').style.display= "none";
	var tab = $('header-tabs-'+tidx);
	var tabtitle = tab.getElementsByTagName('b')[0].innerHTML;
	var tid = tidx*1+100;
	var ujnev = false;
	if (ujnev = window.prompt("Írd be a fül új nevét ("+tabtitle+")", tabtitle)) {
		if (ujnev && ujnev != tabtitle) {
			tab.getElementsByTagName('b')[0].innerHTML = ujnev;
			var tabs = storage.data.layout.tabs;
			var found = -1;
			for (var t = 0; t < tabs.length; t++) {
				if (tabs[t].id == layout.currentTab) { found = t; }
			}
			tabs[found].title = ujnev;
			storage.save('layout.tabs', storage.data.layout.tabs);
		}
	}
}

function GetX( oElement ) {
	// Nem akarjátok tudni...
	var iReturnValue = 0;
	while( oElement != null ) {
		iReturnValue += oElement.offsetLeft;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}


function findPosY(obj) {
	var curtop = 0;
	if(obj.offsetParent)
		while(1) {
			curtop += obj.offsetTop;
			if(!obj.offsetParent)
				break;
			obj = obj.offsetParent;
		}
	else if(obj.y)
		curtop += obj.y;
	return curtop;
}


function tabmindetkinyit (tid) {
	$('hovermenutab').style.display= "none";
	for (var i=0; i<BoxCommon.boxes.length; i++) {
		var box = BoxCommon.boxes[i];
		if (box.data.column-1000>=tid*10 && box.data.column-1000<tid*10+10) {
			var id = box.id;
			$('box_' + id + '-control-kibe').src="/static/close.gif";
			var content = $('box_' + id + '-content');
			if (content) { content.style.display = 'block'; }
			box.open = true;
		}
	}
}
function tabmindetbezar (tid) {
	$('hovermenutab').style.display= "none";
	for (var i=0; i<BoxCommon.boxes.length; i++) {
		var box = BoxCommon.boxes[i];
		if (box.data.column-1000>=tid*10 && box.data.column-1000<tid*10+10) {
			var id = box.id;
			$('box_' + id + '-control-kibe').src="/static/open.gif";
			var content = $('box_' + id + '-content');
			if (content) { content.style.display = 'none'; }
			var edit = $('box_' + id + '-edit');
			if (edit) { edit.style.display = 'none'; }
			box.open = false;
		}
	}
}

function showcurrentsettings () {
	// Ez afféle backdoor az adminisztrációhoz.
	// Csak beírod a címsorba és le tudod menteni a beállítást
	// hogy azt be lehessen tenni bárhová...

	// (nagyon sok macerától kímél meg)

	document.body.innerHTML = '';
	var valami = storage.data;
		for (box in valami.boxes) {
			valami.boxes[box].readed = '';
			valami.boxes[box].readedFirst = '';
			valami.boxes[box].refresh = 0;
		}
	document.body.innerHTML = valami.toJSON(valami);
	document.body.style.font= "1em Courier, Verdana";
	document.body.style.paddingTop= "120px";
	document.body.style.Margin= "20px";
}

function getolvasatlanok() {
	var kim = 0;
	var j = 0;
	for (j in olvasatlanok) {
		if (typeof(olvasatlanok[j])=="number") {
			kim = kim+olvasatlanok[j];
		}
	}
	return kim;
}

function getrssdobozokszama() {
	var kim = 0;
	var j = 0;
	for (j in olvasatlanok) {
		if (typeof(olvasatlanok[j])=="number") {
			kim++;
		}
	}
	return kim;
}

function getszoveg(szoveg) {
		
		var rsskezdoszoveg = szovegek[szoveg];
		rsskezdoszoveg = replaceall(rsskezdoszoveg, '[olvasatlanelemekszama]', getolvasatlanok());
		rsskezdoszoveg = replaceall(rsskezdoszoveg, '[rssdobozokszama]', getrssdobozokszama());
		return rsskezdoszoveg;
} 

window.onscroll = function(){  // Firefox hack... a firefox mindig tekerni akar... no matter what
	if ($('modal').style.display=="block") {
		document.documentElement.scrollTop = topment; // ronda hack TODO
	}
}



// Betöltjük a stringeket
Load ('/js/includes/szovegek.js');





