var hsSite = {
	layout: null,
	
	init: function(conf){
		if (!conf) {
			var conf={};
		}
		this.func = conf.func ? conf.func : [];
		this.layout = conf.layout;
		$(document).ready(function(){
			hsSite.Preferences.load();
			hsSite.initPage();
			var valelem=$('.valasztas')[0];
			if (valelem) {
				var valscrollElem=$('#valasztasScroll')[0];
				var timeout;
				var valheight=Math.round(valscrollElem.offsetHeight/2);
				function Cscroll() {
					valelem.scrollTop=valelem.scrollTop+1;
					if (valelem.scrollTop>=valheight) {
						valelem.scrollTop=0;
					}
					timeout=setTimeout(Cscroll, 30);
				}
				$('#valasztasScroll').hover(function(){clearTimeout(timeout);}, function(){timeout=setTimeout(Cscroll, 30);});
				Cscroll();
			}

		});
	},
	
	login: function(json){
		hsSite.Preferences.change(json);
		this.changeLayout(hsSite.Preferences.defaultLayout);
	},
	
	initPage: function(){
		hsSite.pToggle.init();
		hsSite.dlgMgr.init();
		hsSite.stat.init();
		$.each(this.func, function() {
			hsSite[this].init();
		});
	},
	
	changeLayout: function(layout) {
		if (this.layout != layout && (layout == 1 || layout == 2)) {
			$.get(hsconf.ajax_url + 'setpref.php?act=setLayout', {layout: layout}, function() {
				document.location.reload();
			});
		}
	}
	
};

hsSite.pToggle = {
	cookiejar: null,
	
	init: function(toinit){
		this.cookiejar = $.cookieJar('hs_toggle');
		var obj = this.cookiejar.toObject();
		for (var id in obj) {
			if (toinit && !toinit[id]){ 
				continue;
			}
				
			var chk = $('#' + id);
			if (chk.length) {
				chk.attr('checked', $(obj[id]).size() > 0);
			}
		}
	},
	
	toggle: function(name, selector) {
		var obj = this.cookiejar.toObject();
		
		if (!obj || !obj[name]) {
			this.cookiejar.set(name, selector);
		} else {
			this.cookiejar.remove(name);
		}
		var $obj = $(selector);
		if ($obj.size()>0){
			$obj.toggle();	
		} else {
			location.reload();
		}
	},

	checkErtekelt: function(name){
		if ($('#' + name).attr('checked')) {
			this.cookiejar.set(name, name);
		}
		else {
			this.cookiejar.remove(name);
		}
		document.location.href = hsconf.hirstart_url +'hirtar.php';
	},
	
	selectOrder: function(name, other){
		if (!this.defaults[name]) {
			this.cookiejar.set(name, name);
			this.cookiejar.remove(other);
			document.location.reload();
		}
	}
}

hsSite.Preferences = {
	
	load: function() {
		if (!hsconf.user) {
			this.loadFromCookie();
		} else {
			hsSite.Preferences.change(hsconf.user);
		}
	},
	
	loadFromCookie: function() {
		this.change({
			linkTarget: $.cookie('HS_LINKTARGET') || '_blank',
			defaultLayout: $.cookie('HS_LAYOUT') || '1',
			borderedBox: $.cookie('HS_BORDEREDBOX') || '1',
			onlyTitle: $.cookie('HS_ONLYTITLE') || '0'
		});
	},
	
	change: function(json) {
		this.remember = $.cookie('HS_REMEMBER') == 1 ? 1 : 0;
		this.linkTarget = json.linkTarget;
		this.defaultLayout = parseInt(json.defaultLayout);
		this.onlyTitle = parseInt(json.onlyTitle);
		this.borderedBox = parseInt(json.borderedBox);
		if (json.email) {
			this.loggedIn = true;
			this.uemail = json.email;
			this.hirtarba = json.hirtarba;
			this.hirfigyelo = json.hirfigyelo;
		} else {
			this.loggedIn = false;
			this.uemail = '';
		}
		this.updateDOM();
	},
	
	saveChanges: function(json, callback){
		var me=this;
		$.getJSON(hsconf.ajax_url + 'setpref.php?act=setAll', json, function(ret){
			me.change(json);
			if (callback)
				callback(ret);
		});
	},
	
	updateDOM: function() {
		if (this.loggedIn) {
			var uemail = this.uemail.substr(0, this.uemail.indexOf('@'));
			$('#pb_email').html(uemail);
			if ($('#pb_email').width() > 140){
				var emailField = $('#pb_email');
				thisW = $('#pb_email').width();
				while (140 < thisW) {
					var email = emailField.text();
					emailField.text(email.substring(0, (email.length - 1)));
					thisW = emailField.width();
				}
				emailField.text(emailField.text().substring(0, (emailField.text().length - 3)) +'...');
				$('#pb_email').attr('title', this.uemail);
			}
			
			$('#pb_email, #pb_logout').css('display','inline');
			$('#pb_reg, #pb_login').css('display','none');
			$('div.blueBox.keresesInfo').hide();
		} else {
			$('#pb_email, #pb_logout').css('display','none');
			$('#pb_reg, #pb_login').css('display','inline');
			$('div.blueBox.keresesInfo').show();
		}
		this.updateATarget();
	},
	
	updateATarget: function() {
		$('a[rel^=hs_]').attr('target',this.linkTarget);
	}
	
};

hsSite.vote = {
	
	init: function() {
		$('div.szavazas form').each(function(){
			var voteId = $(this).children("input[@name='voteId']").val();
			if ($.cookie('hs_vote'+ voteId)) {
				hsSite.vote.submit(voteId, true);
			}
			else {
				$(this).submit( function(){ hsSite.vote.submit(voteId); });
			}
		});
	},
	
 	submit: function(voteId, voted){
		var button = $("#v" + voteId + " input.voteBtn");
		var error = '';
		var params = {
			voteId: voteId,
			boxId: $("#v" + voteId + " input[name=boxId]").val()
		};
		button.hide();
		
		if (!voted) {
			if ($("#v" + voteId + " input[name=group" + voteId + "]:checked").size() == 1) 
				params.answer = $("#v" + voteId + " input[name=group" + voteId + "]:checked").val();
			else 
				error = 'A szavazás elküldéséhez ki kell választani egy választ!';
		}
		
		if (error == '') 
			$.post(hsconf.ajax_url + "vote.php", params, function(data){
				$('#v' + voteId).html(data);
				var date = new Date();
				date.setTime(date.getTime() + (hsconf.vote_lifetime * 60 * 1000));
				$.cookie('hs_vote' + voteId, 'nem törölhető', {
					path: '/',
					expires: date
				});
			});
		else {
			button.show();
			alert(error);
		}
	}
	
};

hsSite.search = {
	init: function() {
	},

	submit: function() {
		var q = $(".searchBox form input[name=query]").val();
		switch($(".searchBox ul li a.active").attr("href")){
			case "#hirstart":
				if (!q || q.length < 3) {
					alert('Legalább egy kulcsszót meg kell adni (min. 3 karakter)!');
					return false;
				} else 
					return true;
			case "#videostart":
				if (!q || q.length < 3) {
					alert('Legalább egy kulcsszót meg kell adni (min. 3 karakter)!');
					return false;
				} else
					return true;
			case "#web":
				//go to Google
				window.open('http://www.startlap.hu/web/?q='+ q, '_blank');
				break;
			case "#startlapkereso":
				//go to Startlapkereso
				window.open('http://www.startlapkereso.hu/searchresult.jsp?q='+ q, '_blank');
				break;
		}
		return false;
	},
	
	submitdetails: function() {
		var q = $(".advSearchBox form input[name=query]").val();
		if ((!q || q.length < 3) && !parseInt($(".advSearchBox form select[name=partner]").val()) && !parseInt($(".advSearchBox form select[name=category]").val())) {
			alert('Legalább egy kulcsszót meg kell adni (min. 3 karakter), vagy egyéb keresési feltételt!');
			return false;
		} else 
			return true;
	},
	
	toPage: function(page) {
		document.location.href = $.query.set('page',page);
	},
	
	setAction: function(to){
		$('div.searchBox ul li a, div.advSearchBox ul li a').each(function(){
			if ($(this).attr('href') == '#' + to) {
				$(this).addClass('active');
			}
			else
				$(this).removeClass('active');
		});
	}
	
}

hsSite.topList = {
	actTab : 0,
	
	showTab: function(index, location){
		if (!location)
			location = '.toplista';
		
		$(location +' .fulek li').each(function(i){
			var a = $($(this).find('a').get(0));
			if (i == index) {
				a.addClass('aktiv');
				$('#'+ a.attr('id') +'_body').show();
			}
			else {
				$('#'+ a.attr('id') +'_body').hide();
				a.removeClass('aktiv');
			}
		});
		this.actTab = index;
	},
	
	showItem: function(index){
		$('#tl_tab'+ (this.actTab + 1) +'_body ul li a').each(function(i){
			if(i == (index-1))
				$(this).addClass('aktiv');
			else
				$(this).removeClass('aktiv');
		});
		$('#tl_tab'+ (this.actTab + 1) +'_body .toplista_hirek>div, #tl_tab'+ (this.actTab + 1) +'_body .hircsatornak>div').each(function(i){
			if(i == (index-1))
				$(this).show();
			else
				$(this).hide();
		});
	}
	
}

hsSite.osszesmai = {
	pageButtons: [],
	page:0,
	
	init: function() {
		$('.osszesHirTemak input').each(
			function() {
				var id = this.id;
				var categories = id.split('_');
				categories.shift();
				var selectors = [];
				for(var i=0;i<categories.length;i++) {
					selectors.push('.rovatoldalCikklista .k_'+categories[i]);
				}
				$(this).click(function(){
					hsSite.pToggle.toggle(id, selectors.join(','));
					hsSite.osszesmai.stripOsszesmai();
				});
			}
		);
		var me=this;
		$('.pagination a').click(function(e) {e.preventDefault()}).
		each(function(i) {
			switch(i) {
				case 0:
					me.backButton = $(this);
					me.backButton.click(function() {me.pagePrev();});
				break;
				case 5:
					me.nextButton = $(this);
					me.nextButton.click(function() {me.pageNext();});
				break;
				default:
					var b=$(this);
					b.click(function(){me.toPage(i)});
					me.pageButtons.push(b);
				break;
			}
		});
		this.toPage(1);
		this.stripOsszesmai();
	},
	
	stripOsszesmai: function(){
		$('#osszmailist1 .rovidhir:visible:odd').removeClass('szurke');
		$('#osszmailist1 .rovidhir:visible:even').addClass('szurke');
	},
	
	pagePrev: function() {
		this.page--;
		this.showPage();
	},

	pageNext: function() {
		this.page++;
		this.showPage();
	},
	
	toPage: function(page) {
		this.page=page;
		this.showPage();
	},
	
	showButtons:function(){
		var backButton, nextButton;
		var me=this;
		for(var i=1; i<5;i++) {
			if (i == this.page) {
				this.pageButtons[i-1].addClass('active');
			} else {
				this.pageButtons[i-1].removeClass('active');
			}
		}
		switch(this.page) {
			case 1:
				this.backButton.css('visibility','hidden');
				this.nextButton.css('visibility','visible');
			break;
			case 2:
			case 3:
				this.backButton.css('visibility','visible');
				this.nextButton.css('visibility','visible');
			break;
			case 4:
				this.backButton.css('visibility','visible');
				this.nextButton.css('visibility','hidden');
			break;
		}
	},
	
	showPage:function(){
		this.showButtons();
		
		if(this.page > 0 && this.page < 5 ) {
			var destination = $('#osszmailist'+ this.page);
			
			for(var i=1;i<5;i++){
				if(i != this.page) $('#osszmailist'+i).hide();
			}
			destination.show();
			if (destination.html() == '') {
				var me = this;
				destination.load(hsconf.hirstart_url+'osszesmai'+ this.page +'.php',function() {
					me.filterPage();
				});
			}
			return true;
		}
		else
			return false;
	},
	
	filterPage: function() {
		$('.osszesHirTemak input').each(
			function() {
				if (!this.checked) {
					var categories = this.id.split('_');
					categories.shift();
					for (var i = 0; i < categories.length; i++) {
						$('.rovatoldalCikklista .k_' + categories[i]).hide();
					}
				}
			}
		);
		if ($('#om_bevezeto') && $('#om_bevezeto').attr('checked')) {
			$('.rovatoldalCikklista p.lead').show();
		}
		if ($('#om_opciok') && !$('#om_opciok').attr('checked')) {
			$('.rovatoldalCikklista div.info').hide();
		}
	}
	
}

hsSite.stat = {
	init: function() {
		$this=this;
		$('body').append('<img src="'+hsconf.hirstart_url+'img/blank.gif" id="logimage" style="position:absolute;display:none;" />');
		$('a[rel^=hs_]').mousedown(function(e){
			$this.rel=this.rel;
		});
		$('a[rel^=hs_]').mouseout(function(e){
			delete $this.rel;
		});
		$('a[rel^=hs_]').mouseup(function(e){
			if (e.which!=3 && $this.rel==this.rel) {
				if (!($.browser.msie && $.browser.version=='6.0') || e.which!=2) {
					hsSite.stat.ctclick(this.rel);
				}
			}
		});
	},
	
	salesclick: function(id){
		var src;
		if (!$.cookie('hs_stat')){
			var date = new Date();
			date.setTime(date.getTime() + (hsconf.stat_session_time * 60 * 1000));
			$.cookie('hs_stat', Math.round(Math.random()*10000000000), {path: '/', expires: date});
		}
		src = hsconf.logger_sales_url + '?id='+ id +'&cookie='+ $.cookie('hs_stat');
	
		$('img#logimage').attr("src", src +"&"+ Math.round(Math.random()*10000000000));
	},
	
	ctclick: function(rel){
		rel = rel.split('_');
		var src = hsconf.rd_url +'?id='+ rel[1] +'&bid='+ rel[2];
		$('img#logimage').attr("src", src +"&"+ Math.round(Math.random()*10000000000));
	},
	
	urlclick: function(url){
		var src = hsconf.url_rd_url +'?url='+ escape(url);
		$('img#logimage').attr("src", src +"&"+ Math.round(Math.random()*10000000000));
	}
}



function toggleSubMenu(id){
	var $this = $('#'+ id);
	var s = $this.siblings().get(0);
	$(s).toggleClass('aktiv');
	$this.toggle();
}

function setActivePartnerGroup(letter){
	$('div.aloldalBoxes div.h1_line h1').each(function(){
		if ($(this).text() == letter) {
			$(this).parent().addClass('nari');
		}
		else
			$(this).parent().removeClass('nari'); 
	});
}

function toggleInfo(selector) {
	$('div.rovatoldalForrasBox'+ selector +' div.info').toggle();
}

hsSite.dlg = {};

hsSite.dlg.login = {
	
	parseHistoryHash: function(hash) {
		if (hsSite.Preferences.loggedIn) return false;
		return hsSite.dlgBase.parseHistoryHash.call(this,hash);
	},

	reset: function() {
		this.getField('email').val('');
		this.getField('password').val('');
		$('#loginMsg').html('').hide();
	},

	onLoad: function() {
		hsSite.dlgBase.onLoad.call(this);
		var me=this;
		$('.backBtn',this.el).click(this.close);
		$('form',this.el).submit(function(e) {
			e.preventDefault();
			me.submit();
		});
		$('a.passwdsend',this.el).click(function(e) {
			e.preventDefault();
			me.passwdSend();
		});
	},
	
	focus: function() {
		this.getField('email').focus();
	},

	submit: function() {
		$('#loginMsg').html('').hide();
		var params = {
			email: this.getField('email').val(),
			password: this.getField('password').val(),
			remember: this.getField('remember').attr('checked') ? 1 : 0
		};
		if (!this.checkEmail(params.email)) {
			this.showError('email','Hibás e-mail formátum!');
			return;
		}
		if (!params.password) {
			this.showError('password','Adj meg jelszót!');
			return;
		}
		var me = this;
		var borderedBox = hsSite.Preferences.borderedBox;
		var onlyTitle = hsSite.Preferences.onlyTitle;
		$.post(hsconf.ajax_url + "login.php", params, function(data) {
			if (data.success) {
				$('#loginDlg form').get(0).reset();
				hsSite.login(data);
				me.close();
				if ((borderedBox != data.borderedBox) || (onlyTitle != data.onlyTitle)) {
					document.location.reload();
				}
			} else {
				hsSite.dlg.login.showError('password','Hibás e-mail vagy jelszó!');
			}
		},'json');
	},
	
	showError: function(focus, msg, mark) {
		$('#loginMsg').html(msg).show();
		this.getField(focus).focus();
	},
	
	getField: function(field) {
		return $('input[name = '+field+']', this.el);
	},

	checkEmail:function(email) {
		return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email));
	},
	
	toggleInfo: function(){
		var link = $('#toggableInfoLink');
		var info = $('#toggableInfo');
		if (link.hasClass('hideArrow')){
			link.removeClass('hideArrow');
			info.hide();
		}
		else {
			link.addClass('hideArrow');
			info.show();
		}
	},
	
	passwdSend: function() {
		$('#loginMsg').html('').hide();
		$('#passwdInfo', this.el).hide();
		var email = this.getField('email').val();
		if (!email) {
			this.showError('email','Először add meg az e-mail címet, amivel regisztráltál. Ide küldjük az emlékeztetőt.');
			return;
		}
		if (!this.checkEmail(email)) {
			this.showError('email','Hibás e-mail formátum!');
			return;
		}
		var me=this;
		$.post(hsconf.ajax_url + "passwdsend.php", {email:email}, function(ret) {
			if (ret.success) {
				$('#passwdInfo', this.el).show();
			} else {
				switch(ret.error) {
					case 'notexists':
						me.showError('email','Ilyen e-mail címmel még nem regisztráltak a Hírstartra.');
					break;
					case 'limit':
						me.showError('email','Erre a címre több emlékeztetőt nem küldhetsz ma.');
					break;
					default:
						alert('Hiba a küldés során.');
				}
			}
		},'json');	
	}
	
};

hsSite.dlg.reg = {

	parseHistoryHash: function(hash) {
		if (hsSite.Preferences.loggedIn) return false;
		return hsSite.dlgBase.parseHistoryHash.call(this,hash);
	},

	reset: function() {
		$('input:text, input:password', this.el).val('');
		this.errors = [];
		$('.errMsg',this.el).hide();
	},

	onLoad: function() {
		hsSite.dlgBase.onLoad.call(this);
		var me=this;
		$('.backBtn',this.el).click(this.close);
		$('form',this.el).submit(function(e) {
			e.preventDefault();
			me.submit();
		});
		$('.w635 .h1_line:last, .w635 .content:last', this.el).hide();
		this.getField('email').change(function() {
			me.validateEmail(this.value,true);
		});
		this.getField('code').change(function() {
			me.validateCode(this.value,true);
		});
		this.getField('password2').change(function() {
			me.validatePassword();
		});
		this.getField('acceptpolicy').click(function() {
			if (this.checked) {
				me.cleanError('policy');
			}
		});
		$('#captchaImg',this.el).click(function(){
			me.refreshCaptcha();
		});
	},
	
	focus: function() {
		if (hsSite.Preferences.loggedIn) {
			this.close();
			return;
		};
		this.getField('email').focus();
		this.refreshCaptcha();
	},
	
	refreshCaptcha: function() {
		$('#captchaImg').attr('src',hsconf.site_url+'captcha.php?'+9999*Math.random());
		this.getField('code').val('');
	},

	submit: function() {
		var params = {
			email: this.getField('email').val(),
			password: this.getField('password').val(),
			code: this.getField('code').val(),
			act: 'reg'
		};
		this.validateCode(params.code, false);
		this.validatePassword();
		this.validateEmail(params.email, false);
		if (!this.getField('acceptpolicy').attr('checked')) {
			this.markError(false,'Ha nem fogadod el, nem tudunk regisztrálni.','policy');
		}
		if (this.errors.length) return;
		var me = this;
		$.post(hsconf.ajax_url + "reg.php", params, function(data) {
			if (data.success) {
				$('.w635 .h1_line:first, .w635 .content:first', me.el).hide();
				$('.w635 .h1_line:last, .w635 .content:last', me.el).show();
			} else {
				if (data.error == 'userExists') {
					me.markError('email','Ez az e-mail már foglalt!','email');
				}
				else if (data.error == 'userBanned') {
					me.markError('email','Ez az e-mail ki van tiltva!','email');
				}
				else {
					alert('hiba a regisztráció során');
				}
				me.refreshCaptcha();
			}
		},'json');
	},
	
	markError: function(focus, msg, mark) {
		$('._e_'+mark, this.el).html(msg).show();
		this.errors.push(mark);
		this.getField(focus).focus();
	},
	
	cleanError: function(mark) {
		var n=[];
		for (var i = 0; i < this.errors.length; i++) {
			if (this.errors[i] != mark) 
				n.push(this.errors[i]);
		}
		this.errors = n;
		$('._e_'+mark, this.el).hide();
	},
	
	getField: function(field) {
		return $('input[name = '+field+']', this.el);
	},
	
	validatePassword: function() {
		this.cleanError('password');
		var p = this.getField('password').val();
		if (p != this.getField('password2').val()) {
			this.markError('password','A két jelszó nem egyezik!','password');
		}
		if (p.length < 5) {
			this.markError('password','A jelszó legalább 5 karakter legyen!','password');
		}
		if (!p) {
			this.markError('password','Adj meg jelszót!','password');
		}
	},

	validateEmail: function(value, ajax) {
		this.cleanError('email');
		if (this.checkEmail(value)) {
			if (ajax) this.checkEmailExists(value);
		} else {
			this.markError('email','Hibás e-mail formátum!','email');
		}
	},
	
	checkEmail:function(email) {
		return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email));
	},
	
	checkEmailExists:function(email) {
		var me = this;
		$.getJSON(hsconf.ajax_url + "reg.php", {
			act:'chkEmail',
			email:email
		}, function(ret) {
			if (ret.exists) {
				if (ret.exists==2) {
					me.markError('email','Ez az e-mail ki van tiltva!','email');
				}
				else {
					me.markError('email','Ez az e-mail már foglalt!','email');
				}
			}
			if (!ret.valid) {
				me.markError('email','Nem létező e-mail cím!','email');
			}
		});
	},

	validateCode:function(code, ajax) {
		var me = this;
		this.cleanError('code');
		if (code.length < 5) {
			me.markError('code', 'Túl rövid kód!', 'code');
		} else if (ajax) {
			$.getJSON(hsconf.ajax_url + "reg.php", {
				act: 'chkCode',
				code: code
			}, function(ret){
				if (!ret.valid) {
					me.markError('code', 'Rossz kód!', 'code');
				}
			});
		}
	}
	
};

hsSite.dlg.activated = {};
hsSite.dlg.acterror = {};

hsSite.dlg.setHomePage = {
	onLoad: function() {
		hsSite.dlgBase.onLoad.call(this);
		$('.cancelBtn',this.el).click(this.close);
		$('form', this.el).submit(function(e) {
			e.preventDefault();
			hsSite.dlg.setHomePage.submit();
			hsSite.dlg.setHomePage.close();
		});
	},
	
	reset : function() {
		$('#shbm_sub').hide();
		$('#shbm_'+hsconf.site_id).attr('checked',true);
	},
	
	submit: function() {
		var a = $('input[checked]',this.el).attr('value').split(';');
		var l = document.location;
		var url = l.protocol+'//'+l.host+'/'+a[1];
		var id = a[0];
		var t = $('input[type=submit]',this.el).get(0);
		t.style.behavior = 'url(#default#homepage)';
		t.setHomePage(url);
		//TODO: id ajax post
	}
};

hsSite.dlg.ertekeles = {

	getHistoryHash: function() {
		return this.id+';'+this.config.linkId+';'+this.config.boxId;
	},

	parseHistoryHash: function(hash) {
		var a = hash.split(';');
		if (a[0]==this.id) {
			return {
				linkId: a[1],
				boxId: a[2]
			}
		} else return false;
	},
	
	close: function() {
		if (this.backCounterID) {
			clearInterval(this.backCounterID);
			this.backCounterID = null;
		}
		hsSite.dlgBase.close.call(this);
	},
	
	createHandlers: function() {
		var me=this;
		return {
			clickPos: function(e) {
				e.preventDefault();
				me.sendErtekel(true);
			},
			clickNeg: function(e) {
				e.preventDefault();
				me.sendErtekel(false);
			},
			clickSend: function(e) {
				e.preventDefault();
				me.sendReszletez();
			},
			megsemreszl: function(e) {
				e.preventDefault();
				me.reszletezv();
			},
			visszAhirekhez : function(e) {
				e.preventDefault();
				me.visszAhirekhez(); 
			}
		}
	},
	
	onLoad: function() {
		hsSite.dlgBase.onLoad.call(this);
		this.mainEl = $('> div:first',this.el);
		var h = this.createHandlers();
		$('.ertekeles .tetszettAmitOlvastamBtn', this.mainEl).click(h.clickPos);
		$('.ertekeles .nemTetszettAmitOlvastamBtn', this.mainEl).click(h.clickNeg);
		$('.velemenyKuldeseBtn').click(h.clickSend);
		$('.megsemReszletezemBtn').click(h.megsemreszl);
		$('a.visszAhirekhez').click(h.visszAhirekhez);
		this.handlers = h;
	},
	
	focus: function() {
		$('html,body').scrollTop(0);
		$('>:not(div.h1_line)',this.mainEl).hide();
		$('.ertekeles input[type=checkbox]', this.mainEl).attr('checked', false);
		
		/*
		if (!hsSite.Preferences.loggedIn) {
			$('.ertekelesLoginSzukseges', this.mainEl).show();
		} else {
		*/
			$.getJSON(hsconf.ajax_url+'ertekel.php', {
				linkId:this.config.linkId, 
				boxId:this.config.boxId,
				action:'gethir'
			}, function(ret) {
				if (ret.success) {
					hsSite.dlg.ertekeles.hirLoadCB(ret);
				} else {
					hsSite.dlg.ertekeles.ertekelu(ret);
				}
			});
		/*	
		}
		*/
	},
	
	ertekelu: function(hir) {
		this.allas = hir.ert;
		$('>:not(div.h1_line)', this.mainEl).hide();
		$('.marErtekelt', this.mainEl).show();
		this.showAllas($('.marErtekelt b', this.mainEl));
		
	},
	
	hirLoadCB: function(hir) {
		this.hir=hir;
		$('.rovidhir', this.mainEl).html(this.hir.html);
		$('.ertekeles, .rovidhir', this.mainEl).show();
	},
	
	sendErtekel: function(tetszett) {
		this.tetszett = tetszett;
		this.allas = this.hir.ert + ( tetszett ? 1 : -1 );
		var me = this;
		$.getJSON(hsconf.ajax_url+'ertekel.php',{
			linkId:this.hir.id,
			tetszett: tetszett,
			action:'ertekel'
		}, function(ret){
			me.sendErtekelCB(ret);
		});
	},
	
	sendErtekelCB: function() {
		if 	($('.ertekeles input[type=checkbox]', this.mainEl).attr('checked')) {
			this.reszletez();
		} else {
			this.ertekelv();
		}
	},
	
	visszAhirekhez : function(){
		hsSite.dlgMgr.close();
		var target = 'a[rel=hs_' + this.config.linkId + '_' + this.config.boxId + ']:last';
		var $scrollTo = $(target);
		if ($scrollTo.size()>0){
			var top = $scrollTo.offset().top;
			$('html,body').scrollTop(top);
		}					
	},
	
	ertekelv: function() {
		$('>:not(div.h1_line)', this.mainEl).hide();
		$('.koszonjukVelemenyet2', this.mainEl).show();
		
		//ha a hirtarban van, akkor oldalfrissítést végezzen
		if (document.location.pathname.match('hirtar.php')) {
			$('.koszonjukVelemenyet2 a').attr('href', location.href.replace(location.hash, ''));
		} 
		this.showAllas($('.koszonjukVelemenyet2 b', this.mainEl));
		
	},
	
	reszletez: function() {
		$('>:not(div.h1_line)', this.mainEl).hide();
		this.opEl = $('.ertekelesReszletes' + (this.tetszett ? ':first' : ':last'), this.mainEl);
		this.showAllas($('p.eredmeny > b', this.opEl));
		$('input', this.opEl).attr('checked',false);
		this.opEl.show();
	},
	
	reszletezv: function() {
		$('>:not(div.h1_line)', this.mainEl).hide();
		$('.koszonjukVelemenyet', this.mainEl).show();
		if (document.location.pathname.match('hirtar.php')) {
			$('.koszonjukVelemenyet a').attr('href', 'hirtar.php');
		}
		var me=this;
		this.backcount = 4;
		this.backCounter();
		this.backCounterID = setInterval(function() {
			me.backCounter();
		},1000);
	},

	backCounter: function() {
		this.backcount--;
		if (this.backcount>0) {
			$('.koszonjukVelemenyet a.visszAhirekhez b',this.mainEl).html(this.backcount);
		} else {
			this.close();
			if (document.location.pathname.match('hirtar.php')) {
				document.location.reload();
			} else {
				this.visszAhirekhez();
			}
		}
	},
	
	sendReszletez : function () {
		var me = this;
		var options = [];
		$('input[checked]', this.opEl).each(function() {
			options.push(this.value);
		});
		if (!options.length) {
			alert('Legalább egy lehetőséget jelölj be!');
			return;
		}
		$.getJSON(hsconf.ajax_url+'ertekel.php',{
			linkId: this.hir.id,
			action: 'reszletez',
			tetszett: this.tetszett,
			'opts[]': options
		}, function(){
			me.reszletezv();
		});
	},
	
	showAllas:function(el) {
		el.html(this.allas>0 ? 'tetszett' : 'nem tetszett').attr('className', this.allas>0 ? 'greenText':'redText');
	}
	
};

hsSite.dlg.beallitasok = {
	actPage: 1,
	hirtarba: null,
	
	onLoad : function() {
		hsSite.dlgBase.onLoad.call(this);
		$('.modositasokMenteseBtn',this.el).click(this.submit);
		$('.visszaHirekhezBtn',this.el).click(this.close);
		var me=this;
		me.getField('email').blur(function() {
			me.validateEmail(this.value, true);
		});
		me.getField('password').blur(function() {
			me.validatePassword(this.value, true, false);
		});
		me.getField('password_new').blur(function() {
			me.validateNewPassword();
		});
		$('#beallitasok_3 div.inputBoxLeft input').blur(function() {
			me.validateKulcsszo(this.value, this.name);
		});
	},
	
	focus : function() {
		$('input:text, input:password', this.el).val('');
		this.errors = [];
		$('.errMsg', this.el).hide();
		
		if (hsSite.Preferences.loggedIn){
			$('input[name!=email]', this.el).removeAttr('disabled');
			$('input[name=email]', this.el).val(hsSite.Preferences.uemail);
			$('input[name=password]', this.el).val('');
			$('input#'+ (hsSite.Preferences.remember ? 'on' : 'off'), this.el).attr('checked', 'checked');
			$('input#'+ (hsSite.Preferences.linkTarget == '_blank' ? 'blank' : 'self'), this.el).attr('checked', 'checked');
			$('input#'+ (hsSite.Preferences.defaultLayout == 1 ? 'hard' : 'light'), this.el).attr('checked', 'checked');
			$('input#csakcim'+ (hsSite.Preferences.onlyTitle == 1 ? 'on' : 'off'), this.el).attr('checked', 'checked');
			$('input#keret'+ (hsSite.Preferences.borderedBox == 1 ? 'on' : 'off'), this.el).attr('checked', 'checked');
			this.setHirtarbaState();
			var $this = this;
			$('input#all', this.el).click(function(){ $this.setHirtarbaState(1); });
			$('input#negativ', this.el).click(function(){ $this.setHirtarbaState(2); });
			$('input#readed', this.el).click(function(){ $this.setHirtarbaState(3); });
			$('input#hirfigyeles'+ (hsSite.Preferences.hirfigyelo.enabled ? 'on' : 'off'), this.el).attr('checked', 'checked');
			if (hsSite.Preferences.hirfigyelo.periods)
				$.each(hsSite.Preferences.hirfigyelo.periods, function(){
					$('#hf'+ this).check();
				})
			if (hsSite.Preferences.hirfigyelo.kulcsszavak)
				$('#beallitasok_3 div.inputBoxLeft input').each(function(index){
					if (hsSite.Preferences.hirfigyelo.kulcsszavak[index])
						$(this).val(hsSite.Preferences.hirfigyelo.kulcsszavak[index]);
				});
			else
				$('#beallitasok_3 div.inputBoxLeft input').val('');
			
		}
		else {
			var toEnable = ['input[name=openw]','input[name=temakiosztas]','input[name=csakcim]','input[name=keret]'];
			$('.beallitasokMenteseBox a.torles').hide();
			$('input', this.el).attr('disabled', 'disabled');
			$(toEnable.toString(), this.el).removeAttr('disabled');
			$('input#'+ (hsSite.Preferences.linkTarget == '_blank' ? 'blank' : 'self'), this.el).attr('checked', 'checked');
			$('input#'+ (hsSite.Preferences.defaultLayout == 1 ? 'hard' : 'light'), this.el).attr('checked', 'checked');
			$('input#csakcim'+ (hsSite.Preferences.onlyTitle == 1 ? 'on' : 'off'), this.el).attr('checked', 'checked');
			$('input#keret'+ (hsSite.Preferences.borderedBox == 1 ? 'on' : 'off'), this.el).attr('checked', 'checked');			
			$('#beallitasok_2 div.alerter').click(
				function(){
					alert('Ezek a beállítási lehetőségek csak belépett felhasználóink számára elérhetőek.');
					return false;
				}
			);
			this.changePage(2);
		}
		$('.modositasokMenteseBtn, .visszaHirekhezBtn', this.el).removeAttr('disabled');
	},
	
	validateNewPassword: function() {
		this.cleanError('password_new');
		this.validatePassword($('input[name=password]', this.el).val(), false, true);
		var p = this.getField('password_new').val();
		if (p != $('input[name=password_new]', this.el).val()) {
			this.markError('password_new','A két jelszó nem egyezik!','password_new');
			return false;
		}
		if (p.length < 5) {
			this.markError('password_new','A jelszó legalább 5 karakter legyen!','password_new');
			return false;
		}
		if (!p) {
			this.markError('password_new','Adj meg jelszót!','password_new');
			return false;
		}
		return true;
	},
	
	validatePassword: function(password, ajax, haveTo){
		this.cleanError('password');
		password = $.trim(password);
		if (password != '' && ajax) {
			var me = this;
			$.getJSON(hsconf.ajax_url + "setpref.php", {
				act: 'checkPass',
				pass: password
			}, function(ret){
				if (!ret.exists) {
					me.markError('password', 'Nem megfelelő jelszó!', 'password');
				}
			});
		}
		if(password == '' && haveTo)
			this.markError('password', 'Adj meg jelszót!', 'password');
	},

	validateEmail: function(value, ajax) {
		this.cleanError('email');
		if (value != ''){
			if (this.checkEmail(value)) {
				if (ajax) this.checkEmailExists(value);
			} else {
				this.markError('email','Hibás e-mail formátum!','email');
			}
		}
	},
	
	checkEmail:function(email) {
		return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email));
	},
	
	checkEmailExists:function(email) {
		var me = this;
		$.getJSON(hsconf.ajax_url + "reg.php", {
			act:'chkEmail',
			email:email
		}, function(ret) {
			if (ret.exists) {
				if (ret.exists==2) {
					me.markError('email','Ez az e-mail ki van tiltva!','email');
				}
				else {
					me.markError('email','Ez az e-mail már foglalt!','email');
				}
			}
			if (!ret.valid) {
				me.markError('email','Nem létező e-mail cím!','email');
			}
		});
	},
	
	validateKulcsszo: function(kulcsszo, focus){
		this.cleanError('kulcsszo');
		kulcsszo = $.trim(kulcsszo);
		if (kulcsszo != ''){
			var kulcspattern =  /[ ,\.\&\|\'\"]/;
			if (kulcspattern.test(kulcsszo))
				this.markError(focus, 'Figyelem egy mezőbe egy kulcsszót tudsz megadni!', 'kulcsszo');
		}
	},
	
	markError: function(focus, msg, mark) {
		$('._e_'+mark, this.el).html(msg).show();
		this.errors.push(mark);
		this.getField(focus).focus();
	},
	
	cleanError: function(mark) {
		var n=[];
		for (var i = 0; i < this.errors.length; i++) {
			if (this.errors[i] != mark) 
				n.push(this.errors[i]);
		}
		this.errors = n;
		$('._e_'+mark, this.el).hide();
	},
	
	getField: function(field) {
		if (field.indexOf('kulcs') >= 0)
			return $('input[name='+ field +']', this.el);
		switch(field){
			case 'email':
				return $('input[@name="email_new"]', this.el);
			break;
			case 'password':
				return $('input[name=password]', this.el);
			break;
			case 'password_new':
				return $('input[name=password_new2]', this.el);
			break;
		}
	},
	
	setHirtarbaState : function(state){
		var defaultState=false;
		if (!state) {
			defaultState=true;
			state = hsSite.Preferences.hirtarba;
		}
		state = parseInt(state);
		
		var negativInput = $('input#negativ');
		switch(state){
			case 1:
				$('input#all').attr('checked', 'checked');
				negativInput.check('off').attr('disabled', 'disabled');
			break;
			case 2:
				if (defaultState){
					$('input#readed').attr('checked', 'checked');
					negativInput.removeAttr('disabled').check();
				}
				else {
					if (negativInput.attr('checked')==false) {
						state=3;
					}
				}
			break;
			case 3:
				negativInput.removeAttr('disabled');
				if (defaultState) {
					$('input#readed').attr('checked', 'checked');
					negativInput.attr('checked', '');
				}
				else {
					if (negativInput.attr('checked')==true) {
						state=2;	
					}
				}
			break;
		}
		this.hirtarba = state;
	},
	
	changePage: function(index){
		if (!hsSite.Preferences.loggedIn && index != 2) {
			alert('Ezek a beállítási lehetőségek csak belépett felhasználóink számára elérhetőek.');
			return false;
		}
		if (this.actPage != index) {
			$('.bealitasokContent .fulek li a[rel=#'+ this.actPage +']').removeClass('aktiv');
			$('.bealitasokContent .fulek li a[rel=#'+ index +']').addClass('aktiv');
			$('#beallitasok_'+ this.actPage).hide();
			$('#beallitasok_'+ index).show();
			if (index == 4) {
				this.setHirtarbaState();
			}
			this.actPage = index;
		}
	},
	
	getPageData: function(page, ret){
		if (!ret)
			var ret = {};
		switch(page){
			case 1:
				var newMail = $.trim($('input[name=email_new]', this.el).val());
				if (newMail != ''){
					this.validateEmail(newMail);
					ret.email = newMail;
				}
				if ($.trim($('input[name=password_new]', this.el).val()) != ''){
					var password = $('input[name=password]', this.el).val();
					this.validatePassword(password, false, true);
					if (this.validateNewPassword()){
						ret.old_password = password;
						ret.password = $.trim($('input[name=password_new]', this.el).val());
					}
				}
				if (this.errors.length) return false;
			break;
			case 2:
				if ($("input[name=autologin]:checked", this.el).size())
					ret.remember = $("input[name=autologin]:checked", this.el).val();
				ret.linkTarget = $("input[name=openw]:checked", this.el).val();
				ret.defaultLayout = $("input[name=temakiosztas]:checked", this.el).val();
				ret.onlyTitle = $("input[name=csakcim]:checked", this.el).val();
				ret.borderedBox = $("input[name=keret]:checked", this.el).val();
			break;
			case 3:
				ret.hirfigyelo = {
					enabled: $('input#hirfigyeleson:checked').size() ? true : false
				};
				if (ret.hirfigyelo.enabled){
					ret.hirfigyelo.periods = [];
					$('.timeline input:checked').each(function(){
						ret.hirfigyelo.periods.push(this.name +'h');
					});
					ret.hirfigyelo.kulcsszavak = [];
					var val;
					$('.inputBox.inputBoxLeft input').each(function(){
						val = $(this).val();
						if (val != ''){
							ret.hirfigyelo.kulcsszavak.push(val);
						}
					});
				}
				else {
					$('.timeline input').check('off');
					$('.inputBox.inputBoxLeft input').val('');
				}
				ret.hirfigyelo = $.toJSON(ret.hirfigyelo);
			break;
			case 4:
				if (this.hirtarba)
					ret.hirtarba = this.hirtarba;
			break;
		}
		if (!ret.email && hsSite.Preferences.loggedIn) {
			ret.email = hsSite.Preferences.uemail;
		}
		return ret;
	},
	
	regDel: function(){
		$('#regDel, .beallitasokMenteseBox a.torles').hide();
		$.getJSON(hsconf.ajax_url +'regdel.php', {}, function(feedData) {
			if (feedData.error){
				alert('Hiba törént a törlés során!');
			}
			else {
				document.location.href = hsconf.site_url +'logout.php';
			}
		});
	},
	
	submit: function() {
		if (hsSite.Preferences.loggedIn || hsSite.dlg.beallitasok.actPage == 2){
			var datas;
			if (!hsSite.Preferences.loggedIn)
				datas = hsSite.dlg.beallitasok.getPageData(2);
			else {
				for(var i=1;i<5;i++)
					datas = hsSite.dlg.beallitasok.getPageData(i, datas);
			}
			if (datas != false && !datas.error && !hsSite.dlg.beallitasok.errors.length) {
				var borderedBox = hsSite.Preferences.borderedBox;
				var onlyTitle = hsSite.Preferences.onlyTitle;
				hsSite.Preferences.saveChanges(datas, function(ret){
					if (ret.hirfigyelo) {
						hsSite.Preferences.hirfigyelo = eval('('+ ret.hirfigyelo +')');
					}
					if (!ret.error){
						hsSite.dlg.beallitasok.close();
						if ((document.location.pathname.match('hirtar.php') && hsSite.dlg.beallitasok.actPage == 4) || (datas.defaultLayout && datas.defaultLayout != hsSite.layout) || (borderedBox != ret.borderedBox) || (onlyTitle != ret.onlyTitle)) {
							document.location.reload();
						}
					}
					else {
						hsSite.dlg.beallitasok.changePage(1);
						hsSite.dlg.beallitasok.markError(ret.error, ret.errorText, ret.error);
					}
				});
			}
			else {
				hsSite.dlg.beallitasok.changePage(1);
			}
		}
		else
			hsSite.dlg.beallitasok.close();
	}
};

hsSite.dlgBase = {
	
	reset: function() {},
	focus: function() {},
	blur: function() {},
	callback: function(){},
	
	onLoad: function() {
		this.el = $('#'+this.elId);
		if (this.callback) {
			this.callback();	
		};
	},
	
	reopen: function() {
		hsSite.dlgMgr.open(this,true);
	},
	
	open: function(config) {
		this.config = config ? config :{};
		hsSite.dlgMgr.open(this);
	},
	
	toggle: function(config) {
		this.config = config ? config :{};
		hsSite.dlgMgr.toggle(this);
	},
	
	close: function() {
		hsSite.dlgMgr.close();
	},
	
	getHistoryHash: function() {
		return this.id;
	},
	
	parseHistoryHash: function(hash) {
		return this.getHistoryHash()==hash;
	},
	
	appendHistory: function() {
		var hash = this.getHistoryHash();
		if (hash) $.history.load(hash);
		return hash;
	}
	
}

hsSite.dlgMgr = function () {
	var dialogs = [];
	var active = null;
	var htmlLoaded = false;
	var inhistoryCallback = false;
	var stack = [];
	
	function historyCallback(hash) {
		inhistoryCallback = true;
		handleHash(hash);
		inhistoryCallback = false;
	};
	
	function handleHash(hash) {
		var found = false;
		if (hash) {
			$.each(dialogs, function(){
				var c = this.parseHistoryHash(hash);
				if (c) {
					this.open(c);
					found = true;
					return false;
				}
			});
		} 
		if (!found && (!hash || hash.length>2)) {//TODO hash törlése
			hsSite.dlgMgr.close();
		}
	};
	
	function iehack_hash(context) {
		if (!$.browser.mozilla && !$.browser.opera) {
			function hack(e) {
				handleHash(e.target.href.split('#').pop());
			}
			var u = location.href.split('#').shift();
			$('a',context).each(function() {
				var a = this.href.split('#');
				if (a.length=2 && (!a[0] || a[0]==u)) {
					$(this).click(hack);
				}
			});
		}
	}
	
	var _public = {
		
		init : function() {
			for(var name in hsSite.dlg) {
				hsSite.dlg[name] = this.extend(name,hsSite.dlg[name]);
			}
			$.history.init(historyCallback);
			iehack_hash();
		},
		
		extend: function(name, dlg) {
			dlg = $.extend( $.extend({
				id: name,
				elId: name+'Dlg'
			},hsSite.dlgBase), dlg);
			dialogs.push(dlg);
			return dlg;
		},
		
		toggle: function(dlg){
			if (active) {
				if (active != dlg) {
					this.open(dlg);
				}
				else {
					this.close();
				}
			}
			else {
				this.open(dlg);
			}
		},
		
		open: function(dlg, noHistory) {
			if (!inhistoryCallback && !noHistory && dlg.appendHistory()) return;
			if (active==dlg) return;
			if (active) {
				active.blur();
				active.el.hide();
			}
			if (!this.hided) this.hided = $('#contents > :not(#header,#dialogs)').hide();
			function doit() {
				var ndx = $.inArray(dlg,stack);
				if (ndx == -1) {
					dlg.reset();
					stack.push(dlg);
				} else {
					for(var i=stack.length-1;i>ndx;i--) stack.pop();
				}
				dlg.el.show();
				active = dlg;
				dlg.focus();
			}
			if (!htmlLoaded) {
				$('#dialogs').load(hsconf.hirstart_url+'dialogs.html', null, function(){
					htmlLoaded = true;
					$.each(dialogs, function(){
						this.onLoad();
					});
					$('#dialogs > div').hide();
					iehack_hash($('#dialogs'));
					doit();
				});
			} else {
				doit();
			}
		},
		
		close: function(){
			if (!active) return;
			stack.pop();
			if (!stack.length) {
				this.hided.show();
				this.hided = null;
				active.blur();
				active.el.hide();
				active = null;
				if (!inhistoryCallback) $.history.load('');
			} else {
				this.open(stack[stack.length-1]);
			}
		}
	}

	return _public;
	
} ();


function isValidURL(url){
	var RegExp = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
    if(RegExp.test(url)){
        return true;
    }else{
        return false;
    }
} 

hsSite.hirtar = {

	init: function(){
		if ($.cookie('HT_INFO')) 
			$(':not(div#dialogs) div.info.closable').hide();
		else {
			$(':not(div#dialogs) div.info.closable a.close').click(function(){
				$(':not(div#dialogs) div.info.closable').hide();
				$.cookie('HT_INFO', 1, {
					expires: 365
				});
				return false;
			});
		}
	}
}

$.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;
		}
	});
};

hsSite.votes = {
	init: function() {
		$('.vote_archive .rovidhir a').each(function(index){
			$(this).attr('id', 'vote_'+ index).click(function(){
				hsSite.votes.toggleResults('vote_'+ index);
			});
		});
		if ($('#show_results:checked').size())
			$('.vote_archive .rovidhir a').addClass('toggled');
	},
	
	toPage: function(page) {
		document.location.href = $.query.set('page', page);
	},
	
	toggleResults: function(id){
		var selector = '.vote_archive .rovidhir a';
		if (id){
			selector = '#'+ id;
			$(selector).parent().siblings('.results').toggle();
		}
		else {
			if (!$('#show_results:checked').size()){
				$(selector).addClass('toggled');
				$('.vote_archive div.rovidhir div.results').show();
			}
			else {
				$(selector).removeClass('toggled');
				$('.vote_archive div.rovidhir div.results').hide();
			}
			hsSite.pToggle.toggle('show_results', '.vote_archive div.rovidhir div.results');
		}
		$(selector).toggleClass('toggled');
	}
	
}

hsSite.webes = {
	toPage: function(page) {
		document.location.href = $.query.set('page', page);
	}
};

var $adIFRAME;
function hideIFRAME(hide){
	if (!$adIFRAME){
		$adIFRAME = $('#leftContent>div:first() iframe'); 
	}
	$adIFRAME.css('visibility', hide ? 'hidden' : 'visible');
};