$(document).ready(function() {
	
	ie6=$.browser.msie && ($.browser.version == "6.0") && !window.XMLHttpRequest;
	
	$.ajaxSetup ({ cache: false })
	
	//init cufón fonts
	Cufon.replace('body.home h3, body.watch h3, #nav .items a, body.common h3',{ hover:true});
	
	//init community
	$("#community").mouseover(function() {
		$("#community .comm").css({"backgroundColor":"#f79312", 'color':'#ffffff'});
		$("#community .communitypanel").css({'visibility':'visible'});
	});
	$("#community").mouseleave(function() { 
		$("#community .comm").css({"backgroundColor":"transparent",'color':'#8C8C8C'});
		$("#community .communitypanel").css({'visibility':'hidden'});
	});
	
	//init login
	$("#login").mouseover(function() {
		$("#login .reg").css({"backgroundColor":"#f79312"});
		$("#login .loginpanel").css({'visibility':'visible'});
	});
	$("#login").mouseleave(function() { 
		$("#login .reg").css({"backgroundColor":"transparent"});
		$("#login .loginpanel").css({'visibility':'hidden'});
	});
	$("#login .rememberblock").hide();
	$("#login .loginblock .submit").click(function(e) {
		e.preventDefault();
		$.post("index.php", {username:$("#login .loginblock .username").val(),password:$("#login .loginblock .password").val()}, function(data) {
			if (data.error == 0) {
				location.reload(true);
			} else if (data.error == 1) {
				$("#login .loginblock .username").focus();
				showAlert('Hibás e-mail cím vagy felhasználónév. Kérjük, írja be adatait újra.');
			}
		}, "json");
	});
	$("#login .loginblock input").keypress(function (e) {
 		 if (e.which == 13) $("#login .loginblock .submit").trigger('click');
  	});
	$("#login .loginblock .remember_link").click(function(e) {
		e.preventDefault();
		$("#login .rememberblock").slideToggle(200);
	});
	$("#login .rememberblock .submit").click(function(e) {
		e.preventDefault();
		$.post("index.php", {email:$("#login .rememberblock .email").val()}, function(data) {
			if (data.error == 0) {
				showAlert('A jelszót a megadott e-mail címre elküldtük. Kérjük, ellenőrizze postafiókját!');
			} else if (data.error == 1) {
				$("#login .rememberblock .email").focus();
				showAlert('Nincs ilyen email cím!');
			} else {
				showAlert('A jelszó továbbításakor hiba lépett fel. Kérjük, próbálkozzon később!');
			}
		}, "json");
	});
	
	//init registration
	$("#registration").mouseover(function() {
		$("#registration .reg").css({"backgroundColor":"#f79312"});
		$("#registration .regpanel").css({'visibility':'visible'});
	});
	$("#registration").mouseleave(function() { 
		$("#registration .reg").css({"backgroundColor":"transparent"});
		$("#registration .regpanel").css({'visibility':'hidden'});
	});
	$("#registration .submit").click(function(e) {
		e.preventDefault();
		if ($('#registration .username').val() == "") {
			showAlert('Kérjük, adjon meg egy felhasználónevet!');
			$('#registration .username').focus();
			return;
		}
		if ($('#registration .name').val() == "") {
			showAlert('Kérjük, adja meg teljes nevét!');
			$('#registration .name').focus();
			return;
		}
		if ($('#registration .pass').val() == "") {
			showAlert('Kérjük, adja meg jelszavát!'); 
			$('#registration .pass').focus();
			return;
		}
		if ($('#registration .pass').val() != $('#registration .passagain').val()) {
			showAlert('A két jelszó nem azonos. Kérjük, adja meg újra!'); 
			$('#registration .pass').focus();
			return;
		}
		if (!isValidEmailAddress($('#registration .email').val())) {
			showAlert('Az email cím hibás. Kérjük, adja meg újra!');
			$('#registration .email').focus();
			return;
		}
		
		if (!$('#registration .check').is(':checked')) {
			showAlert('A felhasználási feltételek elfogadása nélkül nem tudjuk rögzíteni adatait!');
			return;
		}
		$.post("index.php", {reg:'1',username:$('#registration .username').val(),name:$('#registration .name').val(),password:$('#registration .pass').val(),email:$('#registration .email').val()}, function(data) {
			if (data.error == 0) {
				showAlert('Köszönjük! A regisztrációja megerősítéséhez szükséges linket elküldtük e-mail címére!');
			} else if (data.error == 1) {
				showAlert('Ez a felhasználónév már szerepel adatbázisunkban. Kérjük, válasszon másikat.');
			}
		}, "json");
	});
	$("#registration input").keypress(function (e) {
 		 if (e.which == 13) $("#registration .submit").trigger('click');
  	});
  	
  	$(".reglink").click(function(e){ e.preventDefault(); $.scrollTo( '#header', 400); $("#registration").trigger("mouseover");});
  	$(".loginlink").click(function(e){ e.preventDefault(); $.scrollTo( '#header', 400); $("#login").trigger("mouseover");});
  	
	
	
	//init header navigation
	actmenu = 0;
	$("#nav .menu").css({'height':'0px','visibility':'visible'});
	$("#nav .items a").mouseover(function() {
		var id = $(this).attr('id');
		$("#nav .items a").removeClass('hover');
		$(this).addClass('hover');
		if (actmenu && $("#"+actmenu+"_menu").length != 0) $("#"+actmenu+"_menu").stop(true).animate({'height':'0px'},200);
		actmenu = id;
		if ($("#"+actmenu+"_menu").length != 0) {
			$("#"+actmenu+"_menu").stop(true).animate({'padding-left':'0'},200).animate({'height':'165px'},100);
		}
	});
	$('#nav').mouseleave(function() {
		$("#nav .items a").removeClass('hover');
		Cufon.replace('#nav .items a');
		if (actmenu) $("#"+actmenu+"_menu").stop(true).animate({'height':'0px'},200);
	});
	$('#nav .menu_nav a').click(function(e) {
		e.preventDefault();
		var url = $(this).attr('href').split("?");
		$(this).parents(".menu").find(".cols").load(url[0],url[1]);
	});
	$('#nav .search a').click(function(e) {
		e.preventDefault();
		location.href = 'search.php?q='+encodeURI($('#search_input').val());
	});
	$("#search_input").keypress(function (e) {
 		 if (e.which == 13) $('#nav .search a').trigger('click');
  	});
  	
  	
	
	//tags block init
	getTags = function(v) {
		var new_list = "";
		if (typeof(v) != "undefined") new_list="gettags="+v+"&";
		var a = $('#tags select').val().split("|");
		$(".tags_wrapper .tags").animate({'opacity':0},100).load("index.php",new_list+"tagsfield="+a[0]+"&sort="+a[1], function() {$(".tags_wrapper .tags").animate({'opacity':1},200)});
	}
	$('#tags .tabs a').click(function(e) {
		e.preventDefault();
		$('#tags .tabs a').removeClass('selected');
		$(this).addClass('selected');
		getTags($(this).attr('id').split("_")[2])
	});
	$('#tags select').change(function() {getTags()});
	$("#tags select").styleSelect({optionsWidth: 1, speed: 200});
	
	//init spotlight
	initSpotlightItems();
  	
  	//init alertmsg 
  	initAlertMsg();
	//GLOBAL init end
	
	//set common pages height
	if ($('#content').length > 0) {
		if ($('#content').height() < $(window).height() - 327) $('#content').css({'height': $(window).height() - 327 +"px"});
	}
	
	
	//HOME init	
	if ($('body.home').length > 0) {
		swfobject.embedSWF("/flash/timemachine.swf?rnd="+Math.round(Math.random()*1000000000), "timemachine_flash", "100%", "100%", "9.0.115.0", "/flash/expressInstall.swf", {}, {menu:'false' , AllowScriptAccess:'always', wmode:'opaque',bgcolor:'#0F0F0F'}, { id:'timemachine_flash'});
	}
	//HOME init end
	
	
	//SEARCH init
	if ($('body.search').length > 0) {
		//init search item
		$(".search_item .tags").css({'margin-top':(120-$(".search_item .tags").height())/2});
		
		//footer positioning on search page
		$('.pager_container').css('visibility','visible');
		$(window).scroll(footerPositioning);
		$(window).resize(footerPositioning);
		footerPositioning();
		
		//add select skin
		$(".pager_container select").styleSelect({optionsPos: 'up'});
		$(".search_header select").styleSelect({optionsWidth: 1, speed: 200});
		$(".search_header select").change(function() {
			location.href="search.php?ord="+$(this).val()+$(this).attr('title');
		});
	}
	//SEARCH init end
	
	
	//WATCH init
	if ($('body.watch').length > 0) {
	
		//add block close button behavior
		$('h3 span.close').click(function() {
			$(this).parent().parent().find('.wrapper_content').animate({'height':'toggle'},300);
			if ($(this).hasClass('close')) {
				$(this).removeClass("close");
				$(this).addClass("open");
			} else {
				$(this).removeClass("open");
				$(this).addClass("close");
			};
		});
		
		
		onTagsLoaded();
		$('#filmtags input').val('Új címke hozzáadása');
		$('#filmtags input').autocomplete({serviceUrl:'tag_autocomplete.php', minChars:1, width:145, zIndex: 300, params: { category:5 }});
		$('#filmtags input').focus(function() {if ($(this).val() == 'Új címke hozzáadása') $(this).val("");});
		$('#filmtags input').blur(function() {if ($(this).val() == "") $(this).val('Új címke hozzáadása')});
		$('#filmtags .add_tag .button').click(function(e) {
			var t =$('#filmtags input').val();
			if (t == "" || t == "Új címke hozzáadása") {
				showAlert("A címke mezője üres!");
				$('#filmtags input').focus();
				return;
			}
			var fid = $('#filmtags input').attr('id').split("_")[1];
			$.post("watch.php", {tag:t,film_id:fid}, function(data) {
				if (data.error == 0) {
					$("#filmtags .tags_list").load("watch.php","id="+fid+"&at=1",onTagsLoaded);
				} else if (data.error == 3) {
					showAlert('Ezt a címkét már hozzárendelték a filmhírhez!');
				} else {
					showAlert('Nincs jogosultsága az címke hozzáadásához!');
				}
			}, "json");
		});
		$("#filmtags .add_tag input").keypress(function (e) {
 			if (e.which == 13) $("#filmtags .add_tag .button").trigger('click');
  		});
		
		
		onCommentsLoaded();
		$('.comment_input .submit').click(function(e) {
			e.preventDefault();
			var msg = $('.comment_input textarea').val();
			if (msg == "") {
				showAlert("A hozzászólás mezője üres!");
				return;
			}
			var fid = $('.comment_input textarea').attr('id').split("_")[1];
			$.post("watch.php", {message:msg,film_id:fid}, function(data) {
				if (data.error == 0) {
					var fid = $('.comment_input textarea').attr('id').split("_")[1];
					$(".wrapper_comments").load("watch.php","id="+fid+"&page=0&ac=1",onCommentsLoaded);
					$('.comment_input textarea').val("");
					limitChars($(this), 1000, $('.comment_input .textarea_title'));
				} else {
					showAlert('Nincs jogosultsága az üzenet törléséhez!');
				}
			}, "json");
		});
		
		$('.comment_input textarea').keyup(function(){
 			limitChars($(this), 1000, $('.comment_input .textarea_title'));
 		});
 		
 		if (playerStatus == 1) {
 			$('#player_flash').flash({  
 				swf: "/flash/player.swf?rnd="+Math.round(Math.random()*1000000000),
 				width: 465,
 				height: 350,
 				params: {menu:'false' , AllowScriptAccess:'always', wmode:'opaque', bgcolor:'#000000', AllowFullscreen:'true' }, 
 				flashvars: playerVars
 			});
 		}
 				
		//add tooltip
		if ($(".tooltip").length > 0) $(".tooltip").toolTip();
		
		//add share links
		$("#forwardpanel .panel_wrapper").css({'visibility':'visible'}).fadeOut(0);
		$("#forwardpanel").mouseover(function(e) { $(this).find(".panel_wrapper").fadeIn(100); });
		$("#forwardpanel").mouseleave(function(e) { $(this).find(".panel_wrapper").fadeOut(200); });
		$("#forwardpanel textarea").click(function() {$(this).select();});
		
		$("#embedpanel .panel_wrapper").css({'visibility':'visible'}).slideUp(0);
		$("#embedpanel").mouseover(function(e) { $(this).find(".panel_wrapper").fadeIn(100); });
		$("#embedpanel").mouseleave(function(e) { $(this).find(".panel_wrapper").fadeOut(200); });
		$("#embedpanel textarea").click(function() {$(this).select();});
		
		$(".twitter").click(function(e) {
			e.preventDefault();
			var fid = $('.sharing').attr('id').split("_")[1];
			$.get("watch.php","share=1&id="+fid);
			msgContent = 'Ezt látni kell!: http://filmhiradok.nava.hu/watch.php?id='+fid;
			window.open("http://twitter.com/home?status="+msgContent);
		});
		
		$(".facebook").click(function(e) {
			e.preventDefault();
			var fid = $('.sharing').attr('id').split("_")[1];
			$.get("watch.php","share=1&id="+fid);
			msgContent = 'u='+escape('http://filmhiradok.nava.hu/watch.php?id='+fid)+'&t='+escape('Mutatok valamit…');
			window.open("http://www.facebook.com/sharer.php?"+msgContent);
		});
		
		$(".iwiw").click(function(e) {
			e.preventDefault();
			var fid = $('.sharing').attr('id').split("_")[1];
			$.get("watch.php","share=1&id="+fid);
			msgContent = 'u='+escape('http://filmhiradok.nava.hu/watch.php?id='+fid)+'&t='+escape('Ezt látni kell!');
			window.open("http://iwiw.hu/pages/share/share.jsp?"+msgContent);
		});
				
	}
	//WATCH init end

});


function initSpotlightItems() {
	$("#spotlight .item").hover(
		function () {
			$(this).find('.b').stop().animate({"opacity": "1"}, 100);
			$(this).find('.a').stop().animate({"opacity": "0"}, 100);
			$(this).find('.title').stop().animate({color:'#f79312'},100);
		}, 
		function () {
			$(this).find('.b').stop().animate({"opacity": "0"}, 200);
			$(this).find('.a').stop().animate({"opacity": "1"}, 200);
			$(this).find('.title').stop().animate({color:'white'},200);
		}
	);
	$("#spotlight .item .img .b").css({'opacity':0});
	$("#spotlight .item .img .a").css({'opacity':1});
}

function initAlertMsg() {
	$('#alertmsg').css({'opacity':0});
	if  (ie6) {
		$('#alertmsg').css({'position':'absolute'});
		$(window).scroll(function() {
			$('#alertmsg').css({'top':$(window).scrollTop()+"px"});
		});
	}
}

function showAlert(text) {
	$('#alertmsg .wrapper').text(text);
	$('#alertmsg').stop(true).animate({'height':39,'opacity':1},300).animate({'left':0},3000).animate({'height':0,'opacity':0},300);
}

function footerPositioning() {
	var pager = $('body.search .pager_container');
	var ph = pager.height();
	var h = $(window).scrollTop()+$(window).height()-ph;
	if ($('.search_items').height() < $(window).height() - 381) $('.search_items').css({'height': $(window).height() - 381 +"px"}); 
	var ft = $('#footer').offset().top;
	h = h < ft-ph ? h : ft-ph;
	if  (ie6 || h == ft-ph) {
		$('body.search .pager_container').css({'position':'absolute','top':h+'px','left':'0px'});
		return;
	} else {
		$('body.search .pager_container').css({'position':'fixed','top':$(window).height()-ph+'px'});
	}
}

function initCommentDelButtons(e) {
	e.preventDefault();
	var p = confirm("Biztosan törölni szeretné a hozzászólást?");
	if (p) {
		var msgId = $(this).attr('href').split('delmsg=')[1];
		$.get("watch.php", {'delmsg':msgId}, function(data) {
			if (data.error == 0) {
				var fid = $('.comment_input textarea').attr('id').split("_")[1];
				$(".wrapper_comments").load("watch.php","id="+fid+"&page=0&ac=1",onCommentsLoaded);
			} else {
				showAlert('Nincs jogosultsága az üzenetküldéshez!');
			}
		}, "json");
	}
}

function initTagDelButtons(e) {
	e.preventDefault();
	var p = confirm("Biztosan törölni szeretné a címkét?");
	if (p) {
		var msgId = $(this).attr('href').split('deltag=')[1];
		$.get("watch.php", {'deltag':msgId}, function(data) {
			if (data.error == 0) {
				var fid = $('#filmtags input').attr('id').split("_")[1];
				$("#filmtags .tags_list").load("watch.php","id="+fid+"&at=1",onTagsLoaded);
			} else {
				showAlert('Nincs jogosultsága az üzenetküldéshez!');
			}
		}, "json");
	}
}


function onTagsLoaded () {
	$("#filmtags a.tagdelete").click(initTagDelButtons);
}

function onCommentsLoaded() {
	$("#comments select").styleSelect({optionsWidth: 1, speed: 300});
	$("#comments select").change(onCommentsPagerChange);
	$("#comments .pager a.left, #comments .pager a.right").click(onCommentsPagerClick);
	$("#comments a.msgdelete").click(initCommentDelButtons);
} 
	
function onCommentsPagerChange() {
	var fid = $('.comment_input textarea').attr('id').split("_")[1];
	$(".wrapper_comments").load("watch.php","id="+fid+"&page="+$(this).val()+"&ac=1",onCommentsLoaded);
}

function onCommentsPagerClick(e) {
	e.preventDefault();
	var vars = $(this).attr('href').split("?")[1];
	$(".wrapper_comments").load("watch.php",vars+"&ac=1",onCommentsLoaded);	
}

function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

function limitChars(textarea, limit, infodiv) {
	var text = textarea.val();	
	var textlength = text.length;
	if(textlength > limit-1) {
		showAlert('Egy hozzászólás legfeljebb '+limit+' karakteres lehet. Kérjük, fogalmazzon tömörebben!')
		infodiv.html('<strong>Új hozzászólás</strong> ('+limit+'/'+textlength+' karakter)');
		textarea.val(text.substr(0,limit-1));
		return false;
	} else {
		infodiv.html('<strong>Új hozzászólás</strong> ('+limit+'/'+textlength+' karakter)');
		return true;
	}
}