var laphu = {};

$(function() {
	laphu.initSearch();
	laphu.initStat();
	$("div.box p.t.d").initMeghatarozas();
	$(".tabber").setTabClick();
	$("div.hirlevel input[type=text]").setFBEvents();
	$("div.box.lk > a").initLinks();
	$("div.f div.box span a, div#footer a").setTargetBlank();
	if (!laphu.conf.accessibility) {
		$("div.td select, td select, input.chkbox, textarea.c").convertInputs();
		$(".rrnyil, .llnyil, .runyil, .rdnyil, .rlnyil").convertShapes({shape: "nyil" });
		$(".pf, .ctl, .ctr, .cbl, .cbr").ifixpng(laphu.conf.res_url + "img/blank.gif");
	}
});

var ie6 = (jQuery.browser.msie && jQuery.browser.version < 7);

laphu.text = {
	linkInfoTexts: {
		showTul: "Tulajdonságok megtekintése",
		hideTul: "Tulajdonságok elrejtése",
		showAllTul: "Összes tulajdonság megtekintése",
		hideAllTul: "Összes tulajdonság elrejtése"
	},
	rate: [
		"rossz",
		"nem az igazi",
		"használható",
		"jó",
		"tökéletes"
	],
	bubbaText: "Értékeld a linket, jelezd, ha hibás!"
};

laphu.naughtyItems = {
	toggled: false,
	ied: false,
	className: "fenyo",
	items: ["iframe", "object", "embed"],
	toggle: function(){
		if (!this.ied) {
			if (ie6) this.items.push("select");
			for(var i=0; i<this.items.length; i++){ this.items[i] += ":visible"; };
			$(this.items.toString())
			.css("visibility", this.toggled ? "visible" : "hidden")
			.addClass(this.className);
			this.ied = true;
		}
		else $("."+ this.className).css("visibility", this.toggled ? "visible" : "hidden");
		this.toggled = !this.toggled;
	}
};
laphu.random = Math.round(Math.random() * 100000000);
laphu.ctclick = function(rel, me){
	var src = laphu.conf.ctlog_url + "?id="+ rel +"&pid="+ laphu.conf.page_id;
	$("img#logimage").attr("src", src +"&rnd="+ laphu.random);
};

laphu.initStat = function(){
	$("body").append('<img alt="logimage" src="' + laphu.conf.res_url +'img/blank.gif" id="logimage" />');
	this.clicked = [];
	var items = ["div.lk a", "div.f div.box span a", "div.he span a"];
	var $this = this;
	$(items.toString()).mousedown(function(e){
		if (!$this.clicked[this.id] && !$.cookie(this.id))
			$this.rel = this.id.split('_').pop();
		
		var date = new Date();
		date.setTime(date.getTime() + laphu.conf.click_wait*1000);
		$.cookie(this.id, '1', {path: '/', expires: date});
	});
	$(items.toString()).mouseout(function(e){
		delete $this.rel;
	});
	$(items.toString()).mouseup(function(e){
		if (e.which != 3 && $this.rel == this.id.split('_').pop()) {
			if (!ie6 || e.which != 2) {
				$this.clicked[this.id] = true;
				delete $this.rel;
				laphu.ctclick(this.id.split('_').pop(), $this);
			}
		}
	});
};

laphu.m2s = function(prefs) {
	this.init = function(prefs){
		this.el = prefs.el;
		this.jEl = $(this.el);
		this.align = this.getAlign();
		this.direction = this.getDirection();
		this.color = prefs.color;
		this.hColor = prefs.hColor;
		this.isInA = this.hColor ? true : false;
		this.pixVisible = "<b></b>";
		this.pixInVisible = "<i></i>";
		this.pixOpacity = "<u></u>";
	};
	
	this.convert = function(){
		$("."+ this.shape, this.jEl).remove();
		var shapeHTML = '<span class="'+ this.shape +'">';
		
		switch(this.direction){
			case 'r':
				for(var y = 0; y < this.matrix.length; y++)
					for(var x = 0; x < this.matrix[y].length; x++)
						shapeHTML += this.getPixel(this.matrix[y][x]);
				break;
			case 'd':
				for(var y = 0; y < this.matrix.length; y++)
					for(var x = 0; x < this.matrix[y].length; x++)
						shapeHTML += this.getPixel(this.matrix[x][y]);
				break;
			case 'l':
				for(var y = 0; y < this.matrix.length; y++)
					for(var x = (this.matrix[y].length-1); x >= 0; x--)
						shapeHTML += this.getPixel(this.matrix[y][x]);
				break;
			case 'u':
				for(var y = (this.matrix.length-1); y >= 0; y--)
					for(var x = (this.matrix[y].length-1); x >= 0; x--)
						shapeHTML += this.getPixel(this.matrix[x][y]);
				break;
		}
		shapeHTML += "</span>";
		if (this.align == 'r')
			this.jEl.append(shapeHTML);
		else
			this.jEl.prepend(shapeHTML);
			
		this.jEl.find("span b, span u").css("backgroundColor", this.color);
		this.jEl.find("span u").fadeTo(0, 0.5);
		if (this.isInA){
			var $this = this;
			this.jEl.hover(function(){
				$(this).find("span b, span u").css("backgroundColor", $this.hColor);
			}, function(){
				$(this).find("span b, span u").css("backgroundColor", $this.color);
			});
		}
	};
	
	this.getPixel = function(val){
		switch(val){
			case 0:
				return this.pixInVisible;
			break;
			case 1:
				return this.pixVisible;
			break;
			case 2:
				return this.pixOpacity;
			break;
		}
	};
	
	this.getMatchClass = function(){
		return this.jEl.attr("class").match(".."+ this.shape).toString();
	};
	
	this.getAlign = function(){
		var c = this.getMatchClass();
		return c.charAt(0);
	};
	
	this.getDirection = function(){
		var c = this.getMatchClass();
		return c.charAt(1);
	};
	
	return this.init(prefs);
};

laphu.nyil = function(prefs) {
	this.shape = "nyil";
	this.matrix = new Array(
		new Array(0, 0, 0, 1, 0, 0, 0, 0, 0),
		new Array(0, 0, 0, 1, 1, 0, 0, 0, 0),
		new Array(1, 1, 1, 1, 1, 1, 0, 0, 0),
		new Array(1, 1, 1, 1, 1, 1, 1, 0, 0),
		new Array(1, 1, 1, 1, 1, 1, 1, 1, 0),
		new Array(1, 1, 1, 1, 1, 1, 1, 0, 0),
		new Array(1, 1, 1, 1, 1, 1, 0, 0, 0),
		new Array(0, 0, 0, 1, 1, 0, 0, 0, 0),
		new Array(0, 0, 0, 1, 0, 0, 0, 0, 0)
	);
	this.inheritFrom = laphu.m2s;
	this.inheritFrom(prefs);
};

(function($) {
	$.fn.convertShapes = function(op) {
		var op = $.extend({
			shape: "nyil"
		}, op);
		return this.each(function() {
			var baseColor = $(this).css("color");
			if ($(this).css("border-top-color")){
				var hoverColor = $(this).css("border-top-color");
			}
			var shape = new laphu[op.shape]({
				el: this,
				color: baseColor,
				hColor: hoverColor ? hoverColor : false
			});
			shape.convert();
		});
	};
	$.fn.setTabClick = function(o) {
		var op = $.extend({
			activeItem : 0
		}, o);
		var tabIndex = 0;
		this.changeTab = function(idx){
			if (tabIndex != idx) {
				$(this).children('a').each(function(i){
					if (i == idx)
						$(this).addClass("active");
					else
						$(this).removeClass("active");
				});
				$(this).siblings("span").each(function(i){
					if (i == idx)
						$(this).removeClass('h');
					else
						$(this).addClass('h');
				});
				tabIndex = idx;
			}
		};
		var me = this;
		return this.each(function() {
			$(this).children('a').each(function(idx){
				$(this).click(function(){
					me.changeTab(idx);
					return false;
				});
			});
			//első link rossz IE6 bug
			if (ie6) $(this).after("<b></b>");
			me.changeTab(op.activeItem);
		});
	};
	$.fn.setTTabClick = function() {
		return this.each(function() {
			var id = $(this).attr("id");
			$(this).children('a').each(function(idx){
				$(this).click(function(){
					if (laphu[id] && laphu[id].changeTab){
						laphu[id].changeTab(idx);
					}
					else
						laphu.changeTTab(idx);
					return false;
				});
			});
		});
	};
	$.fn.setContentTableLinks = function(options) {
		var op = $.extend({
			width : 180
		}, options);
		var size = this.length - 1;
		$("body").append('<span id="strWidth" class="t"></span>');
		var d = $('#strWidth');
		return this.each(function(idx) {
			d.text($(this).text());
			var thisW = d.width();
			if (op.width <= thisW) {
				var text = '';
				while (op.width < thisW) {
					text = d.text();
					d.text(text.substring(0, (text.length - 1)));
					thisW = d.width();
				}
				$(this)
				.attr("title", $(this).text().replace("▪ ", ""))
				.text(d.text().substring(0, d.text().length) +'...');
			}
			if (idx == size)
				d.remove();
		});
	};
	$.fn.initMeghatarozas = function(o) {
		var op = $.extend({
			height : laphu.conf.accessibility ? 64 : 53,
			fix : laphu.conf.accessibility ? 8 : 3
		}, o);
		$("div.f div.box a.y.ab").live("click", function(){
			var p = $(this).siblings('p');
			if($(this).hasClass('top')) {
				$(this).removeClass('top');
				p.css("height", op.height);
			} else {
				$(this).addClass('top');
				p.css("height", parseInt($(this).attr("rel")));
			}
			if (ie6) $(".cbl, .cbr", $(this).parent()).css("bottom", "-1px");
			return false;
		});
		var size = this.length - 1;
		$("body").append('<span id="strHeight" class="t" style="display:block;'+
			(!laphu.conf.accessibility ? "width:190px;line-height:14px;" : "width:210px;line-height:24px;font-weight:normal;")+
			'"></span>');
		var d = $('#strHeight');
		return this.each(function(idx) {
			d.html($(this).html());
			if ((op.height + op.fix) < d.height())
				$(this).after('<a href="#" class="y ab" rel="'+ (d.height() - op.fix) +'"></a>');
			if (idx == size)
				d.remove();
		});
	};
	$.fn.setFBEvents = function() {
		return this.each(function() {
			var value = $.trim($(this).val());
			if (value != '') {
				$(this).focus(function(){
					if ($(this).val() == value) 
						$(this).val('');
				}).blur(function(){
					if ($(this).val() == '') 
						$(this).val(value);
				});
			}
		});
	};
	$.fn.initLinks = function() {
		return this.each(function() {
			$(this).setTargetBlank();
			if (!laphu.conf.accessibility)
				$(this).append("<em onclick=\"goToPage($(this));return false;\" title=\""+ laphu.text.bubbaText +"\"></em>");
			if (ie6) $(this).children("em").height($(this).height() + 10);
		});
	};
	$.fn.setTargetBlank = function() {
		return this.each(function() {
			$(this).attr('target', '_blank');
		});
	};
	$.fn.convertInputs = function(o) {
		var op = $.extend({
			selectLimit: 10
		}, o);
		var bindFn = function(event){
			var me = event.target;
			var w = parseInt($(me).css("width"));
			var h = parseInt($(me).css("height"));
			var lh = parseInt($(me).css("line-height"));
			var up = $(me).parent().parent().siblings(".srollUp").children('a');
			var down = $(me).parent().parent().siblings(".srollDown").children('a');
			var timer = 0;
			var clearMousehold = function() {
				clearInterval(timer);
			};
			var stepOneLine = function(up){
				if (up){
					if ((me.scrollTop - lh) >= 0)
						me.scrollTop -= lh;
					else
						me.scrollTop = 0;
				}
				else {
					if ((me.scrollTop + lh) <= me.scrollHeight)
						me.scrollTop += lh;
					else
						me.scrollTop = me.scrollHeight;
				}
				$(me).keyup();
			};
			if (me.scrollHeight > h) {//aktiváljuk a nyilakat
				if (me.scrollTop > 0)
					up
					.css("display", "block")
					.unbind("mousedown mouseup click")
					.mousedown(function() {
	    				timer = setInterval(function() {
	    					stepOneLine(true);
	    				}, 300);
	    			})
					.mouseout(clearMousehold)
					.mouseup(clearMousehold)
					.click(function(e){
						e.preventDefault();
						clearMousehold();
						stepOneLine(true);
					});
				else
					up.css("display", "none");
				
				if (me.scrollTop < (me.scrollHeight - h))
					down
					.css("display", "block")
					.unbind("mousedown mouseup click")
					.mousedown(function() {
	    				timer = setInterval(function() {
	    					stepOneLine();
	    				}, 300);
	    			})
					.mouseout(clearMousehold)
					.mouseup(clearMousehold)
					.click(function(e){
						e.preventDefault();
						clearMousehold();
						stepOneLine();
					});
				else
					down.css("display", "none");
			}
			else {//leszedjük a nyilakat
				up.css("display", "none");
				down.css("display", "none");
			}
		};
		
		$("div.textarea")
		.live("keyup", bindFn)
		.live("scroll", bindFn)
		.live("focus", bindFn)
		.live("blur", bindFn)
		.live("click", function(){
		    $("textarea", this).focus();
		});
		return this.each(function(index) {
			switch($(this).attr("type").toLowerCase()){
				case "checkbox":
					var label = $(this).siblings("label[for="+ $(this).attr("id") +"]");
					$(this).hide();
					label
					.addClass("chkbox")
					.click(function(){
						$(this).toggleClass("checked");
					});
					if ($(this).attr("checked")){
						label.addClass("checked");
					}
					break;
				case "select-one":
					var select = new laphu.select(this.id);
					if (select)
						laphu.selects[this.id] = select;
					break;
				case "textarea":
					var w = parseInt($(this).css("width"));
					var h = parseInt($(this).css("height"));
					var lh = parseInt($(this).css("line-height"));
					$(this)
					.css({width: (w-16) +"px", height: (h-2) +"px"})
					.empty()
					.wrap("<div class=\"textarea\" style=\"width:"+ (w+2) +"px;height:"+ (h-2) +"px\">"+
						"<div class=\"fir\" style=\"width:"+ (w+2) +"px;height:"+ (h-2) +"px\"><div class=\"sec\" style=\"width:"+ (w-26) +"px;height:"+ (h-2) +"px\"\"></div></div>"+
						"<div class=\"ttl\" /><div class=\"ttr\" /><div class=\"tbl\" /><div class=\"tbr\" />"+
						"<div class=\"srollUp\"><a href=\"#\"></a></div><div class=\"srollDown\"><a href=\"#\"></a></div>"+
						"</div>"
					);
					break;
			}
		});
	};
	$.fn.check = function(mode) {
		var mode = mode || 'on'; // if mode is undefined, use 'on' as default
		return this.each(function() {
			switch(mode) {
			case 'on':
				this.checked = true;
				break;
			case 'off':
				this.checked = false;
				break;
			case 'toggle':
				this.checked = !this.checked;
				break;
			}
		});
	};
	$.fn.setToggleEvents = function(op) {
		var op = $.extend({
			opened: null
		}, op);
		return this.each(function() {
			var a = $(this).find("a.y");
			if ($(this).hasClass("fi"))
				a.click(function(){
					laphu.toggleAllLinkInfo();
					return false;
				});
			else
				a.click(function(){
					laphu.toggleLinkInfo(a.siblings("span").find("a:eq(0)").attr("id"));
					return false;
				});
			if (op.opened && a.attr("id") == "l_"+ op.opened)
				laphu.showLinkInfo($("a#l_"+ op.opened).parent().parent().find("a.y"));
		});
	};
	$.fn.setRatingEvents = function() {
		var me;
		var refreshRating = function(rating, linkId){
			$("#ert_l_"+ linkId +" b").width(rating +"px");
			laphu.info("Köszönjük az értékelését!");
		}
		
		return this.each(function() {
			me = $(this).children("span");
			var actErt = me.children("b").css("width");
			me
			.attr("id", "ert_"+ $(this).parent().siblings("div.he").find("span > a").attr("id"))
			.click(function(e){
				var o = $(this).offset();
				var x = (e.clientX - o.left);
				x = Math.ceil(x/20);
				if (x > 5) x = 5;
				var linkId = $(this).attr("id").split("_").pop();
				$.post(
					"/doboz/index.php?did="+ laphu.conf.dobozId,
					{ajax:1, lid: linkId, rating: x},
					function(data){
						if (data.success){
							actErt = data.rating +"px";
							refreshRating(data.rating, linkId);
						}
						else
							laphu.alert('Az értékelés közben hiba lépett fel, próbálja meg később!');
					},
					"json"
				);
				return false;
			})
			.mousemove(function(e){
				var o = $(this).offset();
				var x = (e.clientX - o.left);
				x = Math.ceil(x/20);
				if (x > 5) x = 5;
				$(this).children("b").width((x*19) +"px").attr("title", laphu.text.rate[x-1]);
			})
			.bind("mouseleave", function() {
				$(this).children("b").width(actErt).attr("title", '');
			});
		});
	};
})(jQuery);

laphu.toggleHidden = function(sender, hiddensParent){
	var visible = sender.hasClass("top");
	sender.toggleClass("top");
	if (sender.attr("rel") != ''){
		var t = sender.attr("rel");
		sender.attr("rel", sender.text()).text(t);
	}
	if (visible)
		hiddensParent.find(".h").hide();
	else
		hiddensParent.find(".h").show();
	if (ie6) $(".cbl, .cbr", $(sender).parent().parent()).css("bottom", "0");
}

laphu.toggleLinkInfo = function(id){
	var link = $("a#"+ id).parent().siblings("a.y");
	if (link.attr("title") == laphu.text.linkInfoTexts.hideTul)
		laphu.hideLinkInfo(link);
	else
		laphu.showLinkInfo(link);
}

laphu.toggleAllLinkInfo = function(){
	var show = true;
	var link = $("div.doboz div.box div.fi a.y");
	var links = $("div.doboz div.box div.boxlnk div.he a.y");
	link.find(".nyil").remove();
	if (link.text() == laphu.text.linkInfoTexts.hideAllTul){
		link
		.text(laphu.text.linkInfoTexts.showAllTul)
		.removeClass("o");
		$.each(links, function(){
			laphu.hideLinkInfo($(this));
		});
	}
	else {
		link
		.text(laphu.text.linkInfoTexts.hideAllTul)
		.addClass("o");
		$.each(links, function(){
			laphu.showLinkInfo($(this));
		});
	}
};

laphu.showLinkInfo = function(link){
	link
	.attr("title", laphu.text.linkInfoTexts.hideTul)
	.parent().parent().addClass('o');
};

laphu.hideLinkInfo = function(link){
	link
	.attr("title", laphu.text.linkInfoTexts.showTul)
	.parent().parent().removeClass('o');
};

laphu.linkajanlas = {
	changeTab: function(idx){
	    if (this.checkChange(idx)) {
		this.updateTitle("Linkajánlás - "+ (idx+1) +". oldal");
		laphu.changeTTab(idx);
	    }
	},
	updateTitle: function(title){
	    $("#linkajanlas").siblings("h2").text(title);
	},
	checkChange: function(idx){
		var actIdx = 0;
		$("#linkajanlas a").each(function(i){
			if($(this).hasClass("act"))
				actIdx = i;
		});
		switch(parseInt(idx)){
			case 0:
				$(".box.la").show();
				return true;
			break;
			case 1:
				if (actIdx == 2) return true;
				else {
					if ($("label[for=y_ok_buttom]").hasClass("checked")) {
						$(".box.la").hide();
						return true;
					}
					else laphu.alert("Nem fogadta el a lap.hu linkajánlási szabályzatát!");
				}
			break;
			case 2:
				if ($("label[for=y_ok_buttom]").hasClass("checked")) {
					if ($("label[for=g_ok_buttom]").hasClass("checked")) {
						$(".box.la").hide();
						if (!$("#captchaImg img").hasClass("l")){
							refreshCaptcha();
							$("#captchaImg img").addClass("l");
						}
						return true;
					}
					else laphu.alert("Nem fogadta el a szerkesztő linkajánlási szabályzatát!");
				}
				else laphu.alert("Nem fogadta el a lap.hu linkajánlási szabályzatát!");
			break;
		}
		return false;
	},
	sendForm: function(){
		var el = $("table.form.linkajanlas");
		var params = this.getParams(el);
		params.ajax = 1;
		laphu.bosyBox.toggle();
		
		$.post(
			"index.php",
			params,
			this.prd,
			"json"
		);
	},
	getParams: function(el){
		var params = {
			boxname: laphu.selects['bname'].getValue(),
			url: $.trim($("input[name=url]", el).val()),
			text: $.trim($("input[name=text]", el).val()),
			alt: $.trim($("input[name=alt]", el).val()),
			comment: $.trim($("textarea[name=comment]", el).val()),
			name: $.trim($("input[name=name]", el).val()),
			email: $.trim($("input[name=email]", el).val()),
			code: $.trim($("input[name=code]", el).val())
		};
		return params;
	},
	prd: function(data){
		if (!data.errors || !data.errors.length){
			if (data.success == true){
				laphu.info("Az ajánlott linket elküldtük a szerkesztő részére!");
				$(".ui-dialog-content a.button").click(function(){
					document.location.href = laphu.conf.laphuURL;
				});
			}
			else {
				laphu.alert("Az ajánlás küldése közben hiba lépett fel, kérjük, próbálja meg később!");
			}
		}
		else {
			var el = $("table.form.linkajanlas");
			var alertEl = el.parent().siblings("p.alert");
			alertEl.addClass("hc").html("<b>Hiba:</b><br />");
			laphu.formUtils.clearErrors(el);
			$.each(data.errors, function(idx, error){
				alertEl.append("<div class=\"ali\">&#9642; "+ error.msg +"</div>");
				laphu.formUtils.setError(el, error.field);
			});
			alertEl.removeClass("hc");
			if (alertEl.height() < 48)
				alertEl.height(48);
		}
		laphu.bosyBox.toggle();
	},
	selectBoxColumn: function(oszlopId, oszlopName){
		laphu.selects['doboz'].setLabel(oszlopName);
		laphu.selects['doboz'].setValue(oszlopId);
		laphu.selects['bname'].setLabel('Nincs doboz kiválasztva');
		laphu.selects['bname'].setValue(0);
		laphu.selects['bname'].setDatas(laphu.conf.boxes[oszlopId]);
	},
	selectBoxName: function(dobozId, dobozName){
		laphu.selects['bname'].setLabel(dobozName);
		laphu.selects['bname'].setValue(dobozId);
	}
};

laphu.ujlaphu = {
	changeTab: function(idx){
		if (this.checkChange(idx)) {
			this.updateTitle("Új lap.hu oldal indítása - "+ (idx+1) +". oldal");
			laphu.changeTTab(idx);
		}
	},
	updateTitle: function(title){
		$("#ujlaphu").siblings("h2").text(title);
	},
	checkChange: function(idx){
		var actIdx = 0;
		$("#ujlaphu a").each(function(i){
			if($(this).hasClass("act"))
				actIdx = i;
		});
		switch(parseInt(idx)){
			case 0:
			case 1:
				return true;
			break;
			case 2:
				if ($("label[for=read_them_buttom]").hasClass("checked")) return true;
				else laphu.alert("Nem fogadta el a szerkesztési alapelveket!");
			break;
		}
	},
	sendForm: function(){
		var el = $("div.body.ujlaphu");
		var params = this.getParams(el);
		params.ajax = 1;
		laphu.bosyBox.toggle();
		
		$.post(
			"index.php",
			params,
			this.prd,
			"json"
		);
	},
	getParams: function(el){
		var params = {
			hasSite: $("label[for=i_have_laphu_buttom]").hasClass("checked") || 0,
			name: $.trim($("input[name=name]", el).val()),
			email: $.trim($("input[name=email]", el).val()),
			email2: $.trim($("input[name=email2]", el).val()),
			pageName: $.trim($("input[name=page_name]", el).val()),
			category: laphu.selects["kategoriak"].getValue(),
			definition: $.trim($("textarea[name=definition]", el).val()),
			conception: $.trim($("textarea[name=conception]", el).val()),
			subject: $.trim($("textarea[name=subject]", el).val()),
			overlap: $.trim($("textarea[name=overlap]", el).val()),
			connection: $.trim($("textarea[name=connection]", el).val()),
			link1name: $.trim($("input[name=link1name]", el).val()),
			link1url: $.trim($("input[name=link1url]", el).val()),
			link2name: $.trim($("input[name=link2name]", el).val()),
			link2url: $.trim($("input[name=link2url]", el).val()),
			link3name: $.trim($("input[name=link3name]", el).val()),
			link3url: $.trim($("input[name=link3url]", el).val()),
			link4name: $.trim($("input[name=link4name]", el).val()),
			link4url: $.trim($("input[name=link4url]", el).val()),
			code: $.trim($("input[name=code]", el).val())
		};
		return params;
	},
	prd: function(data){
		if (!data.errors || !data.errors.length){
			if (data.success == true){
				laphu.info("Köszönjük, hogy részt veszel a Startlap mozgalomban!<br /><br />"+
					"Lapindítási szándékodat regisztráltuk és szerkesztőink nemsokára felveszik veled a kapcsolatot.<br />"+
					"Szerkesszük együtt a magyar internet legdinamikusabban fejlődő laprendszerét!<br /><br />"+
					"A Startlap szerkesztősége");
				$(".ui-dialog-content a.button").click(function(){
					window.location.reload();
				});
			}
			else {
				laphu.alert("A jelentkezés küldése közben hiba lépett fel, kérjük, próbálja meg később!");
			}
		}
		else {
			var el = $("div.body.ujlaphu");
			var alertEl = el.siblings("p.alert");
			alertEl.addClass("hc").html("<b>Hiba:</b><br />");
			laphu.formUtils.clearErrors(el);
			$.each(data.errors, function(idx, error){
				alertEl.append("<div class=\"ali\">&#9642; "+ error.msg +"</div>");
				laphu.formUtils.setError(el, error.field);
			});
			alertEl.removeClass("hc");
			if (alertEl.height() < 48)
				alertEl.height(48);
			scroll(0,0);
		}
		laphu.bosyBox.toggle();
	},
	selectMainCategory: function(id, name){
		laphu.selects['fokategoria'].setLabel(name);
		laphu.selects['fokategoria'].setValue(id);
		laphu.selects['kategoriak'].setLabel('Nincs kategória kiválasztva');
		laphu.selects['kategoriak'].setValue(0);
		laphu.selects['kategoriak'].setDatas(laphu.conf.subCategories[id]);
	},
	selectCategory: function(id, name){
		laphu.selects['kategoriak'].setLabel(name);
		laphu.selects['kategoriak'].setValue(id);
	}
};

laphu.atadolaphu = {
	changeTab: function(idx){
		if (this.checkChange(idx)) {
			this.updateTitle("Jelentkezés átadó lapok szerkesztésére - "+ (idx+1) +". oldal");
			laphu.changeTTab(idx);
		}
	},
	updateTitle: function(title){
		$("#atadolaphu").siblings("h2").text(title);
	},
	checkChange: function(idx){
		var actIdx = 0;
		$("#ujlaphu a").each(function(i){
			if($(this).hasClass("act"))
				actIdx = i;
		});
		switch(parseInt(idx)){
			case 0:
			case 1:
				return true;
			break;
			case 2:
				if ($("label[for=read_them_buttom]").hasClass("checked")) return true;
				else laphu.alert("Nem fogadtad el a szerkesztési alapelveket!");
			break;
		}
	},
	sendForm: function(){
		var el = $("div.body.atadolaphu");
		var params = this.getParams(el);
		params.ajax = 1;
		laphu.bosyBox.toggle();
		
		$.post(
			"index.php",
			params,
			this.prd,
			"json"
		);
	},
	getParams: function(el){
		var params = {
			hasSite: $("label[for=i_have_laphu_buttom]").hasClass("checked") || 0,
			name: $.trim($("input[name=name]", el).val()),
			email: $.trim($("input[name=email]", el).val()),
			email2: $.trim($("input[name=email2]", el).val()),
			pageName: laphu.selects["pagename"].getValue(),
			definition: $.trim($("textarea[name=definition]", el).val()),
			conception: $.trim($("textarea[name=conception]", el).val()),
			subject: $.trim($("textarea[name=subject]", el).val()),
			overlap: $.trim($("textarea[name=overlap]", el).val()),
			connection: $.trim($("textarea[name=connection]", el).val()),
			link1name: $.trim($("input[name=link1name]", el).val()),
			link1url: $.trim($("input[name=link1url]", el).val()),
			link2name: $.trim($("input[name=link2name]", el).val()),
			link2url: $.trim($("input[name=link2url]", el).val()),
			link3name: $.trim($("input[name=link3name]", el).val()),
			link3url: $.trim($("input[name=link3url]", el).val()),
			link4name: $.trim($("input[name=link4name]", el).val()),
			link4url: $.trim($("input[name=link4url]", el).val()),
			code: $.trim($("input[name=code]", el).val())
		};
		return params;
	},
	prd: function(data){
		if (!data.errors || !data.errors.length){
			if (data.success == true){
				laphu.info("Köszönjük, hogy részt veszel a Startlap mozgalomban!<br /><br />"+
					"Lap átvételi szándékodat regisztráltuk és szerkesztőink nemsokára felveszik veled a kapcsolatot.<br />"+
					"Szerkesszük együtt a magyar internet legdinamikusabban fejlődő laprendszerét!<br /><br />"+
					"A Startlap szerkesztősége");
				$(".ui-dialog-content a.button").click(function(){
					window.location.reload();
				});
			}
			else {
				laphu.alert("A jelentkezés küldése közben hiba lépett fel, kérjük, próbálja meg később!");
			}
		}
		else {
			var el = $("div.body.atadolaphu");
			var alertEl = el.siblings("p.alert");
			alertEl.addClass("hc").html("<b>Hiba:</b><br />");
			laphu.formUtils.clearErrors(el);
			$.each(data.errors, function(idx, error){
				alertEl.append("<div class=\"ali\">&#9642; "+ error.msg +"</div>");
				laphu.formUtils.setError(el, error.field);
			});
			alertEl.removeClass("hc");
			if (alertEl.height() < 48)
				alertEl.height(48);
			scroll(0,0);
		}
		laphu.bosyBox.toggle();
	},
	selectLaphu: function(id, name){
		laphu.selects['pagename'].setLabel(name);
		laphu.selects['pagename'].setValue(id);
	}
};

laphu.tTabIndex = 0;
laphu.changeTTab = function(idx){
	if (laphu.tTabIndex != idx) {
		$(".ttabber").children('a').each(function(i){
			if (i == idx)
				$(this).addClass("act");
			else
				$(this).removeClass("act");
		});
		$(".ttabber").siblings("div:gt(1)").each(function(i){
			if (i == idx)
				$(this).show();
			else
				$(this).hide();
		});
		laphu.tTabIndex = idx;
	}
};

laphu.alert = function(message){
	laphu.dialog.open({mode: 'alert', content: message});
};

laphu.info = function(message){
	laphu.dialog.open({mode: 'info', content: message});
};

laphu.confirm = function(message, handler){
	laphu.dialog.open({mode: 'confirm', content: message, confirmHandler: handler});
}

laphu.generateId = function(str){
	if (!str || str == '')
		str = "laphu";
	return str + Math.round(Math.random()*1000);
}

laphu.dialogs = [];
laphu.dialog = {
	callbacks : {},
	
	add2body : function(html){
		$('body').append('<div id="cont'+ this.id +'" class="hc"><div id="'+ this.id +'">'+ html +'</div></div>');
	},
	
	getButton : function(buttons){
		var html = '';
		for (var i in buttons){
			this.callbacks['bu_'+ this.id +'_'+ i] = buttons[i].handler;
			html += '<a id="bu_'+ this.id +'_'+ i +'" href="#" onclick="return false;" class="gomb"><b>'+ buttons[i].text +'</b></a>';
		}
		return html;
	},
	
	addCallbacks : function(){
		var $this = this;
		$.each(this.callbacks, function(index, callback){
			$('#'+ index).unbind('click').click( function(){ eval(callback); return false; });
		});
	},
	
	close : function(){
		var id = laphu.dialogs.pop();
		$("#"+ id).dialog("destroy").remove();
		$("#cont"+ id).remove();
		if (!laphu.dialogs.length) laphu.naughtyItems.toggle();
	},
	
	open : function(prefs){
		this.prefs = {
			title: 'Rendszerüzenet',
			url: '',
			modal: true,
			params: {},
			mode: 'default',
			content: '',
			confirmHandler: ''
		};
		$.extend(this.prefs, prefs);
		
		var dialogOptions = {
			modal: this.prefs.modal,
		    title: this.prefs.title,
		    width: 500,
		    dialogClass: 'main-dialog',
			position: ["center", 84],
			closeOnEscape: false,
			close: function(event, ui) {
				laphu.dialog.close();
			}
		}
		
		this.id = laphu.generateId('dialog');
		laphu.dialogs.push(this.id);
		laphu.naughtyItems.toggle();
		var $this = this;
		switch(this.prefs.mode){
			case 'default':
				var html = this.prefs.content;
				this.add2body(html);
				$("#"+ this.id).dialog(dialogOptions);
			break;
			case 'dialog':
				$.get(
					this.prefs.url,
					this.prefs.params,
					function(html){
						$this.add2body(html);
						$("#"+ $this.id).dialog(dialogOptions);
						/*
						if (laphu.forms[$this.prefs.form] && laphu.forms[$this.prefs.form].callback)
							laphu.forms[$this.prefs.form].callback();
						*/
					}
				);
			break;
			case 'alert':
			case 'info':
				var cls = (this.prefs.mode == 'info' ? 'lamp' : this.prefs.mode);
				var style = '';
				if (ie6)
					style = ' style="background-image:none !important; filter:Progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+ laphu.conf.rel_path +'res/img/'+ cls +'.png\', sizingMethod=\'crop\');"';
				
				var html = '<div class="'+ this.prefs.mode +'"><div class="img '+ cls +'"'+ style +'></div><div class="left" style="width:406px;overflow:hidden;">'+ this.prefs.content +'</div><div class="clear" style="padding-top:10px;"></div><div class="bs"><a href="javascript:laphu.dialog.close();" class="left button">Rendben<span>&nbsp;</span></a></div></div>';
				this.add2body(html);
				$("#"+ this.id).dialog(dialogOptions);
			break;
			case 'confirm':
				var html = '<div class="confirm"><div class="img"></div>'+ this.prefs.content +'<div class="clear" style="padding-top:10px;"></div>'+ this.getButton([{text: 'rendben', handler: this.prefs.confirmHandler, icon: 'tick'}, {text: 'mégsem', handler: '$this.close();', icon: 'cross'}]) +'</div>';
				this.add2body(html);
				$("#"+ $this.id).dialog($.extend(dialogOptions, {height: 200}));
				this.addCallbacks();
			break;
		}
		$("#"+ this.id +" .pf").ifixpng(laphu.conf.res_url +"img/blank.gif");
	}
}

laphu.selects = {};
laphu.select = function(id){
	this.id = 0;
	this.pageSize = 10;
	this.label = '';
	this.options = [];
	this.jEl = null;
	this.timer = 0;
	this.callback = false;
	
	this.init = function(id){
		if (!id || $.trim(id) == '') return false;
		
		this.id = id;
		if (!this.setJel()) return false;
		this.label = this.getJel().siblings("label").text();
		this.options = this.getJel()[0].options;
		this.callback = this.getJel().attr("title").indexOf("document.") == 0 ? false : this.getJel().attr("title").replace('();', '');
		
		if (this.getJel()
		.hide()
		.after("<div class=\"input w200 pointer rdnyil\"><b></b><p class=\"sep\">&nbsp;</p><em>&nbsp;</em></div>")){
			this.setLabel(this.label);
			this.setOptions();
			return this;
		}
		else return false;
	};
	
	this.setJel = function(){
		if ($('#'+ this.id).size()){
			this.jEl = $('#'+ this.id);
			return true;
		}
		else return false;
	};
	
	this.getJel = function(){
		var ret = false;
		if (this.jEl != null)
			ret = this.jEl;
		else {
			if (this.id)
				if (this.setJel()) 
					ret = this.jEl;
		}
		return ret;
	};
	
	this.setLabel = function(text){
		var el = this.getJel().siblings(".input").find('b').eq(0);
		el.text(text);
	};
	
	this.clearInt = function() {
		clearInterval(this.timer);
	};
	
	this.setInt = function(){
		var me = this;
		this.timer = setInterval(function() {
			me.closeSelecter(false);
			me.clearInt();
		}, 1000);
	};
	
	this.closeSelecter = function(justClose){
		var visible = this.getJel().siblings(".selecter").css("display") == "block";
		if (!justClose){
			if (visible)
				this.toggleSelecter(visible);
		}
		else
			this.toggleSelecter(visible);
	};
	
	this.setValue = function(value){
		this.getJel().attr("rel", value);
	};
	
	this.getValue = function(){
		return typeof this.getJel().attr("rel") != "undefined" ? this.getJel().attr("rel") : 0;
	};
	
	this.setDatas = function(datas){
	    this.options = [];
	    if (typeof datas[0] == "string"){//ha nincs külön érték megadva
		for(var i in datas){
		    if (parseInt(i) >= 0)
			this.options.push({text: datas[i], value: datas[i]});
		}
	    }
	    else {
		for(var i in datas){
		    if (parseInt(i) >= 0)
			this.options.push(datas[i]);
		}
	    }
	    if (this.options.length){//csak ha valóban vannak elemek
		this.clearOptions();
		this.pageSize = 10;
		this.setOptions();
		$(".rrnyil, .llnyil", this.getJel().siblings(".selecter")).convertShapes({shape: "nyil"});
	    }
	};
	
	this.clearOptions = function(){
		this.getJel().siblings(".selecter").remove();
	};
	
	this.setOptions = function(){
		var opts = "<div class=\"selecter\"><div class=\"top\"></div><div class=\"c\">";
		var me = this;
		if (this.options.length){
			if (this.options.length > this.pageSize){
				var pageCount = Math.ceil(this.options.length/this.pageSize);
				var p = 1;
				var m;
				opts += "<div id=\""+ this.id +"_"+ p +"\">";
				for (var i = 0; i < pageCount*this.pageSize; i++){
					m = i!= 0 && i % this.pageSize == 0;
					if (m){
						opts += this.getSelectPager(p, pageCount);
						opts += "</div><div id=\""+ this.id +"_"+ (p+1) +"\" style=\"display:none;\">";
						p++;
					}
					if (this.options[i])
						opts += this.getSelectRow(this.options[i], i, ((i+1) % this.pageSize == 0) || (i == this.options.length-1));
					else
						opts += "<b class=\"sep\">&nbsp;</b>";
				}
				opts += this.getSelectPager(p, pageCount) +"</div>";
			}
			else
				$.each(this.options, function(idx){
					opts += me.getSelectRow(this, idx, idx == (me.options.length-1));
				});
		}
		else {
			opts += "<b>Nincs megjeleníthető elem!</b>";
		}
		opts += "</div><div class=\"bottom\"></div></div>";
		this.getJel()
		.siblings(".input")
		.after(opts)
		.unbind("click")
		.click(function(){
			me.closeSelecter(true);
		});
		
		this.getJel()
		.siblings(".selecter")
		.find("div.c > a, div.c > div > a").unbind("click").click(function(){
			var visible = $(this).parent().parent().css("display") == "block";
			me.toggleSelecter(visible);
		});
		this.getJel()
		.siblings(".input")
		.unbind("mouseover mouseout")
		.mouseover(function(){
			me.clearInt();
		})
		.mouseout(function(){
			me.setInt();
		});
		this.getJel()
		.siblings(".selecter")
		.width(200)
		.mouseover(function(){
			me.clearInt();
		})
		.mouseout(function(){
			me.setInt();
		});
	};
	
	this.toggleSelecter = function(visible){
		var dH = $(document).height();
		var sib = this.getJel().siblings(".selecter");
		var offSet = this.getJel().siblings(".input").offset();
		var height = sib.height();
		var topPadding = this.getJel().parent().hasClass("td") ? 10 : 0;
		var topPos = 20 + topPadding;
		if ((offSet.top + height) > (dH - 40)){
			sib.find(".top").attr("class", "ctop");
			sib.find(".bottom").attr("class", "cbottom");
			sib.height(height).css("top", -(height-(topPos-17)) +"px");
		}
		else {
			sib.find(".ctop").attr("class", "top");
			sib.find(".cbottom").attr("class", "bottom");
			sib.height(height).css("top", topPos +"px");
			//this.getJel().siblings(".selecter").height(height).css("top", topPos +"px");
		}
		
		var el = this.getJel().siblings(".input");
		el.children(".nyil").remove();
		if (visible){
			el.removeClass("runyil")
			.addClass("rdnyil")
			.convertShapes({shape: "nyil"});
			sib.hide().css({
				zoom: 0,
				zIndex: 1
			});
			//parentet 1-re
			sib.parent().parent().css({
				zoom: 0,
				zIndex: 1
			});
		}
		else {
			el.removeClass("rdnyil")
			.addClass("runyil")
			.convertShapes({shape: "nyil"});
			//többit hide
			for (var i in laphu.selects){
				laphu.selects[i].closeSelecter();
			}
			
			sib.show().css({
				zoom: 1,
				zIndex: 10000,
				"float": "left"
			});
			//parentet 10000-re
			sib.parent().parent().css({
				zoom: 1,
				zIndex: 10000
			});
		}
	};
	
	this.getSelectPager = function(page, pageCount){
		var html = '';
		switch(page){
			case 1:
				html = "<div class=\"l\" style=\"border-bottom:0;\">" +
					"<strong class=\"left llnyil\">Előző</strong>"+
					"<a class=\"right rrnyil\" href=\"javascript:laphu.setSelectPage('"+ this.id +"', "+ (page+1) +")\">Következő</a>"+
					"</div>";
				break;
			case pageCount:
				html = "<div class=\"l\" style=\"border-bottom:0;\">" +
					"<a class=\"left llnyil\" href=\"javascript:laphu.setSelectPage('"+ this.id +"', "+ (page-1) +")\">Előző</a>"+
					"<strong class=\"right rrnyil\">Következő</strong>"+
					"</div>";
				break;
			default:
				html = "<div class=\"l\" style=\"border-bottom:0;\">" +
					"<a class=\"left llnyil\" href=\"javascript:laphu.setSelectPage('"+ this.id +"', "+ (page-1) +")\">Előző</a>"+
					"<a class=\"right rrnyil\" href=\"javascript:laphu.setSelectPage('"+ this.id +"', "+ (page+1) +")\">Következő</a>"+
					"</div>";
		}
		return html;
	};
	
	this.getSelectRow = function(option, idx, last){
		var html = '<a href="';
		if (option.value.indexOf && option.value.indexOf("http") == 0){
		    html += htmlspecialchars(option.value) +"\" target=\"_blank\""+ (laphu.conf.nofollow ? " rel=\"nofollow\"" : '');
		}
		else {
		    html += "#\" onclick=\"eval("+ this.callback +"('"+ htmlspecialchars(option.value) +"', '"+ htmlspecialchars(option.text) +"'));return false;\"";
		}
		html += (last ? " class=\"nom\"" : '') +">"+ htmlspecialchars(option.text) +"</a>";
		return html;
	};
	
	this.setPage = function(page){
		$("#"+ this.id +"_"+ page)
		.show()
		.siblings("div")
		.hide();
	};
	
	return this.init(id);
};

laphu.setSelectPage = function(id, page){
	$("#"+ id +"_"+ page)
	.show()
	.siblings("div")
	.hide();
}

laphu.changeHirekPage = function(forward){
	var el = $("div.news");
	
	if (el){
		var i = 0;
		el.children("div[class=''], div[class='h']").each(function(idx){
			if (!$(this).hasClass("h")) {
				i = idx;
				$(this).addClass("h");
			}
		});
		i = forward ? i+1 : i-1;
		el.children("div[class='h']").eq(i).removeClass("h");
		var p = el.children("div.l");
		if (i == 0){
			p.children("strong.left").show();
			p.children("a.left").hide();
		}
		else if (i == el.children("div[class=''], div[class='h']").size()-1){
			p.children("strong.right").show();
			p.children("a.right").hide();
		}
		else {
			p.children("strong").hide();
			p.children("a").show();
		}
	}
}

laphu.uzenetASzerkesztonek = {
	show: function(){
		var el = $("#uzenetASzerkesztonek").html();
		laphu.dialog.open({
			content: el,
			title: "Üzenet a szerkesztőnek"
		});
		refreshCaptcha();
	},
	sendForm: function(){
		var el = $(".ui-dialog-content table.form.uzenetASzerkesztonek");
		var params = this.getParams(el);
		params.ajax = 1;
		laphu.bosyBox.toggle();
		
		$.post(
			"index.php",
			params,
			this.prd,
			"json"
		);
	},
	getParams: function(el){
		var params = {
			name: $.trim($("input[name=name]", el).val()),
			email: $.trim($("input[name=email]", el).val()),
			comment: $.trim($("textarea[name=comment]", el).val()),
			code: $.trim($("input[name=code]", el).val())
		};
		return params;
	},
	prd: function(data){
		if (!data.errors || !data.errors.length){
			if (data.success == true){
				laphu.dialog.close();
				laphu.info("A javaslatot sikeresen továbbítottuk a szerkesztőnek!");
			}
			else {
				laphu.alert("A javaslat küldése közben hiba lépett fel, kérjük, próbálja meg később!");
			}
		}
		else {
			var el = $(".ui-dialog-content table.form.uzenetASzerkesztonek");
			var alertEl = el.siblings("p.alert");
			alertEl.addClass("hc").html("<b>Hiba:</b><br />");
			laphu.formUtils.clearErrors(el);
			$.each(data.errors, function(idx, error){
				alertEl.append("<div class=\"ali\">&#9642; "+ error.msg +"</div>");
				laphu.formUtils.setError(el, error.field);
			});
			alertEl.removeClass("hc");
			if (alertEl.height() < 48)
				alertEl.height(48);
		}
		laphu.bosyBox.toggle();
	}
};

laphu.hibasLinkJelzese = {
	linkId: 0,
	
	show: function(id, text, url){
		this.linkId = id;
		$("#hibasLinkJelzese #hll").html('<b>'+ text +'</b>');
		$("#hibasLinkJelzese #hlu").html('<b>'+ url +'</b>');
		var el = $("#hibasLinkJelzese").html();
		laphu.dialog.open({
			content: el,
			title: "Hibás link jelzése"
		});
		refreshCaptcha();
	},
	
	sendForm: function(){
		var el = $(".ui-dialog-content table.form.hibasLinkJelzese");
		var params = this.getParams(el);
		params.ajax = 1;
		params.lid = this.linkId;
		laphu.bosyBox.toggle();
		
		$.post(
			"../doboz/index.php?did="+ laphu.conf.dobozId,
			params,
			this.prd,
			"json"
		);
	},
	getParams: function(el){
		var params = {
			name: $.trim($("input[name=name]", el).val()),
			email: $.trim($("input[name=email]", el).val()),
			comment: $.trim($("textarea[name=comment]", el).val()),
			code: $.trim($("input[name=code]", el).val())
		};
		return params;
	},
	
	prd: function(data){
		if (!data.errors || !data.errors.length){
			if (data.success == true){
				laphu.dialog.close();
				laphu.info("A hibás linkről értesítettük a szerkesztőt!");
			}
			else {
				laphu.alert("A hibás link jelzése közben hiba lépett fel, kérjük, próbálja meg később!");
			}
		}
		else {
			var el = $(".ui-dialog-content table.form.hibasLinkJelzese");
			var alertEl = el.siblings("p.alert").eq(0);
			alertEl.addClass("hc").html("<b>Hiba:</b><br />");
			laphu.formUtils.clearErrors(el);
			$.each(data.errors, function(idx, error){
				alertEl.append("<div class=\"ali\">&#9642; "+ error.msg +"</div>");
				laphu.formUtils.setError(el, error.field);
			});
			alertEl.removeClass("hc");
			if (alertEl.height() < 48)
				alertEl.height(48);
		}
		laphu.bosyBox.toggle();
	}
};

laphu.hirlevel = {
	go2page: function(){
		var email = $("div.box div.hirlevel input").val();
		document.location.href = laphu.conf.rel_path +"hirlevel"+ (email != "Email cím" ? "/?email="+ email : '')
	},
	
	sendForm: function(){
		var el = $(".w466 table.form");
		var params = this.getParams(el);
		params.ajax = 1;
		laphu.bosyBox.toggle();
		
		$.post(
			"index.php",
			params,
			this.prd,
			"json"
		);
	},
	getParams: function(el){
		var params = {
			name: $.trim($("input[name=name]", el).val()),
			email: $.trim($("input[name=email]", el).val()),
			zip: $.trim($("input[name=zip]", el).val()),
			city: $.trim($("input[name=city]", el).val()),
			address: $.trim($("input[name=address]", el).val()),
			code: $.trim($("input[name=code]", el).val())
		};
		return params;
	},
	
	prd: function(data){
		if (!data.errors || !data.errors.length){
			if (data.success == true){
				laphu.info("Sikeres feliratkozás!<br /><br />A feliratkozás véglegesítéséhez elküldtünk postafiókodra egy aktivációs e-mailt.");
				$(".ui-dialog-content a.button").click(function(){
					document.location.href = laphu.conf.laphuURL;
				});
			}
			else {
				laphu.alert("A feliratkozás közben hiba lépett fel, kérjük, próbálja meg később!");
			}
		}
		else {
			var el = $(".w466 table.form");
			var alertEl = el.parent().parent().siblings("p.alert");
			alertEl.addClass("hc").html("<b>Hiba:</b><br />");
			laphu.formUtils.clearErrors(el);
			$.each(data.errors, function(idx, error){
				alertEl.append("<div class=\"ali\">&#9642; "+ error.msg +"</div>");
				laphu.formUtils.setError(el, error.field);
			});
			alertEl.removeClass("hc");
			if (alertEl.height() < 48)
				alertEl.height(48);
		}
		laphu.bosyBox.toggle();
	},
	
	unsubscribe: function(){
		params = {
			ajax: 1,
			code: $.trim($("table.form input[name=code]").val()),
			pages: ''
		};
		var size = $("div.hl label.checked").size();
		if (size)
			$("div.hl label.checked").each(function(i){
				params.pages += $(this).attr("for").split("_").pop() + (size-1 > i ? ',' : '');
			});
		else
			params.pages = 0;
		laphu.bosyBox.toggle();
		
		$.post(
			"index.php",
			params,
			this.prdLe,
			"json"
		);
	},
	
	prdLe: function(data){
		if (!data.errors || !data.errors.length){
			if (data.success == true){
				laphu.info("Sikeres leiratkozás!");
				$(".ui-dialog-content a.button").click(function(){
					document.location.href = laphu.conf.laphuURL;
				});
			}
			else {
				laphu.alert("A leiratkozás közben hiba lépett fel, kérjük, próbálja meg később!");
			}
		}
		else {
			var el = $(".w700 table.form");
			var alertEl = $(".w700 p.alert");
			alertEl.addClass("hc").html("<b>Hiba:</b><br />");
			laphu.formUtils.clearErrors(el);
			$.each(data.errors, function(idx, error){
				alertEl.append("<div class=\"ali\">&#9642; "+ error.msg +"</div>");
				laphu.formUtils.setError(el, error.field);
			});
			alertEl.removeClass("hc");
			if (alertEl.height() < 48)
				alertEl.height(48);
			scroll(0,0);
		}
		laphu.bosyBox.toggle();
	}
};

$("label[for=allofthem]").live("click", function(){
	var check = $(this).hasClass("checked");
	if (check){
		$("div.hl label.chkbox[class='chkbox']").addClass("checked");
	}
	else {
		$("div.hl label.chkbox[class='chkbox checked']").removeClass("checked");
	}
});

laphu.formUtils = {
	clearErrors: function(el){
		$(".a", el).removeClass("a");
	},
	
	setError: function(el, field){
		$("input[name="+ field +"]", el).parent().addClass("a").parent().siblings("td").addClass("a");
		$("select[name="+ field +"]", el).siblings(".input").addClass("a").parent().addClass("a").parent().siblings("td").addClass("a");
		$("textarea[name="+ field +"]", el).parent().parent().parent().addClass("a").parent().siblings("td").addClass("a");
	}
};

laphu.bosyBox = {
	show: function(){
		$('<div />')
		.addClass('ui-widget-overlay-p')
		.attr('id', 'progressbar-s')
		.height($(document).height())
		.appendTo("body")
		.show();
		$("body").append("<div id=\"progressbar\"><b>Feldolgozás folyamatban...</b></div>");
		
		$("#progressbar").css('top', this.getTopPosition()).progressbar({value: 0});
		
		if (!laphu.dialogs.length)
			laphu.naughtyItems.toggle();
		
		var animeFn = function(){
			$(".ui-progressbar-value").animate(
				{width: "100%" },
				4000,
				"linear",
				function(){
					$(".ui-progressbar-value")
					.animate(
						{opacity: "0"},
						1000,
						"linear",
						function(){
							$(".ui-progressbar-value").css({opacity: "1", width: 0});
							animeFn();
						}
					);
				}
			);
		};
		animeFn();
	},
	
	getTopPosition: function(){
		return ($(document).scrollTop() + Math.round($("body").height() / 2) - 20) +"px";
	},
	
	hide: function(){
		$("#progressbar").progressbar('destroy');
		$("#progressbar").remove();
		$("#progressbar-s").remove();
		if (!laphu.dialogs.length)
			laphu.naughtyItems.toggle();
	},
	
	toggle: function(){
		if ($(".ui-progressbar").size())
			this.hide();
		else
			this.show();
	}
};

SuggestionObj.timer = 0;

SuggestionObj.clearTimer = function() {
	clearInterval(this.timer);
};

SuggestionObj.setTimer = function(){
	var me = this;
	this.timer = setInterval(function() {
		me.closeSuggestDiv();
	}, 2000);
};

SuggestionObj.closeSuggestDiv = function(){
	this.clearTimer();
	$("div.startlapSuggestionResults").hide();
	$("div.h980 > b").siblings().css("visibility", "visible");
};

SuggestionObj.showSuggestDiv = function(){
	if ($("div.startlapSuggestionResults li").size()) {
		$("div.startlapSuggestionResults").show();
		$("div.h980 > b").siblings().css("visibility", "hidden");
	}
};

SuggestionObj.strongEnough = function(str){
	return "<b>"+ str +"</b>";
};

SuggestionObj.links = [];
SuggestionObj.topLink = 1;
SuggestionObj.hasContainer = false;

SuggestionObj.suggestionCallback = function(links, id){
	$("div.startlapSuggestionResults ul").empty();
	this.links = links;
	this.topLink = 0;
	if (this.links.length) {
		this.topLink = 1;
		var aContent = '';
		var linksHTML = '';
		var regexp = new RegExp(this.previousQuery, "ig");
		for (var i = 0; i < this.links.length; i++) {
			aContent = this.links[i].replace($(this.links[i]).text(), $(this.links[i]).text().replace(regexp, this.strongEnough));
			linksHTML += "<li>"+ aContent +"</li>";
		}
		if (!this.hasContainer){
			linksHTML = "<div id=\"controll\"><div id=\"upa\"><a tabindex=\"100\" href=\"#\">&nbsp;</a></div><div id=\"downa\"><a tabindex=\"100\" href=\"#\">&nbsp;</a></div><ul>"+
						linksHTML +
						"</ul></div>";
			$("div.startlapSuggestionResults").append(linksHTML);
			this.hasContainer = true;
			var me = this;
			$("div.search div.top form input#q, div.startlapSuggestionResults")
			.mouseover(function(){
				me.clearTimer();
			})
			.mouseout(function(){
				me.setTimer();
			});
			$("div.search div.top form input#q")
			.click(function(){
				me.showSuggestDiv();
			});
		}
		else {
			$("div.startlapSuggestionResults ul").html(linksHTML);
		}
		$("div.startlapSuggestionResults ul a").attr("tabindex", 100);
		this.showSuggestDiv();
	}
	else {
		this.closeSuggestDiv();
	}
	$("div.startlapSuggestionResults ul").css({"marginTop" : "0px"});
	this.refreshArrows();
};

SuggestionObj.refreshArrows = function(){
	var vars = {
		up : $("#upa").children('a'),
		down : $("#downa").children('a')
	};
	if (this.links.length <= 4) {//leszedjük a nyilakat
		vars.up.css("visibility", "hidden");
		vars.down.css("visibility", "hidden");
	}
	else {
		var me = this;
		vars.lh = 23;
		vars.ul = $("div.startlapSuggestionResults ul");
		vars.mTop = parseInt($("div.startlapSuggestionResults ul").css("marginTop"));
		vars.scrollCount = 4;
		var stepOneLine = function(up){
			var marginTop = 0;
			if (up){
				if (me.topLink > 1){
					if (me.topLink <= 5){
						marginTop = 0;
						me.topLink = 1;
					}
					else {
						marginTop = vars.mTop + vars.scrollCount * vars.lh;
						me.topLink -= vars.scrollCount;
					}
				}
			}
			else {
				if (me.topLink < me.links.length){
					if ((me.links.length - (me.topLink + 4)) <= 4){
						marginTop = -(me.links.length - 4) * vars.lh;
						me.topLink = me.links.length - 3;
					}
					else {
						marginTop = vars.mTop - vars.scrollCount * vars.lh;
						me.topLink += vars.scrollCount;
					}
				}
			}
			vars.up.unbind("click");
			vars.down.unbind("click");
			vars.ul.animate({"marginTop" : marginTop +"px"}, 200, "linear", function(){
				me.refreshArrows();
			});
		};
		if (me.topLink > 1)
			vars.up
			.css("visibility", "visible")
			.unbind("click")
			.click(function(e){
				e.preventDefault();
				stepOneLine(true);
			});
		else
			vars.up.css("visibility", "hidden");
		
		if ((me.links.length - me.topLink) >= 4)
			vars.down
			.css("visibility", "visible")
			.unbind("click")
			.click(function(e){
				e.preventDefault();
				stepOneLine();
			});
		else
			vars.down.css("visibility", "hidden");
	}
};

laphu.check = function(e){
	if (e.keyCode == 40 || e.keyCode == 38 || e.keyCode == 9){
		e.stopPropagation();
        e.cancelBubble = true;
		e.preventDefault();
		return false;
	}
	return true;
};

SuggestionObj.check = function(e){};

SuggestionObj.hideResults = function(){};
SuggestionObj.showResults = function(){};
SuggestionObj.transformLink = function(){};

laphu.initSearch = function(){
	$("div.startlapSuggestionResults a")
	.live("keydown", laphu.check)
	.live("keypress", laphu.check)
	.live("keyup", laphu.check);

	$("div.search a.c").click(function(){
		$(this).siblings("a.c").removeClass("selected").children("input").check("off");
		$(this).addClass("selected").children("input").check();
		return false;
	});
	
	var form = $("div.search div.top form");
	var input = $("input#q", form);
	
	form.attr("onsubmit", "headerSearch()");

	var setGoogle = function(){
	    form.attr("action", "http://www.startlap.hu/web/");
	};
	var setStartlapKereso = function(){
	    form.attr("action", "http://www.startlapkereso.hu/searchresult.jsp");
	};
	
	var headerSearch = function(){
		if ($("a[href=#google]").hasClass("selected")){
			firstTracker._trackPageview($('#google_url').val() + 'google/');
			secondTracker._trackPageview($('#google_url').val() + 'google/');
		}
		else {
			firstTracker._trackPageview($('#google_url').val() + 'startlap/');
			secondTracker._trackPageview($('#google_url').val() + 'startlap/');
		}
		form.submit();
	};

	$("a.right", form).click(function(){
		headerSearch();
	});

	if ($("a[href=#google]").hasClass("selected")){//ha a google az alap
	    setGoogle();
		$("img", form).show();
	    input.css("background", "none").focus(function(){
			$(this).css("background", "#fff").siblings("img").hide();
			if (typeof delRefresh == "function")
				delRefresh(ref);
	    }).blur(function(){
			if ($(this).val() == '')
				$(this).css("background", "none").siblings("img").show();
	    });
	}
	else {//ha a startlap az alap
	    setStartlapKereso();
	    input.css("background", "#fff").keyup(function(e){
			if (!laphu.conf.accessibility){
				SuggestionObj.suggest(this);
				laphu.check(e);
			}
	    })
	    .click(function(){
			if (!laphu.conf.accessibility)
				SuggestionObj.showSuggestDiv();
			if (typeof delRefresh == "function")
				delRefresh(ref);
	    });
	}
	
	if (laphu.conf.accessibility) {
	    $("input#s_g").change(function(){
		if ($.trim(input.val()) == '')
		    $("img", form).show();
		setGoogle();
		input
		.unbind("keyup focus click")
		.focus(function(){
		    $(this).siblings("img").hide();
		    if (typeof delRefresh == "function")
			delRefresh(ref);
		})
		.blur(function(){
		    if ($(this).val() == '')
			$(this).siblings("img").show();
		});
		input.focus();
	    });
	    $("input#s_s").change(function(){
			$("img", form).hide();
			setStartlapKereso();
			input
			.unbind("blur")
			.focus(function(){
				if (typeof delRefresh == "function")
				delRefresh(ref);
			});
			input.focus();
	    });
	}
	else {
	    $("a[href=#google]").click(function(){
			setGoogle();
			input
			.unbind("keyup focus click blur")
			.focus(function(){
				$(this).css("background", "#fff").siblings("img").hide();
				if (typeof delRefresh == "function")
				delRefresh(ref);
			})
			.blur(function(){
				if ($(this).val() == '')
				$(this).css("background", "none").siblings("img").show();
			});
			input.focus();
	    });
	    //villogás ellen
	    $("a[href=#startlap]").hover(
			function(){
				input.unbind("blur");
			}, function(){
				if ($("a[href=#google]").hasClass("selected"))
				input.blur(function(){
					if ($(this).val() == '')
					$(this).css("background", "none").siblings("img").show();
				});
	    });
	    $("a[href=#startlap]").click(function(){
			$("img", form).hide();
			setStartlapKereso();
			input
			.css("background", "#fff")
			.unbind("blur")
			.keyup(function(e){
				SuggestionObj.suggest(this);
				laphu.check(e);
			})
			.click(function(){
				SuggestionObj.showSuggestDiv();
				if (typeof delRefresh == "function")
				delRefresh(ref);
			});
			input.focus();
	    });
	}
}

$("#captchaImg").live('click', refreshCaptcha);
function refreshCaptcha(){
    $('#captchaImg img').attr('src', laphu.conf.rel_path +'captcha.php?'+ Math.round(10000 * Math.random()));
};

function goToPage(em){
    var lid = $(em).parent().attr("id").split("_").pop();
    var boxurl = $('h2 a',$(em).parent().parent()).attr("href");
    if (boxurl.indexOf('?')>0) document.location.href = boxurl+'&lid='+lid+'#doboz';
    else document.location.href = boxurl +'?'+lid+'#doboz';
};

function htmlspecialchars(ch) {
	ch = ch.replace(/&/g, "&amp;")
	ch = ch.replace(/\"/g, "&quot;")
	ch = ch.replace(/\'/g, "&#039;")
	ch = ch.replace(/</g, "&lt;")
	ch = ch.replace(/>/g, "&gt;")
	return ch
}