var Ajax_HandlerURL		= '/res/php/Ajax.php';
var Ajax_Animation		= Lng[0]["System"]["Animation"];
var Ajax_Loading		= Lng[0]["System"]["Loading"];
var Ajax_Error			= Lng[0]["System"]["Error"];
var Ajax_CurrentMod		= '';
var Interval_Count		= '';
var ModuleHistory		= new Array();
if (QueryData == undefined)
var QueryData			= 'KO';
var InitMod				= new Object();

function LoadPlayer(LinkID) {
	$('#PlayerContent').html('<br><br><center>' + Ajax_Animation + '</center><br><br>');

	$.ajax({type: "POST", url: Ajax_HandlerURL, dataType: "json",
		data: "Request=GetPlayer&ID=" + LinkID,
		success: function(Response) {

			//> Stammdaten ersetzen
			$('.ValueC:first').html(Response.Block['Player'].Data['Player'].UserName);
			$('.SeriesTitle').html(Response.Block['Player'].Data['Player'].Headline);
			$('#RSentence').html(Response.Block['Player'].Data['Player'].RSentence);

			//> Player parsen und ersetzen
			ParsedHTML = Response.Block['Player'].Template.process(Response.Block['Player'].Data);
			var SubSelection = $(".PlayerSubSelection").html();
			$("#StreamArea").replaceWith(ParsedHTML);
			$(".PlayerSubSelection").html(SubSelection);

		}
	});
}

function RemoveComment(CommentID) {
	$.ajax({type: "POST", url: Ajax_HandlerURL, dataType: "text",
		data: "Request=RemoveComment&ID=" + CommentID,
		success: function(Response) {
   			$('#UsrComment_' + CommentID).remove();
		}
	});
}

function LoadExtraComments() {
	$.ajax({type: "POST", async: true, url: Ajax_HandlerURL, dataType: "json",
		data: "Request=GetEntryComments&SourceID=" + $('.CurrentVideo').attr('id'),
		beforeSend: function () { $("#CommentList").html('<center><br />' + Ajax_Animation + '<br /><br /></center>') },
		success: function(Data) {
			ParsedHTML = Data.Template.process(Data.Data);
			$("#CommentList").html(ParsedHTML);
		}
	});
}

function LoadEpisode(LinkID) {
	$('.PlayerSubSelection').html('Loading ...');
	$.ajax({type: "POST", url: Ajax_HandlerURL, dataType: "json",
		data: "Request=GetEpisodeSelection&ID=" + LinkID,
		success: function(Data) {
			$('.PlayerSubSelection').html('');
			if (Data.Count > 1)	{
				$('#PlayerContent').html('<div class="PlayerSubHint">' + Data.Notice + '</div>');
				$('.PlayerSubSelection').html(Data.Selection);
			} else {
				LoadPlayer(Data.ID);
            }
		}
	});
}

function DisplayMirrors(BaseID) {
	if ($('.MirrorSelection').html() != '') {
		$('.MirrorSelection').slideUp("slow", function () { $('.MirrorSelection').html(''); } );
		return;
	}

	$.ajax({type: "POST", url: Ajax_HandlerURL, dataType: "json",
		data: "Request=GetMirrors&ID=" + BaseID,
		beforeSend: function () {
			$('.MirrorSelection').html('<center><br>' + Lng[0]["System"]["Animation"] + '<br><br></center>');
			$('.MirrorSelection').slideDown("fast");
		},
		error: function () {
			$('.MirrorSelection').html('<center><br>Error<br><br></center>');
		},
		success: function(Data) {
			HTMLBlock = Data.Template.process(Data);
			$(".MirrorSelection").html(HTMLBlock);
			$('.MirrorSelection').slideDown("slow");
			$(".MirrorCombo").bind("click", function(e) {
				DisplayQueueMirrors(this, e);
			});
		}
	});
}

function DisplayQueueMirrors(Sender, Event) {
	$('.DropDownBtn').hide();
	var MenuID = $(Sender).attr('alt');
	var position = $(Sender).position();
	CorrentTop = position.top + 47;
	CorrentLeft = position.left - 124;
	$('#' + MenuID).css({'top': CorrentTop + 'px', 'left' : CorrentLeft + 'px'});
    $('#' + MenuID).one("mouseleave", function() { $(this).hide(); });
	$('#' + MenuID).slideDown("fast");
}

function LoadMail(MailID) {
	$.ajax({type: "POST", async: true, url: Ajax_HandlerURL, dataType: "html",
		data: "Request=GetMail&MailID=" + MailID,
		beforeSend: function(Data) { $('#MailContent').html(Ajax_Loading); 	},
		success: function(Result) { if (Result != undefined && Result != '' && Result != '404' && Result != '403') $('#MailContent').html(Result); else { $('#MailContent').html(''); alert('Fehler beim laden der Mail') } }
	});
}

function SendApplication() {
	$.ajax({type: "POST", async: true, url: Ajax_HandlerURL, dataType: "text",
		data: "Request=SetApplication&" + $('#ApplicationForm').serialize(),
		success: function(Result) { alert(Result); }
	});
}

function DisplayLeftChars(Source, Dest, Max) {
	var LeftChar = Max - (($(Source).attr('value') == undefined) ? 0 : $(Source).attr('value').length);
	if (LeftChar >= 0)
	$(Dest).html(Lng[0]["Entry"]["CharsLeft"].replace(/%s1/g, LeftChar)); else
	$(Dest).html(Lng[0]["Entry"]["CharsFull"]);
}

var TPModifier = {
	Sprintf : function(Sentence, Param1, Param2, Param3) {
		return Sentence.replace(/%s1/g, Param1).replace(/%s2/g, Param2).replace(/%s3/g, Param3);
	}
};

function LoadModule(Module) {
	if (Module == Ajax_CurrentMod && Module != 'Entry') return;
	else if (Module + '-' + arguments[1] + '-' + arguments[2] == Ajax_CurrentMod) return;
	if (arguments[3] != "UseHistory") {
		var ModID = ModuleHistory.length;
		ModuleHistory[ModID] = new Object();
		ModuleHistory[ModID]["Module"] = Module;
		ModuleHistory[ModID]["Param1"] = arguments[1];
		ModuleHistory[ModID]["Param2"] = arguments[2];
		var ModData = new Object();
		ModData['Module'] = Module;
		ModData['P1'] = arguments[1];
		ModData['P2'] = arguments[2];
		if (Ajax_CurrentMod != '') $.history(ModData);
		else InitMod = ModData;
	}
	$.ajax({type: "POST", async: true, url: Ajax_HandlerURL, dataType: "json",
		data: "Request=LoadModule&Name=" + Module + "&Param1=" + arguments[1] + "&Param2=" + arguments[2] + "&Data=" + QueryData,
		beforeSend: function(Data) {
			$('#Module').html(Ajax_Loading);
		},
		success: function(Data) {
			$("#Module").html('');
			for (Block in Data.Block) {
				if (Data.Block[Block].Data != undefined)
				Data.Block[Block].Data._MODIFIERS = TPModifier;
				HTMLBlock = Data.Block[Block].Template.process(Data.Block[Block].Data);
				$("#Module").append(HTMLBlock);
				if (Data.Block[Block].Data['Sortable'] != undefined && Data.Block[Block].Data['Sortable'] == 1 && Data.Block[Block].Data['Pager'] === false)
				$('.EntryTabList').tablesorter();
				else if (Data.Block[Block].Data['Sortable'] != undefined && Data.Block[Block].Data['Sortable'] == 1)
				$('.EntryTabList').tablesorter().tablesorterPager({container: $("#pager")});
			}

			Ajax_CurrentMod = ((Data.ModName == undefined) ? Module + arguments[1] + arguments[2] : Data.ModName);
			if ($("#CaptureInput").length == 1) $("#CaptureInput").focus();
		},
		error: function (Data) {
			$('#Module').html(Ajax_Error);
		}
	});
}

function RefreshModule() {
	var WantedPos = parseInt(ModuleHistory.length) - 1;
	if (WantedPos >= 0) {
		Ajax_CurrentMod = "XYZ";
		LoadModule(ModuleHistory[WantedPos]["Module"], ModuleHistory[WantedPos]["Param1"], ModuleHistory[WantedPos]["Param2"], 'UseHistory');
	} else alert('Fehler, aktuelles Modul unbekannt');
}

function PerformESearch() {
	$.ajax({type: "POST", async: true, url: Ajax_HandlerURL, dataType: "json",
		data: "Request=GetExtSearchResult&" + $('#ESearch').serialize(),
		beforeSend: function(Data) { $("#ESearchResult").html(''); $('#StateMsg').html(Ajax_Animation); },
		success: function(Data) {
			$('#StateMsg').html('');
			$("#ESearchResult").html('');
			for (Block in Data.Block) {
				if (Data.Block[Block].Data != undefined)
				Data.Block[Block].Data._MODIFIERS = TPModifier;
				HTMLBlock = Data.Block[Block].Template.process(Data.Block[Block].Data);
				$("#ESearchResult").append(HTMLBlock);
			}
		}
	});
}

function ChangeLayout(Layout) {
	$('#Lablor').attr('value', Layout);
	$('#Layouter').submit();
}

function ESearchGo(Offset) {
	$('#ESearchOffset').attr('value', Offset);
	PerformESearch();
}

function SetBookmark(Sender) {
	$.ajax({type: "POST", async: true, url: Ajax_HandlerURL, dataType: "json",
		data: "Request=SetBoomark&VideoID=" + $('.CurrentVideo').attr('id'),
		beforeSend: function(Data) { $(Sender).attr('src', '/res/gr/Ani/Loading.gif'); },
		success: function(Data) {
			$(Sender).attr('src', '/res/gr/Btn/Remember.png')
			alert(Data.Msg);
		}
	});
}

function RemoveBookmark(Sender, BookID) {
	if (!confirm(Lng[0]["Confirmations"]["DelBook"])) return;
	$.ajax({type: "POST", async: true, url: Ajax_HandlerURL, dataType: "json",
		data: "Request=RemoveBoomark&BookID=" + BookID,
		beforeSend: function(Data) { $(Sender).attr('src', '/res/gr/Ani/Loading.gif'); },
		success: function(Data) {
			$(Sender).attr('src', '/res/gr/Btn/delete.png')
			if (Data.Error == "0")
			$('#Bookmark_' + BookID).remove(); else
			alert(Data.Msg);
		}
	});
}

function RemoveMail(Sender, MailID) {
	if (!confirm(Lng[0]["Confirmations"]["DelMail"])) return;
	$.ajax({type: "POST", async: true, url: Ajax_HandlerURL, dataType: "json",
		data: "Request=RemoveMail&MailID=" + MailID,
		beforeSend: function(Data) { $(Sender).attr('src', '/res/gr/Ani/Loading.gif'); },
		success: function(Data) {
			$(Sender).attr('src', '/res/gr/Btn/delete.png')
			if (Data.Error == "0")
			$('#Mail' + MailID).remove(); else
			alert(Data.Msg);
		}
	});
}

function RateVideo(Sender, Type) {
	$.ajax({type: "POST", async: true, url: Ajax_HandlerURL, dataType: "json",
		data: "Request=SetRating&VideoID=" + $('.CurrentVideo').attr('id') + "&Mode=" + Type,
		beforeSend: function(Data)	{ $(Sender).attr('src', '/res/gr/Ani/Loading.gif'); },
		success: function(Data) {
			$(Sender).attr('src', '/res/gr/Btn/Be'+ Type +'.png')
			if (Data.Error == '1') alert(Data.Msg);
			else $('#RSentence').html(Data.RSentence);
		}
	});
}

function PostComment() {
	$.ajax({type: "POST", async: true, url: Ajax_HandlerURL, dataType: "json",
		data: "Request=SetComment&Override="+ arguments[0] +"&VideoID=" + $('.CurrentVideo').attr('id') + "&" + $('#PostCommentForm').serialize(),
		beforeSend: function(Data) {
			$('.CommentInfo').html(Ajax_Animation);
		},
		success: function(Data) {
			if (Data.Error == '2') {
				$('.CommentInfo').html('Operation abgebrochen');
            	if (!confirm(Data.Hint)) PostComment("Y");
			} else {
				$('.CommentInfo').html(Data.Msg);
				if (Data.Error == '0') {
					$('.CommentField').attr('value', '');
					$('#CommentList').prepend(Data.Data);
					$('#CommentList').toggle();
					$('#CommentBox').toggle();
				}
			}
		}
	});
}

function PerformLogin() {
	$.ajax({type: "POST", async: true, url: Ajax_HandlerURL, dataType: "json",
		data: "Request=SetLogin&" + $('#LoginForm').serialize(),
		beforeSend: function() {
			$('.Headline').html('<span style="float:left; Margin: 4px 0px 0px -29px;">' + Ajax_Animation + '</span>');
		},
		success: function(Data) {
			$('.Headline').html(Data.Msg)
			var Test = Lng[0]['Login']['Msg_' + Data.State];
			$("#Module").html(Data.Block['Login'].Template.process(Data.Block['Login'].Data));
			if (Data.Block['Login']["Data"]["State"] == 0) {
				$('#ILogin').hide();
				$('#UserMenu').show();
			}
		}
	});
}

function Logout() {
	$.ajax({type: "POST", async: true, url: Ajax_HandlerURL, dataType: "json",
		data: "Request=SetLogout",
		beforeSend: function() {
			$('.Headline').html('<span style="float:left; Margin: 4px 0px 0px -29px;">' + Ajax_Animation + '</span>');
		},
		success: function(Data) {
			$('.Headline').html(Data.Msg)
			$("#Module").html(Data.Block['Logout'].Template.process());
			$('#ILogin').show();
			$('#UserMenu').hide();
		}
	});
}

function SetOptions(Mode) {
	$.ajax({type: "POST", async: true, url: Ajax_HandlerURL, dataType: "json",
		data: "Request=SetOptions&Mode=" + Mode + "&" + $('#OptForm').serialize(),
		beforeSend: function() {
			$('#OptFeedBack').html('<center>' + Ajax_Animation + '</center>');
		},
		success: function(Data) {
			$("#OptFeedBack").html(Data.Msg);
			if (Data.RefreshPage && confirm('Apply Settings?')) location.reload();
			$('[name=B1]').attr('disabled', ((Mode == 'Delete') ? 'disabled' : '') );
		}
	});
}

function GetSearchPlugin() {
	try { window.external.AddSearchProvider("http://kino.to/pub/XML/SearchPlugin.xml");}
	catch (ex1) { alert("Das Suchplugin funktioniert nur unter Firefox und Internet Explorer >= 7.\nWenn Du mit Opera (9) unterwegs bist, klicke einfach mit rechts auf das Suchfesnter und wähle 'Suche hinzufügen'"); }
}

$.history.callback = function (Data, cursor ) {
	if (Data == undefined) Data = InitMod;
	LoadModule(Data['Module'], Data['P1'], Data['P2'], 'UseHistory');
};

$(function() { $("#SearchPhrase").jSuggest({ url: Ajax_HandlerURL, type: "POST", minchar: 3, delay: 400, zindex: 20000, loadingImg: '/res/gr/Ani/Loading.gif', data: "Request=GetAutoComplete&Term", autoChange: false }); });
function Highlight(Element, Style) { $(Element).removeClass(); $(Element).addClass(Style); }
function SendVerifikation() { $.ajax({type: "POST", async: true, url: Ajax_HandlerURL, dataType: "html", data: "Request=GetPlayerWindowHD&" + $('#CaptureForm').serialize(), success: function(Player) { $('#PlayerContent').html(Player); }}); }
function PerformSearch() { LoadModule('Search', escape($('#SearchPhrase').attr('value'))); }
function ExtSearch(Title, Season) { LoadModule('Search', Title, Season); }
function ShowHint(Hint) { $('.PlayerSubSelectionHint').html(Hint); }
function ReloadPlayer() { $.ajax({type: "POST", async: true, url: Ajax_HandlerURL, dataType: "text", data: "Request=GetPlayerWindow&VideoID=" + $('.CurrentVideo').attr('id'), success: function(Msg) { if (Msg != '') alert(Msg); }}); }
function ReloadPlayers() { $.ajax({type: "POST", async: true, url: Ajax_HandlerURL, dataType: "text", data: "Request=GetPlayerWindows&VideoID=" + $('.CurrentVideo').attr('id'), success: function(Msg) { if (Msg != '') alert(Msg); }}); }