// CONFIG
cRefreshTodayTimeout = 45000;

// Flash message
function flashMessage(message) {
	$(".message").slideUp('slow');
	$("#content").prepend("<div class='message' style='display: none'>"+message+"</div>");
	$(".message:first").slideDown('slow');
}

// INFOBOX

function showInfo_loaded(data) {
	var wHeight = $(window).height();
	var wScrollTop = $(window).scrollTop();
	var pos = InfoBox.position();
	var height = InfoBox.height()+18; //18px border
	//alert(wHeight);
	//alert(wScrollTop);
	if (pos.top+height > wHeight + wScrollTop) { //repos if not fit in browser
		InfoBox.css({'top': wScrollTop+wHeight-height})
	}
}

showInfoTimer = undefined;
function randurl() {
	return "&rev="+mediarev;
}

// SearchFormFocus
function searchformfocus(e) {
	var field = $("#searchforminput");
	var value = field.val();
	
	if (e.type == "click" || e.type == "select" || e.type == "focus") { //make "Gyorskereses..." text gone
		if (value == "Keresés...") field.val("");
		field.removeClass("inactive");
	} else if (e.type == "blur") {
		if (value == "") {
			field.val("Keresés...");
			field.addClass("inactive");
		}
	}
}

// MovieInfo
function showMovieInfo(e) {
	var obj = this;
	var imgobj = $(this).children(":first");
	imgobj.addClass("IStar");
	showInfoTimer = setTimeout(function () {showMovieInfo_delayed.apply(obj, new Array(e))}, 200);
}

function showMovieInfo_delayed(e) {
	var id = $(this).attr("href").replace(/[^0-9]*/, "");
	var pos = $(this).children(":first").position();
	InfoBox.css({'left': pos.left+17, 'top': pos.top, 'display': 'block', 'height': 'auto', 'width': '350px'})
	InfoBoxRight.AbortLoad("/Db/Movie?id="+id+"&format=ajax"+randurl(), showInfo_loaded);
}

function clickMovieInfo(e) {
	if (curuserId == 0) {
		flashMessage('A filmek megjelöléséhez <img height="12" width="12" class="spr LoginIcon" src="/media/img/null.png"/><a href="/User/Login"><b>be kell jelentkezned</b></a> !');
		return false;
	}
	var id = $(this).attr("href").replace(/[^0-9]*/, "");
	var imgobj = $(this).children(":first");
	if (imgobj.hasClass("IStarA")) {
		$.post("/Db/MovieMark", {action: "remove", id: id});
		imgobj.removeClass("IStarA");
	} else {
		$.post("/Db/MovieMark", {action: "add", id: id});
		imgobj.addClass("IStarA");
	}
	return false;
}


//SerieInfo
function showSerieInfo(e) {
	var obj = this;
	if ($(this).hasClass("TvSerieI")) {
		var imgobj = $(this).children(":first");
		imgobj.addClass("IStar");
	}
	showInfoTimer = setTimeout(function () {showSerieInfo_delayed.apply(obj, new Array(e))}, 200);
}

function showSerieInfo_delayed(e) {
	var id = $(this).attr("href").replace(/[^0-9]*/, "");
	var pos = $(this).children(":first").position();
	var left = pos.left+17;
	var top = pos.top;
	var setingsBoxParent = $(this).parents("#SettingsBoxDiv");
	if (setingsBoxParent.length) {
		var settingsBoxPos = $(setingsBoxParent[0]).position();
		left += settingsBoxPos.left;
		top += settingsBoxPos.top;
	}
	InfoBox.css({'left': left, 'top': top, 'display': 'block', 'height': 'auto', 'width': '200px'})
	if ($(this).hasClass("TvSerieI"))
		InfoBoxRight.AbortLoad("/Db/Serie?tvserieid="+id+"&format=ajax"+randurl(), showInfo_loaded);
	else
		InfoBoxRight.AbortLoad("/Db/Serie?id="+id+"&format=ajax"+randurl(), showInfo_loaded);
}


function hideInfo(e) {
	var imgobj = $(this).children(":first");
	imgobj.removeClass("IStar");
	InfoBox.css({'display': 'none', 'height': '1px'});
	InfoBoxRight.html("");
	clearTimeout(showInfoTimer);
}

function clickSerieInfo(e) {
	if (curuserId == 0) {
		flashMessage('A sorozatok megjelöléséhez <img height="12" width="12" class="spr LoginIcon" src="/media/img/null.png"/><a href="/User/Login"><b>be kell jelentkezned</b></a> !');
		return false;
	}
	var id = $(this).attr("href").replace(/[^0-9]*/, "");
	var imgobj = $(this).children(":first");
	if (imgobj.hasClass("IStarA")) {
		$.post("/Db/SerieMark", {action: "remove", id: id});
		imgobj.removeClass("IStarA");
	} else {
		$.post("/Db/SerieMark", {action: "add", id: id});
		imgobj.addClass("IStarA");
	}
	return false;
}

// SETTINGSBOX

function filterTable(e) {
	s = (new Date).getTime();
	
	var field = $("#FilterListSearchField");
	var value = field.val();
	//var searchExp = new RegExp("\b"+value+"[^>]*</label\b", "i");
	var searchExp = new RegExp(value+"[^>]*</label", "mi");
	if (e.type == "keyup") { //filter table
		var found = 0;
		$("#FilterListTable tr").each(function (i) { //loop the rows
			if (searchExp.test(this.innerHTML)) {
				this.style.display = "";
				found++;
			} else this.style.display = "none"; //if not found hide it
		});
		
		var display = $("#FilterListSearchDisplay")
		if (value == "") $("#FilterListSearchDisplay").fadeOut(); //hide search x button
		else display.fadeIn();
		$("span", display).html(found);
	} else if (e.type == "click" || e.type == "select" || e.type == "focus") { //make "Gyorskereses..." text gone
		if (value == "Gyorskeresés...") field.val("");
		field.removeClass("inactive");
	} else if (e.type == "blur") {
		if (value == "") {
			field.val("Gyorskeresés...");
			field.addClass("inactive");
			$("#FilterListSearchDisplay").fadeOut();
		}
	}
	
	$("#jsinit").html((new Date).getTime()-s);
}

function filterTable_cleanSearch() {
	var field = $("#FilterListSearchField");
	field.val("");
	field.trigger("keyup");
	field.trigger("blur");
	return false;
}

contenturl = "";
function submitSettings_loaded() {
	var form = this;
	if (contenturl != "") {
		$("#content").AbortLoad(contenturl+randurl(), function () { refreshTodayTimer = setTimeout(refreshToday, cRefreshTodayTimeout) });
	}
	if (form.attr("aftersubmit")) {
		eval(form.attr("aftersubmit"));
	}
}

submitSettingsTimer = undefined;
function submitSettings(e) {
	obj = this;
	clearInterval(submitSettingsTimer);
	submitSettingsTimer = setTimeout(function () {submitSettings_delayed.apply(obj, new Array(e))}, 1000);
}

function submitSettings_delayed(e) {
	var form = $(this).parents('form:first');
	clearTimeout(refreshTodayTimer); 
	$("#SettingsBoxContentDiv").AbortPost(form.attr("action"), form.serialize(), function() {submitSettings_loaded.apply(form)});
}

function settings_loaded() {
	$("#SettingsBoxContentDiv select").each(function (i) { //bind submit to input changes
		$(this).bind("change", submitSettings);
	});
	$("#SettingsBoxContentDiv input").each(function (i) { //bind submit to input changes
		$(this).bind($.browser.msie ? "click" : "change", submitSettings);
	});
	$("#FilterListSearchField").unbind($.browser.msie ? "click" : "change"); //dont submit on quicksearch
	$("#FilterListSearchField").bind("keyup click select focus blur", filterTable);
	//$("#FilterListSearchField").focus();
}

function loadSettingsTab(url) {
	var SettingsBoxContent = $("#SettingsBoxContentDiv");
	$(".SettingsTab li a").css("cursor", "wait");
	SettingsBoxContent.load(url, '', settings_loaded);
}

function clickSettings(obj, title, url, contenturl_param, width) {
	if (width == null) width = 360; //default width
	contenturl = contenturl_param; //make it global
	var SettingsBox = $("#SettingsBoxDiv");
	var SettingsBoxHead = $("#SettingsBoxHeadDiv");
	var SettingsBoxContent = $("#SettingsBoxContentDiv");
	if (SettingsBox.css('display') == 'block') return hideSettings(); //if visible hide it
	var eobj = $(obj);
	var pos = eobj.position();
	SettingsBox.css({'left': pos.left-width+eobj.width(), 'top': pos.top+17, 'width': width, 'display': 'block', 'height': 'auto'});
	//<div class='FormFoot'><div class='action submit'><input type=button value='Mentés'/><input style='margin-left: 5px' type=button value='Mégse'/></div>
	SettingsBoxHead.html("<h2 style='float: right' id='SettingsClose'><b style='display: block'><a href='#' style='color:white; text-transform: none' onClick='return hideSettings()'>x</a></b></h2><h2 style='padding-top: 5px'><b>"+title+"</b></h2>");
	SettingsBoxContent.load(url, '', settings_loaded);
	return false;
}

function hideSettings() {
	var SettingsBox = $("#SettingsBoxDiv");
	var SettingsBoxContent = $("#SettingsBoxContentDiv");
	SettingsBox.css({'display': 'none'});
	SettingsBoxContent.html("");
	return false;
}

// REFRESHTODAY
function refreshToday() {
	if (pageType == 'TvMovies') url = "/Tv/Filmek/Napi?format=ajax"+randurl();
	if (pageType == 'TvSeries') url = "/Tv/Sorozatok/Napi?format=ajax"+randurl();
	$("#TvDay1").AbortLoad(url);
	refreshTodayTimer = setTimeout(refreshToday, cRefreshTodayTimeout);
}

// ONLOAD

if (window.pageType != undefined) $(document).ready(function() {
	s = (new Date).getTime();
	if (pageType == 'TvMovies' || pageType == 'DvdReleases' || pageType == 'MovieReleases') { //add infobox
		//INFOBOX
		$("body").append("<div class='InfoBox PopupBox' id='InfoBoxDiv'><div id='InfoBoxLeftDiv'></div><div id='InfoBoxRightDiv'></div></div>");
		$(".MovieI").live("mouseover", showMovieInfo).live("mouseout", hideInfo).live("click", clickMovieInfo);
		//put them to global
		InfoBox = $("#InfoBoxDiv"); 
		InfoBoxLeft = $("#InfoBoxLeftDiv"); 
		InfoBoxRight = $("#InfoBoxRightDiv"); 
	}
	if (pageType == 'TvSeries') { //add infobox
		$("body").append("<div class='InfoBox PopupBox' id='InfoBoxDiv'><div id='InfoBoxLeftDiv'></div><div id='InfoBoxRightDiv'></div></div>");
		$(".SerieI").live("mouseover", showSerieInfo).live("mouseout", hideInfo);
		$(".TvSerieI").live("mouseover", showSerieInfo).live("mouseout", hideInfo).live("click", clickSerieInfo);
		//put them to global
		InfoBox = $("#InfoBoxDiv"); 
		InfoBoxLeft = $("#InfoBoxLeftDiv"); 
		InfoBoxRight = $("#InfoBoxRightDiv"); 
	}
	if (pageType == 'TvMovies' || pageType == 'TvSeries') {
		//SETTINGSBOX
		$("body").append("<div class='SettingsBox PopupBox' id='SettingsBoxDiv'><div id='SettingsBoxInnerDiv'> <div id='SettingsBoxHeadDiv'></div> <div id='SettingsBoxContentDiv'></div> </div></div>");
		//REFRESHER
		refreshTodayTimer = setTimeout(refreshToday, cRefreshTodayTimeout);
	}
	//searchforminput = $("#searchforminput");
	//searchforminput.bind("click select focus blur", searchformfocus);
	
	$("#jsinit").html((new Date).getTime()-s);
});

// LINK TO POST FORM

function submitLink(url, params) {
	f = document.createElement('form');
	f.style.display = 'none';
	$("body").append(f);
	f.method = 'POST';
	if (typeof url == 'string' && url != '') {
		f.action = url;
	};
	if (!params) params = new Array();
	jQuery.each(params, function(name, value) {
		var input = document.createElement("input");
		input.setAttribute("type", "hidden");
		input.setAttribute("name", name);
		input.setAttribute("value", value);
		f.appendChild(input);
	});
	f.submit();	
}

// PAUSE

$.fn.pause = function(milli,type) {
	milli = milli || 1000;
	type = type || "fx";
	return this.queue(type,function(){
		var self = this;
		setTimeout(function(){
			$.dequeue(self);
		},milli);
	});
};

$.fn.clearQueue = $.fn.unpause = function(type) {
	return this.each(function(){
		type = type || "fx";
		if(this.queue && this.queue[type]) {
			this.queue[type].length = 0;
		}
	});
};

// AbortAndLoad JQUERY extension

abortLoads = [];

(function ($) {
	$.fn.AbortLoad = function (url, onDone) { //stops ajax loads to this html elements and load a new
		var id = this.attr("id");
		var obj = this;
		this.css("cursor", "wait");
		if (abortLoads[id]) {
			abortLoads[id].abort();
			delete abortLoads[id];
		}

		abortLoads[id] = $.get(url, "", function (data) {
			delete abortLoads[id];
			obj.html(data);
			obj.css("cursor", "auto");
			if (onDone) onDone.apply(obj, new Array(data));
		});
	};
	$.fn.AbortPost = function (url, postdata, onDone) { //stops ajax posts to this html element and post a new one
		var id = this.attr("id");
		var obj = this;
		this.css("cursor", "wait");
		if (abortLoads[id]) {
			abortLoads[id].abort();
			delete abortLoads[id];
		}

		abortLoads[id] = $.post(url, postdata, function (data) {
			delete abortLoads[id];
			obj.css("cursor", "auto");
			if (onDone) onDone.apply(obj, new Array(data));
		});
	};
})(jQuery);