

var pageTitleInterval = 0,
	pageTitleTimeout = 0,
	KNF = {},
	pageTitle = "",
	messageChooserTextBuffer,
	popY = 0,
	chooser_selection = 2,
	env_check = new Array(),
	knfRequiredFlash = "10";

(function($) {
	var shift = {
		"left": function(a) {
			a.push(a.shift());
		},
		"right": function(a) {
			a.unshift(a.pop());
		}
	};
	$.marqueeTitle = function(options) {
		var opts = $.extend({},
		{
			txt: "",
			dir: "left",
			speed: 200
		}, options),
			t = (opts.txt || document.title).split("");
		if (!t) {
			return;
		}
		t.push(" ");
		pageTitleInterval = setInterval(function() {
			var f = shift[opts.dir];
			if (f) {
				f(t);
				document.title = t.join("");
			}
		}, opts.speed);
	};
}(jQuery));

function activateTitleScroller(some_text) {
	deactivateTitleScroller();
	pageTitle = document.title;
	pageTitleTimeout = window.setTimeout("deactivateTitleScroller()", 15000);
	$.marqueeTitle({txt: some_text + " --- " + some_text + " ---", speed: 150});
}

function deactivateTitleScroller() {
	if (pageTitleInterval) {
		clearInterval(pageTitleInterval);
		document.title = pageTitle;
	}
	if (pageTitleTimeout) {
		clearTimeout(pageTitleTimeout);
	}
}

function ts_nudge(arg) {activateTitleScroller(arg ? arg + " flirtet mit Dir!" : "Du wurdest angeflirtet!");}
function ts_addfriend(arg) {activateTitleScroller(arg ? arg + " möchte Dich kennenlernen!" : "Du hast eine neue Kontaktanfrage!");}
function ts_chat(arg) {activateTitleScroller(arg ? arg + " möchte mit Dir chatten!" : "Jemand möchte mit Dir chatten!");}



function knfMessage(msg, buttons, error) {
	var sep = '<div class="spc20"></div>' + "\n";
	var out = msg;

	if (buttons) {
		out += sep;
		for (var i = 0, c = buttons.length; i < c; i++) {
			if (buttons[i].cssclass) {
				buttons[i].cssclass.replace(/bGreen/g, "btn-green");
				buttons[i].cssclass.replace(/bYellow/g, "btn-orange");
				buttons[i].cssclass.replace(/bRed/g, "btn-red");
				buttons[i].cssclass.replace(/bPink/g, "btn-red");
				buttons[i].cssclass.replace(/bBlue/g, "btn-blue");
			}
			out += '<a href="' + (buttons[i].href ? buttons[i].href : '#') + '" onclick="knfMessageHide(); ' + (buttons[i].click ? buttons[i].click : '') + (buttons[i].href ? '' : '; return(false);') + '" class="' + (buttons[i].cssclass ? buttons[i].cssclass : '') + '">' + buttons[i].title + '</a>' + "\n";
		}
	}
	out += '<div class="clr"></div>';
	$('#knfMessageContent').html(out);
	$('#knfMessage').toggleClass('knfMessageError', error ? true : false);
	knfMessagePositioner();

	$(window).bind("scroll resize", knfMessagePositioner);

	$('#knfMessage').fadeTo("fast", 1);
}

function knfMessageHide() {
	$('#knfMessage').fadeOut("fast");
	$(window).unbind("scroll resize", knfMessagePositioner);
}

function knfMessagePositioner() {
	$('#knfMessage').stop();
	$('#knfMessage').animate({
		left: Math.round((($(window).width() - $('#knfMessage').outerWidth()) / 2) + $(window).scrollLeft()),
		top: Math.round((($(window).height() - $('#knfMessage').outerHeight()) / 2) + $(window).scrollTop())
	}, "fast");
}

var HS = {
	scroller: null,
	left: 0,

	start: function() {
		if (HS.scroller) {
			var e = HS.scroller;
			var time = (parseInt(e.css("left")) - HS.left) * 25;

			e.animate({left: HS.left}, time, "linear", function() {
				$(this).css("left", 0);
				HS.start();
			});
		}
	},

	stop: function() {
		if (HS.scroller) {
			HS.scroller.stop(true);
		}
	},

	init: function() {
		var e = HS.scroller = $("#uw_scroller div").first();
		var t = e.html();
		if (t.length) {
			e.css({visibility: "hidden", position: "absolute"}).append(" ");
			HS.left = 0 - e.width();
			e.append(e.html());
			e.css({visibility: "visible", width: HS.left * -2});
			$("#uw_scroller").css("position", "relative").bind({
				mouseover: HS.stop,
				mouseout: HS.start
			});
			HS.start();
		}
	}
};

function crmPopupSwitchProfiles(num) {
	var thumbs = $(".crm-profiles-thumb");
	var blocks = $(".crm-popup-profile");

	for (var i = 0, c = thumbs.length; i < c; i ++) {
		if (i == num) {
			$(thumbs[i]).addClass("act");
			$(blocks[i]).show();
		} else {
			$(thumbs[i]).removeClass("act");
			$(blocks[i]).hide();
		}
	}
}

var PeopleInvite = {
	successCallback: function(data) {
		$("#searchResults").html(data);
		$("#loaderImg").hide();
	},

	fetch: function(form, options) {
		var parameters = [$(form).serialize()];
		parameters[parameters.length] = "page=1";

		$("#loaderImg").show();

		$.ajax({
			url: form.action,
			data: parameters.join("&"),
			success: PeopleInvite.successCallback
		});

		return(false);
	},

	fetchDirectly: function(url) {
		$.ajax({
			url: url,
			success: PeopleInvite.successCallback
		});
		return(false);
	},

	onclickHandler: function(event, element) {
		PeopleInvite.remove(element);
	},

	updateCount: function(isNegative) {
		var count = 0 + parseInt($("#userCounter").text());
		count += (isNegative ? -1 : +1);
		$("#userCounter").text(count);
		$("#knf_btn_send").val((count > 1) ? "Einladungen senden" : "Einladung senden");
	},

	doesExist: function(userId) {
		return($("#peopleInviteForm [name='ids[]']").filter(function(arg) {return($(this).val() == userId);}).length > 0);
	},

	add: function(userId, login) {
		var count = 0 + parseInt($("#userCounter").text());
		if (count >= 20) {
			knfMessage("Du hast bereits die maximale Anzahl an Usern ausgewählt!", [{title: "OK", cssclass: "bw70 bBlue"}]);
		} else if (!PeopleInvite.doesExist(userId)) {
			$("#alreadyInvited").append($("<div/>").append($("<a/>", {
				href: "#",
				title: "Aus der Einladungsliste entfernen",
				click: function() {PeopleInvite.remove(this); return(false);}
			}).append($("<img/>", {
				src: "/images/evo3x/symbols/delete.png"
			}))).append(login).append($("<input/>", {
				type: "hidden",
				name: "ids[]",
				value: userId
			})));

			PeopleInvite.updateCount();
		}
		return(false);
	},

	remove: function(element) {
		$(element).parent().remove();
		PeopleInvite.updateCount(true);
	},

	submit: function(form) {
		return(PeopleInvite.fetch(form));
	}
};

function ensureMax(form) {
	if ($(form).find("[name=importants\[\]]:checked").length > 3) {
		knfMessage('Du darfst maximal nur 3 Fragen markieren!', [{title: 'OK', cssclass: 'btn-red bw90'}]);
		return(false);
	}
}

function ensureMin(form) {
	if ($(form).find("[name=importants\[\]]:checked").length < 1) {
		knfMessage('Bitte markiere mindestens 1 Frage als wichtig!', [{title: 'OK', cssclass: 'btn-red bw90'}]);
		return(false);
	}
}

function messageChooserBold() {
	$("#default_message").css("font-weight", 100);
}

function messageChooserSetBuffer() {
	messageChooserTextBuffer = $("#free_message").val();
}

function messageChooserGetBuffer() {
	if ($("#default_message :selected").val() != "") {
		$("#free_message").val(messageChooserTextBuffer);
	}
}

function getMessageChooser() {
	var message = $("#default_message").val();
	if (message && (message.length < 1)) {
		message = $("#free_message").val();
	}
	if ($("#message_chooser_selects").length) {
		message = $("#message_chooser_selects input:checked").val();
		if (check_option() && mctext_edited) {
			var tmp = $("#message_chooser").val();
			if (tmp.length) {
				message = tmp;
			}
		}
	}
	return(message || false);
}

function textErase(obj) {
	$(obj).removeAttr("onfocus").unbind("focus").val("");
}

function removeElement(element) {
	var e = $(element).parent();
	var n = $(".mProf.hidden", e.parent()).first();
	e.remove();
	n.removeClass("hidden");
}

function askConfirmation(element, id, text) {
	var params = "id=" + id;
	if (window.confirm(text)) {
		params += "&block=1";
	}
	$.post("/user/block_list_user", params);
	removeElement(element);
}

function removeVisit(id, element) {
	$.ajax({
		type: "POST",
		url: "/user/remove_visit",
		data: {id: id},
		error: function(xhr, status, error) {
			askConfirmation(element, id, xhr.responseText);
		},
		success: function(data, status, xhr) {
			removeElement(element);
		}
	});
	return(false);
};

function removeNetworkUser(id, login, element) {
	$.ajax({
		type: "POST",
		url: "/user/remove_network_user",
		data: "id=" + id,
		error: function(xhr, status, error) {
			askConfirmation(element, id, xhr.responseText);
		},
		success: function(data, status, xhr) {
			removeElement(element);
		}
	});
	return(false);
};

var Flash = {
	get: function(name) {
		return($("[name=" + name + "]").toArray()[0]);
	}
};

function confirmDelete(id, old) {
	knfMessage("Willst Du dieses Bild wirklich entfernen?", [
		{title: "Ja", cssclass: "btn-red bw90", click: "delete_profile_photo(" + id + ", " + old + ")"},
		{title: "Nein", cssclass: "btn-blue bw90 btn_blue"}
	]);
}

function buttonHub(buttonObject) {
	if ($(buttonObject).attr("id") == "elv_button_save") {
		$("#knf_pay_elv").hide();
		$("#knf_pay_waiting").show();
	}
}

function resizeMiniLive(size) {
	$("#flashMinilive").height(size);
}

function resizeMegaLive(size) {
	$("#megalive_wrap, #flashMegalive").height(size);
}

function setPopY(callingElement) {
}

function hoverLtIE7() {
	$(function() {
		var selector = "div.polaroid, div.slot";
		$(selector).mouseover(function() {$(this).addClass("hover");});
		$(selector).mouseout(function() {$(this).removeClass("hover");});
	});
}

function mailboxActivate(item_id) {
	$("#mailbox_list").children(".item_0, .item_1").each(function(i, e) {
		$(e).removeClass("item_0 item_1").addClass("item_" + (i % 2));
	});
	$("mbitem_" + item_id).removeClass("unread").addClass("active");
}

function updateInOutBoxLinks(arg, outbox) {
	$("#j21p_nav_msgs").addClass("active");
	$("#msgs-posteingang").attr("href", "/user/" + arg);
	$("#msgs-postausgang").attr("href", "/user/" + arg + "?outbox=true");
	$(outbox ? "msgs-postausgang" : "msgs-posteingang").addClass("active");
	navi_show("j21p_sub_nav_msgs", $("#j21p_nav_msgs"));
}

function check_option() {
	return(chooser_selection == 1);
}

function switch_premium_feature(arg) {
	if (arg == 1) {
		$("#knf_btn_send, #knf_btn_send_friend_request").hide();
		$("#knf_btn_premium").show();
	} else {
		$("#knf_btn_premium").hide();
		$("#knf_btn_send, #knf_btn_send_friend_request").show();
	}
}

var mctext_edited = false;

function switch_chooser(num) {
	$("#chooser_freitext").toggleClass("act", num == 1);
	$("#chooser_auswahl").toggleClass("act", num == 2);
	$("#message_chooser").toggle(num == 1);
	$("#message_chooser_selects").toggle(num == 2);
	chooser_selection = num;
}

function switch_chooser_v2(num) {
	if (num == 1) {
		$("#message_chooser_selects").hide();
		$("#message_chooser").show();
		$("#chooser_freitext").removeClass().addClass("active");
		$("#chooser_auswahl").removeClass();
	} else {
		$("#message_chooser").hide();
		$("#message_chooser_selects").show();
		$("#chooser_auswahl").removeClass().addClass("active");
		$("#chooser_freitext").removeClass();
	}
	chooser_selection = num;
}

function delete_profile_photo(arg, old) {
	$.ajax({
		url: "/photo/delete_photo",
		data: {id: arg},
		complete: function() {
			var par = $("#photo" + arg).parent()
			$(par).find("div.clr").remove();
			$("#photo" + arg).remove();
			if (old) {
				$(par).append("<a class=\"empty\" href=\"/photo/uploadprofilephoto\"><span>Lade ein Foto hoch!</span></a>");
			} else {
				$(par).append("<div class=\"photoEditBox\"><a class=\"photoEditEmpty\" title=\"Jetzt ein Foto hochladen\" href=\"/photo/uploadprofilephoto\"></a></div>");
			}
			$(par).append("<div class=\"clr\"></div>");
		}
	});
}

function set_profilephoto(arg) {
	$.ajax({
		url: "/photo/set_profilephoto",
		data: {id: arg},
		complete: function() {
			window.location.href = "/user/view?tab=gallery&edit_mode=true";
		}
	});
}

function setChecks(check) {
	$("form[name=mbForm] input[type=checkbox]").prop("checked", check);
}

function showDelLink(arg) {
	$("#delin, #delout, #checkall_pipe").hide();

	if (arg == "in") {
		var do1 = "in";
	} else if (arg == "out") {
		var do1 = "out";
	} else {
		return(false);
	}

	if ($(do1 + "Form :checked").length > 0) {
		$("#del" + do1 + ", #checkall_pipe").show();
	}

	$("#checki").prop("checked", env_check[arg]);
	if (env_check[arg]) {
		$("#checkall_info").hide();
	} else {
		$("#checkall_info").show();
	}
}

function knf_switch_inout(arg) {
	if (arg == "in") {
		$("#box_out").hide();
		$("#box_in").show();
		$("#link_out").css("color", "#fff");
		$("#link_in").css("color", "#000");
	} else if (arg == "out") {
		$("#box_in").hide();
		$("#box_out").show();
		$("#link_in").css("color", "#fff");
		$("#link_out").css("color", "#000");
	}
	showDelLink(arg);
}

function showPaymentPopup() {
	if (window.top != window.self) {
		window.top.location.href = "https://www.kissnofrog.com/payment/changepackage?fb=true";
	} else {
		document.location.href = "/payment/changepackage";
	}
}

function showPaymentPopupForUser(userId) {
	if (window.top != window.self) {
		window.top.location.href = "https://www.kissnofrog.com/payment/changepackage?partner=" + userId + "&fb=true";
	} else {
		document.location.href = "/payment/changepackage?partner=" + userId;
	}
}

function showPaymentPopupForUserWithTrigger(userId, trigger) {
	if (window.top != window.self) {
		window.top.location.href = "https://www.kissnofrog.com/payment/changepackage?partner=" + userId + "&pt=" + trigger + "&fb=true";
	} else {
		document.location.href = "/payment/changepackage?partner=" + userId + "&pt=" + trigger;
	}
}

var myExecutor;
var myExecutorId;
var exCounter = 1;
var EXECUTOR_INTERVAL = 15 * 1000;

function poll() {
	if (exCounter) {
		KNF.Popups.nextOne();
	} else {
		exCounter += 1;
	}
}

var startExecutor = function(userId) {
	myExecutorId = userId;
	exCounter = 1;
	myExecutor = window.setInterval(function() {
		poll(myExecutorId);
	}, EXECUTOR_INTERVAL);
};

var restartExecutor = function() {
	if (myExecutor) {
		stopExecutor();
		startExecutor(myExecutorId);
		exCounter = 0;
	}
};

var stopExecutor = function() {
	window.clearInterval(myExecutor);
};

function heartBeat() {
	$.get("/user/heartbeat");
}

var startHeartBeat = function() {
	myExecutor = window.setInterval(heartBeat, EXECUTOR_INTERVAL);
};

function knf_removeInvitedUser(className) {
	$("." + className).each(function() {
		$(this).remove();
		$("#userCount").val(parseInt($("#userCount").val()) - 1);
	});
}

function addInvitedUser(response, userId) {
	var idsMap = {};
	var ids = [];
	$(".user").each(function() {
		var id = this.id;
		idsMap[parseInt(id, 10)] = true;
		ids[ids.length] = parseInt(id, 10);
	});
	var count = parseInt($("#userCount").val(), 10);
	var limit = 20;
	if (count < limit && ids.length < limit) {
		if (!idsMap[userId]) {
			count += 1;
			$("#userCounter").text(count);
			$("#userCount").val(count);
			$(response).appendTo("#alreadyInvited");
		}
	} else {
		alert("Du hast schon " + limit + " Leute eingeladen.");
	}
}

function inviteUser(id) {
	if (window.location.href.indexOf("/meeting/afterCreate") > -1) {
		if ($("#meetingId").length > 0) {
			$("#knf_btn_send").val("Versenden");
			$.ajax({
				url: "/meeting/invite/" + id,
				success: function(data) {
					addInvitedUser(data, id);
				}
			});
		}
	} else {
		$.ajax({
			url: "/meeting/invite/" + id,
			success: function(data) {
				$("#alreadyInvited").html(data);
			}
		});
	}
}

function mbNewMessage(arg) {
	$("#mbContent, #mbMessage, #mbOptions").hide();
	$("#mbBack, #mbNewMessage").show();
	if (arg) {
		$("#message_recipient").val(arg);
	}
}

function mbClose() {
	$("#mbNewMessage, #mbMessage, #mbBack").hide();
	$("#mbContent, #mbOptions").show();
}

function mbLoadMessage(id) {
	$.ajax({
		url: "/message/view",
		data: {id: id},
		success: function(data) {
			$("#mbMessage").html(data);
			$("#mbNewMessage, #mbContent, #mbOptions").hide();
			$("#mbBack, #mbMessage").show();
		}
	});
}

function mbShowOldMessages() {
	$("#mbShowOldMessages").slideUp();
	$("#mbMessage .mbItem:hidden").slideDown();
}

function knf_loadMailbox(arg, id, title, height) {
	$("#mailbox_view").html("<img src=\"http://static.kissnofrog.com/images/evolution3/symbols/indicator_mbox.gif\" width=\"16\" height=\"16\" align=\"absmiddle\"/> " + title + " wird geladen...");
	knf_resizeMailbox(height || 160);
	knf_mailboxMessageQuit();
	$.ajax({
		url: arg,
		data: {id: id},
		success: function(data) {
			$("#mailbox_view").html(data);
			mailboxActivate(-1);
			mailboxActivate(id);
		}
	});
}

function knf_mailboxMessageAnswer() {
	knf_resizeMailbox(-1);
	$("#mailbox_view_content").height(230);
	$("#mailbox_MessageAnswer").hide();
	$("#mb_messageAnswer").show();
}

function knf_mailboxNewMessage(to) {
	knf_resizeMailbox(160);
	$("mailbox_view").hide();
	$("mailbox_newMessage").show();
	if (to) {
		$("#message_recipient").val(to);
	}
}

function knf_send_message(someForm) {
	breakLongWords("[name='message\[message\]']");
	$.ajax({
		url: "/message/create",
		dataType: "json",
		type: "POST",
		data: $(someForm).serialize(),
		error: function(xhr) {knfMessage("FEHLER: " + xhr.responseText, [{title: "OK", cssclass: "btn-red bw90"}], 1);},
		success: function (data) {
			mbClose();
			if (data.pic) {
				knfMessage("Die Nachricht wurde versendet.", [{title: "OK", cssclass: "btn-red bw90"}]);
			} else {
				var e = document.getElementById("message_recipient");
				if (e) {
					KNF.Popups.fetch("/popups/nopic?login=" + e.value);
				}
			}
			someForm.reset();
		}
	});
	return(false);
}

function breakLongWords(element) {
	$(element).each(function() {
		$(this).val($(this).val().replace(/(\S{50})/g, "$1 "));
	});
}

function knf_mailboxMessageQuit() {
	knf_resizeMailbox(160);
	$("#mailbox_newMessage").hide();
	$("#mailbox_MessageAnswer").show();
	mailboxActivate(-1);
}

function knf_resizeMailbox(listH) {
	if (listH == -1) { // hide list
		$("#mailbox_list, #mailbox_list_header").hide();
		$("#mailbox_view").show().css({height: 410, marginTop: 0});
	} else if (listH == -2) { // hide mailbox
		$("#mailbox_view").hide();
		$("#mailbox_list_header").show();
		$("#mailbox_list").show().css({height: 395});
	} else {
		$("#mailbox_list_header").show();
		$("#mailbox_list").show().css({height: listH});
		$("#mailbox_view").show().css({height: 360 - listH, marginTop: 20});
	}
}

function knf_checkMeetingStartTime() {
	var now = new Date();
	now.setMinutes(now.getMinutes() + 1);
	var dateField = document.getElementById("datePicker");
	var startTime = new Date(dateField.value);
	startTime.setHours(parseInt(document.getElementById("calHour").value, 10));
	startTime.setMinutes(parseInt(document.getElementById("calMin").value, 10));
	if (isNaN(startTime) || startTime < now) {
		knfMessage("Startzeit muss mindestens 1 Minute in der Zukunft liegen.", [{title: "OK", cssclass: "btn-red bw90"}]);
		return(false);
	} else {
		return(true);
	}
}

function showMeetingList(isLoggedIn) {
	if (typeof meetings == "undefined") {
		return(false);
	}

	var subscriptions = (typeof meetingSubscriptions == "object" && meetingSubscriptions) ? meetingSubscriptions : {};
	var applications = (typeof meetingApplications == "object" && meetingApplications) ? meetingApplications : {};

	var currentMillis = new Date().getTime() + serverTimeOffset;
	var pair, id, time, e;
	for (var i = 0, l = meetings.length; i < l; i++) {
		pair = meetings[i];
		id = pair[0];
		time = pair[2];

		if (!isLoggedIn) {
			$("#register-" + id).show();
		} else {
			if (time < currentMillis) {
				$("#join-" + id).show();
			} else {
				if (!subscriptions[id]) {
					var e = $("#subscribe-" + id).show();
				} else {
					var e = $("#unsubscribe-" + id).show();
				}
				if (e.length < 1) {
					if (!applications[id] && !subscriptions[id]) {
						$("#apply-" + id).show();
					} else {
						$("#unapply-" + id).show();
					}
				}
			}
		}
	}
}

function mtCreateSetType(val) {
	if (val == "av") {
		$("#ct_txt_on, #ct_av_off").hide();
		$("#ct_txt_off, #ct_av_on").show();
		$("#ct_type").val(val);
	} else if (val == "t") {
		$("#ct_txt_off, #ct_av_on").hide();
		$("#ct_txt_on, #ct_av_off").show();
		$("#ct_type").val(val);
	}
}

function mtCreateSetAllow(val) {
	if (val == "0") {
		$("#ct_private_on, #ct_public_off").hide();
		$("#ct_private_off, #ct_public_on").show();
		$("#ct_allow").val(val);
	} else if (val == "1") {
		$("#ct_private_off, #ct_public_on").hide();
		$("#ct_private_on, #ct_public_off").show();
		$("#ct_allow").val(val);
	}
}

function createCookie(name, value, days) {
	var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		expires = "; expires=" + date.toGMTString();
	}
	document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(";");
	for (var i = 0, len = ca.length; i < len; i++) {
		var c = ca[i];
		while (c.charAt(0) == " ") {
			c = c.substring(1, c.length);
		}
		if (c.indexOf(nameEQ) == 0) {
			return c.substring(nameEQ.length, c.length);
		}
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name, "", -1);
}

function trackClick(user, partner, type, origin, value) {

}

function flashClickTracking() {}

function infoToggleView(obj, force) {
	var objs = $(obj).parent().children("div.info_cat_sub, p");

	if (force == "none") {
		objs.slideUp("slow");
	} else if (force == "block") {
		objs.slideDown("slow");
	} else {
		objs.slideToggle("slow");
	}
}

KNF.Countdown = {
	ONE_MINUTE_IN_SECONDS: 60,
	ONE_HOUR_IN_MINUTES: 60,
	isLoggedIn: false,

	pluralize: function(count, singular, plural) {
		count = Math.round(parseInt(count));
		var result = count + " ";
		if (count == 1) {
			result += singular;
		} else if (plural) {
			result += plural;
		} else {
			result += singular + "n";
		}
		return(result);
	},

	displayJoinButton: function(id) {
		$("#subscribe-" + id + ", #unsubscribe-" + id + ", #apply-" + id + ", #unapply-" + id).hide();
		if (KNF.Countdown.isLoggedIn) {
			$("#join-" + id).show();
		}
	},

	updateTimes: function() {
		var now = new Date();
		if (typeof serverTimeOffset == "number") {
			now.setTime(now.getTime() + serverTimeOffset);
		}
		var pair, id, startTime, minutes, element, update, seconds;
		for (var i = 0, l = meetings.length; i < l; i++) {
			pair = meetings[i];
			if (pair) {
				id = pair[0];
				startTime = pair[1];
				if (id && startTime) {
					startTime = new Date(startTime);

					minutes = (startTime / 60000) - (now / 60000);
					if (minutes >= KNF.Countdown.ONE_HOUR_IN_MINUTES) {
						$("#knf_meeting_start_" + id).show();
					} else {
						update = "";
						$("#knf_meeting_start_" + id).hide();
						$("#knf_countdown_" + id).show();
						seconds = Math.round((startTime / 1000) - (now / 1000));
						if (seconds >= KNF.Countdown.ONE_MINUTE_IN_SECONDS) {
							update = KNF.Countdown.pluralize(seconds / KNF.Countdown.ONE_MINUTE_IN_SECONDS, "Minute");
						} else if (seconds > 0) {
							update = KNF.Countdown.pluralize(seconds, "Sekunde");
						} else {
							update = "jetzt!";
						}
						if (seconds <= KNF.Countdown.ONE_MINUTE_IN_SECONDS * 5) {
							KNF.Countdown.displayJoinButton(id);
						}
						$("#knf_countdown_" + id).text(update);
					}
				}
			}
		}
	},

	run: function(userIsLoggedIn) {
		KNF.Countdown.isLoggedIn = userIsLoggedIn;
		if (typeof meetings != "undefined" && meetings) {
			window.setInterval(KNF.Countdown.updateTimes, 1000);
		}
	}
};

KNF.Nudges = {
	doReload: false,
	FLIRT_HEADLINE: "Mit diesem Nutzer flirten?",
	FLIRT_TEXT: "Um Deine Chancen zu erhöhen, wähle noch eine kurze Nachricht für Deinen Flirt aus ...",
	MESSAGE_HEADLINE: "Nachricht an Flirtpartner schreiben?",
	MESSAGE_TEXT: "Schreib eine kurze Nachricht ...",
	RESPONSE_HEADLINE: "Flirt erwidern?",
	RESPONSE_TEXT: "Schreibe eine kurze Nachricht ...",

	sendNudge: function(id) {
		var parameters = {
			id: id,
			message: $("#knf_flirtmsg :selected").val()
		};
		if (KNF.Nudges.doReload) {
			parameters["reload"] = true;
		}
		$.ajax({
			url: "/user/nudge",
			data: parameters,
			complete: function() {
				KNF.Nudges.hidePopup();
				knfMessage("Flirt wurde verschickt", [{title: "OK", cssclass: "btn-red bw90"}]);
			}
		});
	},

	sendMessage: function(id) {
		$.ajax({
			url: "/message/send_message",
			data: {
				to: id,
				message: $("#knf_flirtresponsemsg1").val()
			},
			complete: function() {
				KNF.Nudges.hidePopup();
			}
		});
	},

	sendResponseNudge: function(id, parentId) {
		var parameters = {
			id: id,
			nudge_id: parentId,
			message: $("#knf_flirtresponsemsg2").val()
		};
		$.ajax({
			url: "/user/nudge",
			data: parameters,
			complete: function() {
				KNF.Nudges.hidePopup();
			}
		});
	},

	hidePopup: function() {
		$("#knf_flirtpopup").hide();
		$("#knf_flirtpopup textarea").val("");
	},

	displayPopup: function() {
		$("#knf_flirtpopup").show();
		window.scrollTo(0, 0);
	},

	preparePopup: function(userObject) {
		var yesButton = $("#knf_flirtpopup #knf_flirtyes");
		yesButton.unbind("click").bind("click", function(event) {
			KNF.Nudges.sendNudge(userObject["id"]);
		});
		$("#knf_flirtpopup #knf_flirtno").click(KNF.Nudges.hidePopup);
		yesButton.attr("src", "http://static.kissnofrog.com/images/evolution/buttons/big_btn_flirten.png");

		var userInfo = $("#knf_flirtpopup #knf_mpr_cont_flirt");
		userInfo.find("a").attr("href", "/profile/" + userObject["login"]);
		userInfo.find("img").attr("src", userObject["profileImageGridThumb"]);
		userInfo.find("p").text(userObject["login"]);

		var cont = $("#knf_flirtcont");
		cont.find(".knf_popuphead p").text(KNF.Nudges.FLIRT_HEADLINE);
		cont.find(".knf_popuptext p").text(KNF.Nudges.FLIRT_TEXT);

		$("#flirt_select").show();
		$("#flirt_textarea1, #flirt_textarea2").hide();
	},

	prepareTextAreaPopup: function(userObject) {
		KNF.Nudges.preparePopup(userObject);
		var yesButton = $("#knf_flirtpopup #knf_flirtyes");
		yesButton.unbind("click").bind("click", function(event) {
			KNF.Nudges.sendMessage(userObject["id"]);
		});
		yesButton.attr("src", "http://static.kissnofrog.com/images/evolution/buttons/big_btn_senden.png");

		var cont = $("#knf_flirtcont");
		cont.find(".knf_popuphead p").text(KNF.Nudges.MESSAGE_HEADLINE);
		cont.find(".knf_popuptext p").text(KNF.Nudges.MESSAGE_TEXT);

		$("#flirt_select, #flirt_textarea2").hide();
		$("#flirt_textarea1").show();
	},

	prepareResponsePopup: function(userObject, parentId) {
		KNF.Nudges.preparePopup(userObject);
		var yesButton = $("#knf_flirtpopup #knf_flirtyes");
		yesButton.unbind("click").bind("click", function(event) {
			KNF.Nudges.sendResponseNudge(userObject["id"], parentId);
		});

		var cont = $("#knf_flirtcont");
		cont.find(".knf_popuphead p").text(KNF.Nudges.RESPONSE_HEADLINE);
		cont.find(".knf_popuptext p").text(KNF.Nudges.RESPONSE_TEXT);

		yesButton.attr("src", "http://static.kissnofrog.com/images/evolution/buttons/big_btn_senden.png");

		$("#flirt_select, #flirt_textarea1").hide();
		$("#flirt_textarea2").show();
	},

	acknowledge: function(id) {
		$.ajax({
			url: "/nudge/acknowledge",
			type: "POST",
			data: {id: id}
		});
	},

	requite: function(userObject, parentId) {
		if ($("#knf_flirtpopup")) {
			KNF.Nudges.prepareResponsePopup(userObject, parentId);
			KNF.Nudges.displayPopup();
		}
	},

	message: function(userObject) {
		if ($("#knf_flirtpopup")) {
			KNF.Nudges.prepareTextAreaPopup(userObject);
			KNF.Nudges.displayPopup();
		}
	},

	initiate: function(userObject, reload) {
		if ($("#knf_flirtpopup")) {
			KNF.Nudges.doReload = !!reload;
			KNF.Nudges.preparePopup(userObject);
			KNF.Nudges.displayPopup();
		}
	},

	flirtLive: function(userId, isBlacklisted) {
		if (KNF.wstPopup.check(userId, function() {KNF.Nudges.flirtLive(userId, isBlacklisted);})) {
		var flash = Flash.get("megaLive");
		if (flash) {
			var intervalId = window.setInterval(function() {
				arguments.callee.tries = (arguments.callee.tries || 0) + 1;
				if (arguments.callee.tries > 10) {
					window.clearInterval(intervalId);
					return(false);
				}
				var flash = Flash.get("megaLive");
				if (flash) {
					try {
						if (!isBlacklisted) {
							flash.flirtLive(userId);
						}
						knfMessage("Dein Live-Flirt wurde verschickt.", [{title: "OK", cssclass: "btn-red bw90"}]);
						window.clearInterval(intervalId);
					} catch(e) {}
				}
			}, 500);
		}
		}
	},

	connectLive: function(userId) {
		var flash = Flash.get("megaLive");
		if (flash) {
			var intervalId = window.setInterval(function() {
				arguments.callee.tries = (arguments.callee.tries || 0) + 1;
				if (arguments.callee.tries > 10) {
					window.clearInterval(intervalId);
					flash = null;
					return(false);
				}
				try {
					flash.connectRequest(userId);
					window.clearInterval(intervalId);
					flash = null;
				} catch(e) {}
			}, 500);
		}
	},

	privateLiveChat: function(userId) {
		var flash = Flash.get("megaLive");
		if (flash) {
			var intervalId = window.setInterval(function() {
				arguments.callee.tries = (arguments.callee.tries || 0) + 1;
				if (arguments.callee.tries > 10) {
					window.clearInterval(intervalId);
					flash = null;
					return(false);
				}
				try {
					flash.requestPrivateLiveChat(userId);
					window.clearInterval(intervalId);
					flash = null;
				} catch(e) {}
			}, 500);
		}
	},

	initiate2: function(userId, click_origin) {
		if (KNF.wstPopup.check(userId, function() {KNF.Nudges.initiate2(userId, click_origin);})) {
		var clickParams = "&click_type=2";
		if (click_origin == -1) {
			clickParams += "&click_origin=" + click_origin;
		}
		KNF.Popups.fetch("/popups/sendflirt?id=" + userId + clickParams);
		}
	},

	requite2: function(parentId) {
		KNF.Popups.fetch("/popups/flirt_respond?id=" + parentId);
	},

	send: function(userId, parentId) {
		var tmp;
		var message = $("input[name=friend_request_message]:checked").val();
		if (check_option()) {
			breakLongWords("#message_chooser");
			message = $("#message_chooser").val();
		}
		if ((tmp = getMessageChooser()) !== false) {message = tmp;}
		$("#knf_pc_addfriend").hide();
		$("#knf_pc_addfriend_wait").show();

		$.ajax({
			url: "/user/nudge",
			type: "POST",
			data: {
				id: userId,
				nudge_id: parentId,
				message: message
			},
			complete: function() {
				KNF.Popups.fetch("/popups/flirt_sent");
			}
		});
	}
};

KNF.Spots = {
	fadeIn: function(id) {
		$("#" + id).stop().fadeTo("slow", 1);
	},

	fadeOut: function(id) {
		$("#" + id).stop().fadeTo("slow", 0);
	},

	rewritePopups: function(meetingId) {
		$(".small_popup_for_" + meetingId).each(function(i, e) {
			el = $(e);
			if (!el.hasClass("small_popup_profile")) {
				el.addClass("small_popup_already_invited");
				el.html("<p class='small_popup_already_invited'>Du bist zu diesem Chat bereits verabredet.</p>");
			}
		});
	},

	reservationSucceeded: function(meetingId, isPrivate, startingSoon) {
		var action = isPrivate ? "apply" : "subscribe";
		$("." + action + "-" + meetingId).hide();
		$("." + action + "-box-" + meetingId).hide();
		if (!startingSoon) {
			$(".un" + action + "-" + meetingId).show();
			$(".un" + action + "-box-" + meetingId).show();
		}
	},

	reservationFailed: function(message) {
		knfMessage(message, [{title: "OK", cssclass: "btn-red bw90"}], 1);
	},

	showMeeting: function(id) {
		window.location.href = "/meeting/view/" + id;
	},

	showPopup: function(element, popup) {
		if (element) {
			popup = $("#" + popup);
			if (popup) {
				$(element).mouseout(function() {
					$(this).unbind("mouseout");
					popup.hide();
				});
				popup.show();
			}
		}
	},

	switchImage: function(element, newImage) {
		element = $(element);
		if (element) {
			var oldImage = element.attr("src");
			element.attr("src", newImage).mouseout(function() {
				$(this).unbind("mouseout");
				$(this).attr("src", oldImage);
			});
		}
	}
},

KNF.Session = {
	inviteUser: function(id) {
		KNF.Popups.fetch("/popups/session_invite?id=" + id, null);
	},

	popupStep2: function() {
		if ($("#session_invite_meetings input:checked").length > 0) {
			$("#knf_btn_step2, #session_invite_meetings").hide();
			$("#knf_btn_send, #session_invite_message").show();
		} else {
			knfMessage("Du musst mindestens einen Chat auswählen!", [{title: "OK", cssclass: "btn-red bw90"}]);
		}
	},

	sendInvitation: function(uID) {
		var meetings = new Array(), tmp;
		var message = $("input[name=friend_request_message]:checked").val();
		if (check_option()) {
			breakLongWords("#message_chooser");
			message = $("#message_chooser").val();
		}
		$("#session_invite_meetings input:checked").each(function(i, e) {
			meetings.push($(e).val());
		});
		if ((tmp = getMessageChooser()) !== false) {message = tmp;}
		KNF.Popups.close();
		$.ajax({
			url: "/meeting/meetingInvitation",
			type: "POST",
			data: {invitedUserId: uID, "meeting[]": meetings, invite_text: message},
			success: function() {
				KNF.Popups.fetch("/popups/session_invite_sent?id=" + uID, null);
			}
		});
	}
};

KNF.Friends = {
	checkForPopup: function(link, partnerId, freeText, clickTracking) {
		if (KNF.wstPopup.check(partnerId, function() {KNF.Friends.checkForPopup(link, partnerId, freeText, clickTracking);})) {
		var url = "/popups/check_friend_request?id=" + partnerId;
		if (freeText) {
			url += "&text=true";
		}
		if (typeof clickTracking == "number") {
			url += "&click_origin=" + clickTracking;
		}

		KNF.Popups.fetch(url, function() {
			$("#knf_btn_send_friend_request").click(function() {
				var tmp;
				$("#knf_pc_addfriend").hide();
				$("#knf_pc_addfriend_wait").show();
				var message = $("input[name=friend_request_message]:checked").val();
				if (check_option()) {
					breakLongWords("#message_chooser");
					message = $("#message_chooser").val();
				}
				if ((tmp = getMessageChooser()) !== false) {message = tmp;}
				var params = {id: partnerId};
				if (message) {
					params.friend_request_message = message;
				}
				$.ajax({
					url: "/user/friend_request",
					type: "POST",
					data: params,
					complete: function() {
						$(link).removeClass("knf_profileactions_anfreunden").addClass("knf_profileactions_anfreunden_pending");
						$(link).unbind("click").click(KNF.Friends.alreadySent);
						KNF.Popups.fetch("/popups/addfriend_sent?id=" + partnerId);
					}
				});
				return(false);
			});
		});
		}
	},

	request: function(link, userId, freeText) {
		if (KNF.wstPopup.check(userId, function() {KNF.Friends.request(link, userId, freeText);})) {
		var url = "/popups/addfriend?id=" + userId;
		if (freeText) {
			url += "&text=true";
		}
		KNF.Popups.fetch(url, function() {
			$("#knf_btn_send_friend_request").click(function() {
				var tmp;
				$("#knf_pc_addfriend").hide();
				$("#knf_pc_addfriend_wait").show();
				var message = $("input[name=friend_request_message]:checked").val();
				if (check_option()) {
					breakLongWords("#message_chooser");
					message = $("#message_chooser").val();
				}
				if ((tmp = getMessageChooser()) !== false) {message = tmp;}
				var params = {id: userId};
				if (message) {
					params.friend_request_message = message;
				}
				$.ajax({
					url: "/user/friend_request",
					type: "POST",
					data: params,
					complete: function() {
						$(link).removeClass("knf_profileactions_anfreunden").addClass("knf_profileactions_anfreunden_pending");
						$(link).unbind("click").click(KNF.Friends.alreadySent);
						KNF.Popups.fetch("/popups/addfriend_sent?id=" + userId);
					}
				});
				return(false);
			});
		});
		}
	},

	alreadyDenied: function() {
		KNF.Popups.fetch("/popups/addfriend_denied");
	},

	alreadySent: function() {
		KNF.Popups.fetch("/popups/addfriend_pending");
	},

	acceptRequest: function(id) {
		KNF.Friends.handleFriendRequest(id, true);
	},

	denyRequest: function(id, suppressReload) {
		KNF.Friends.handleFriendRequest(id, false, suppressReload);
	},

	handleFriendRequest: function(id, accept, suppressReload) {
		var params = {id: id};
		var tmp;
		if (accept) {
			params.accept = true;
		}
		var message = $("input[name=friend_request_message]:checked").val();
		if (check_option()) {
			breakLongWords("#message_chooser");
			message = $("#message_chooser").val();
		}
		if ((tmp = getMessageChooser()) !== false) {message = tmp;}
		if (message && accept) {
			params.friend_request_message = message;
		}
		$.post("/user/handle_friend_request", params, function() {
			if (!suppressReload) {
				window.location.reload(true);
			}
		});
		KNF.Popups.close();
	},

	markRead: function(id) {
		$.post("/friend_request/read", {id: id});
	},

	remove: function(id) {
		$.post("/friend/remove", {id: id}, function() {
			window.location.reload(true);
		});
	}
};

KNF.Popups = {
	container: null,
	popupPositionPE: null,

	prepare: function() {
		if (!KNF.Popups.container) {
			KNF.Popups.container = $("#knf_pop_box_outer");
		}
	},

	clear: function() {
		$("#knf_pop_box_outer").empty();
	},

	hide: function() {
		$("#knf_pop_box_outer").stop(true, true).fadeOut("fast");
		restartExecutor();
	},

	show: function() {
		mctext_edited = false;
		$("#message_chooser").one("focus", function() {mctext_edited = true;});
		var container = $("#knf_pop_box_outer");
		var popWidth = container.outerWidth();
		var popHeight = container.outerHeight();

		if (typeof is_mobile != "undefined") {
			container.css("top", popY + "px");
			container.css("left", Math.round(($(window).width() - popWidth) / 2) + "px");
		} else {
			container.css("top", Math.round($(window).scrollTop() + (($(window).height() - popHeight) / 2)) + "px");
			container.css("left", Math.round(($(window).width() - popWidth) / 2) + "px");
		}

		container.stop(true, true).fadeTo("fast", 1);
		{KNF.Popups.activatePE();}
	},

	activatePE: function() {
		KNF.Popups.deactivatePE();
		$(window).bind("scroll resize", KNF.Popups.popupPositionPE = function() {
			if ($("#knf_pop_box_outer").is(":visible")) {
				var container = $("#knf_pop_box_outer");
				var popWidth = container.outerWidth();
				var popHeight = container.outerHeight();

				container.stop(true, true);
				if (typeof is_mobile == "undefined") {
					container.animate({
						top: Math.round($(window).scrollTop() + (($(window).height() - popHeight) / 2)),
						left: Math.round(($(window).width() - popWidth) / 2)
					}, "fast");
				} else {
					container.animate({
						left: Math.round(($(window).width() - popWidth) / 2)
					}, "fast");
				}
			}
		});
	},

	deactivatePE: function() {
		if (KNF.Popups.popupPositionPE) {
			$(window).unbind("scroll resize", KNF.Popups.popupPositionPE);
		}
	},

	nextOne: function() {
		if (!$("#knf_pop_box_outer").is(":visible")) {
			KNF.Popups.fetch("/popups/next");
		}
	},

	fetch: function(url, callback, sizeObj) {
		stopExecutor();
		$.ajax({
			url: url,
			dataType: "html",
			beforeSend: function() {
				KNF.Popups.prepare();
				KNF.Popups.hide();
			},
			success: function(data) {
				KNF.Popups.clear();
				var container = $("#knf_pop_box_outer");
				if (data) {
					if ($("#selfClosing").val() == "true") {
						window.setTimeout(KNF.Popups.hide, 25000);
					}
					container.html(data);
					KNF.Popups.show();
					if ($("#nope").val() == "true") {KNF.Popups.deactivatePE();}
					if (typeof callback === "function") {
						callback();
					}
				}
			},
			error: KNF.Popups.hide
		});
	},

	passChatPopup: function(id) {
		$.post("/meeting/pass", {id: id});
		KNF.Popups.hide();
	},

	acknowledgeChat: function(id) {
		$.post("/private_chat/acknowledge", {id: id});
		KNF.Popups.hide();
	},

	close: function() {
		KNF.Popups.hide();
		var e = $("[name=megaLive]").first();
		if (e && e.restoreMegaLive) {
			e.restoreMegaLive();
		}
	}
};

KNF.Invitations = {
	accept: function(id) {
		$.post("/meeting_subscription/mark_notified", {id: id, accept: true});
	},

	pass: function(id) {
		$.post("/meeting_subscription/mark_notified", {id: id});
	}
};

KNF.Forms = {
	deleteMany: function(form, prefix, hasMailbox) {
		$.post(form.action, $(form).serialize(), function(ids) {
			for (var i = 0, l = ids.length; i < l; i++) {
				$("#" + prefix + ids[i]).remove();
			}
			if (!$(".mbItem").length) {
				$("#empty_inbox_message").show();
			}
			if (hasMailbox) {
				mailboxActivate();
			}
		}, "json");
		return(false);
	}
};

function knf_flirt_checker(fromUserId, toUserId, origin, click_string) {
	trackClick(fromUserId, toUserId, 2, origin, click_string);
	setPopY(this);
	$.ajax({
		url: "/user/check_nudge",
		type: "POST",
		data: {id: toUserId},
		success: function (data) {
			if (data.fromLive) {
				if (data.mayFlirt) {
					KNF.Nudges.flirtLive(data.toUserId, data.fromIsBlacklisted);
				} else {
					showPaymentPopupForUserWithTrigger(data.toUserId, 2);
				}
			} else {
				if (!data.fromIsBlacklisted && data.mayFlirt) {
					KNF.Nudges.initiate2(data.toUserId, origin)
				} else {
					if (data.mayRequest) {
						KNF.Popups.fetch('/popups/fbinvite?id='+data.toUserId+'&type=2')
					} else {
						showPaymentPopupForUserWithTrigger(data.toUserId, 2);
					}
				}
			}
		}
	});
	return(false);
}

KNF.wstPopup = {
	activate: false,
	action: null,

	resize: function() {
		$("#wst-wrapper").height(380);
	},

	toggle: function() {
		$("#wst-prestep, #wst-wrapper").toggle();
	},

	uploadStarting: function() {
		$("#wst-wrapper a").remove();
	},

	check: function(user, action) {
		if (KNF.wstPopup.activate) {
			KNF.wstPopup.action = action;
			KNF.Popups.fetch("/popups/photoupload?id=" + user);
			return(false);
		}
		return(true);
	},

	done: function() {
		KNF.wstPopup.activate = false;
		if (KNF.wstPopup.action) {
			KNF.wstPopup.action();
		}
		KNF.Popups.close();
	}
}

function facebookInvite(title, responseHandler) {
	FB.ui({
		method: 'apprequests',
		message: 'Musst Du unbedingt mal ausprobieren!',
		title: title
	},
	function(response) {
		if (response && response.request_ids && response.request_ids.length>4) {
			responseHandler(true);
		} else {
			responseHandler(false);
		}
	});
}

function loadGallery(id, nick) {
	$.ajax({
		url: "/user/check_gallery",
		method: "post",
		success: function(data) {
			if (data == "1") {
				KNF.Popups.fetch("/popups/fbinvite?id=" + id + "&type=4");
			} else {
				window.location.href = "/profile/" + nick + "?tab=gallery";
			}
		}
	});
}

function startTabs(arg) {
	$("#user_start_new, #user_start_online, #user_start_themes").hide();
	$("#user_start_new_link, #user_start_online_link, #user_start_themes_link").removeClass();
	$("#" + arg).show();
	$("#" + arg + "_link").addClass("act");
}

KNF.Menu = {
	active: null,
	tabs: null,
	timer: null,

	init: function() {
		KNF.Menu.tabs = $("#main-menu a");
		KNF.Menu.active = KNF.Menu.tabs.filter(".act");
		$("#main-menu a div").mouseenter(KNF.Menu.hover);
		KNF.Menu.tabs.hover(KNF.Menu.stopTimer, KNF.Menu.startTimer);
		$("#sub-menu").hover(KNF.Menu.stopTimer, KNF.Menu.startTimer);
		KNF.Menu.reset();
	},

	hover: function(evt) {
		KNF.Menu.stopTimer();
		KNF.Menu.show(evt.currentTarget.parentNode);
	},

	stopTimer: function() {
		window.clearTimeout(KNF.Menu.timer);
		KNF.Menu.timer = null;
	},

	startTimer: function() {
		KNF.Menu.stopTimer();
		KNF.Menu.timer = window.setTimeout("KNF.Menu.reset()", 1000);
	},

	show: function(obj) {
		if ($(obj).length) {
			KNF.Menu.tabs.not(obj).removeClass("act");
			$(obj).addClass("act");

			if ($(obj).attr("id")) {
				var sub = $($(obj).attr("id").replace(/root_/g, "#sub_"));
				$("#sub-menu div").not(sub).hide();
				sub.show();
			}
		} else {
			$("#sub-menu div").hide();
			KNF.Menu.tabs.removeClass("act");
		}
	},

	reset: function() {
		KNF.Menu.show(KNF.Menu.active);
	}
};

KNF.StartTipps = {
	timer: null,

	init: function() {
		$("#start-tipps").hover(KNF.StartTipps.stopTimer, KNF.StartTipps.startTimer);
		KNF.StartTipps.startTimer();
	},
	
	stopTimer: function() {
		if(KNF.StartTipps.timer) {
			window.clearInterval(KNF.StartTipps.timer);
			KNF.StartTipps.timer = null;
		}
	},
	
	startTimer: function() {
		KNF.StartTipps.stopTimer();
		KNF.StartTipps.timer = window.setInterval("KNF.StartTipps.animate()", 5000);
	},
	
	animate: function() {
		$("#start-tipps img").stop(true, true).animate({"left": "-=100%"}, "slow", null, KNF.StartTipps.reset);
	},
	
	reset: function() {
		if (parseInt($(this).css("left")) < 0) {
			$(this).css("left", "300%");
		}
	}
};

KNF.SlideBox = {
	timer: null,
	num: 0,

	init: function() {
		KNF.SlideBox.num = $("#slide-box img").length;
		var links = $("#slide-box a");
		var rand = Math.floor(Math.random() * links.length);
		if (rand > 0) {
			for (var i = rand - 1; i >= 0; i --) {
				rand += $("img", links.get(i)).length - 1;
			}
		}
		rand = KNF.SlideBox.num - rand;
		$("#slide-box img").css({"position": "absolute", "top": 0}).each(function(idx, obj) {
			var x = (((idx + rand) % KNF.SlideBox.num) * 100);
			$(obj).css("left", x + "%");
		});
		if (KNF.SlideBox.num > 1) {
			$("#slide-box").hover(KNF.SlideBox.stopTimer, KNF.SlideBox.startTimer);
			KNF.SlideBox.startTimer();
		}
	},
	
	stopTimer: function() {
		if(KNF.SlideBox.timer) {
			window.clearInterval(KNF.SlideBox.timer);
			KNF.SlideBox.timer = null;
		}
	},
	
	startTimer: function() {
		KNF.SlideBox.stopTimer();
		KNF.SlideBox.timer = window.setInterval("KNF.SlideBox.animate()", 5000);
	},
	
	animate: function() {
		$("#slide-box img").stop(true, true).animate({"left": "-=100%"}, "slow", null, KNF.SlideBox.reset);
	},
	
	reset: function() {
		if (parseInt($(this).css("left")) < 0) {
			$(this).css("left", ((KNF.SlideBox.num - 1) * 100) + "%");
		}
	}
};

KNF.Similars = {
	w: 0,
	x: 0,
	
	arrows: function() {
		if (parseInt($(".similars .similar").first().css("left")) == KNF.Similars.x) {
			$("#similarsPrev").addClass("disabled");
		}
		if (parseInt($(".similars .similar").last().css("left")) == KNF.Similars.x) {
			$("#similarsNext").addClass("disabled");
		}
	},
	
	load: function (id, p) {
		p = p ? 0 + p : 1;
		$.ajax({
			url: "/user/similars",
			data: {"id": id, "page": p},
			success: KNF.Similars.init
		});
	},
	
	init: function(data, textStatus, XMLHttpRequest) {
		$("#similars").html(data);
		
		KNF.Similars.w = $("#similars .shiny-box").innerWidth();
		KNF.Similars.x = Math.floor((KNF.Similars.w - $("#similars .similar").first().outerWidth()) / 2);
			
		$(".similars .similar").each(function(idx, obj) {
			$(obj).css({"left": KNF.Similars.x + (idx * KNF.Similars.w), "top": 15});
		});
		
		$("#similarsPrev").click(function() {
			if (!$(this).hasClass("disabled")) {
				$(".similars .similar").animate({"left": "+=" + KNF.Similars.w}, "slow", null, KNF.Similars.arrows);
				$("#similarsNext").removeClass("disabled");
			}
		});
		
		$("#similarsNext").click(function() {
			if (!$(this).hasClass("disabled")) {
				$(".similars .similar").animate({"left": "-=" + KNF.Similars.w}, "slow", null, KNF.Similars.arrows);
				$("#similarsPrev").removeClass("disabled");
			}
		});
	}
}

KNF.Login = {
	toggle: function() {
		$('#form-login, #form-login-close, #link-login, #fb-login, #headlines').fadeToggle();
	}
}

KNF.init = function() {
	KNF.Menu.init();
	KNF.StartTipps.init();
	$("a.external").click(function(evt) {window.open(evt.currentTarget.href, "_blank"); return(false);});
}

$(KNF.init);

KNF.Live = new function() {
	this.TYPE_MESSAGE = 0;
	this.TYPE_MESSAGE_RESPONSE = 1;
	this.TYPE_FRIEND_REQUEST = 2;
	this.TYPE_FRIEND_REQUEST_RESPONSE = 5;
	this.TYPE_CHAT_REQUEST = 3;
	this.TYPE_GAME_REQUEST = 4;
	
	this.flirtLimitPopup = false

	this.MessageBox = function(senderName, senderID) {
		this.box = $("<div class=\"MessageBox\"/>");
		
		$("<a href=\"#\" class=\"MessageBoxClose\">X</a>").appendTo(this.box).click(KNF.Live.close);
		$("<a href=\"#\" class=\"MessageBoxVideochat\" title=\"Videochat starten\"></a>").appendTo(this.box).click({"id": senderID}, KNF.Live.startChat);
		$("<a href=\"#\" class=\"MessageBoxAddfriend\" title=\"Kontaktanfrage senden\"></a>").appendTo(this.box).click({"id": senderID}, KNF.Live.addfriend);
		
		$("<span class=\"MessageBoxTitle\">" + senderName + "</span>").click({"login": senderName}, KNF.Live.gotoProfile).appendTo(this.box);
		
		this.content = $("<div class=\"MessageBoxContent\"/>");
		this.content.appendTo(this.box);
		
		var form = $("<div class=\"MessageBoxForm\"/>").appendTo(this.box);
		this.text = $("<input class=\"MessageBoxText\" type=\"text\" id=\"text_" + senderID + "\"/>").appendTo(form);
		this.button = $("<input class=\"MessageBoxButton\" type=\"submit\" id=\"button_" + senderID + "\"/>").appendTo(form);
		this.button.attr("value", " ");
		this.button.click(function() {
			if (KNF.Live.elements[senderID].mayFlirt) {
				KNF.Live.sendMessage(senderID, $("#text_" + senderID).val());
			} else if (!KNF.Live.flirtLimitPopup) {
				KNF.Live.flirtLimitPopup = true;
				KNF.Popups.fetch("/popups/flirtlimit?id=" + senderID);
			}
		});
		this.text.keypress(function(evt) {
			if (KNF.Live.elements[senderID].mayFlirt) {
				if (evt.which == 13) $("#button_" + senderID).click();
			} else if (!KNF.Live.flirtLimitPopup) {
				KNF.Live.flirtLimitPopup = true;
				KNF.Popups.fetch("/popups/flirtlimit?id=" + senderID);
			}
		});

		this.box.appendTo("#megalive_messages");
	};
	
	this.startChat = function(evt) {
		var senderID = evt.data.id;
		var flash = Flash.get("megaLive");
		if (flash) flash.requestPrivateLiveChat(senderID);
	};
	
	this.addfriend = function(evt) {
		var senderID = evt.data.id;
		var flash = Flash.get("megaLive");
		if (flash) flash.connectRequest(senderID);
		knfMessage("Deine Kontaktanfrage wurde verschickt.", [{title: "OK", cssclass: "btn-red bw90"}]);
	};
	
	this.sendMessage = function(id, msg) {
		if (msg && msg.length) {
			$("#text_" + id).val("");
			
			var flash = Flash.get("megaLive");
			if (flash) flash.sendMessage(id, msg)
		}
	};

	this.LiveEvent = function(type, senderName, senderID, senderImage, message) {
		this.type = type;
		this.senderName = senderName;
		this.senderID = senderID;
		this.senderImage = senderImage;
		this.message = message;
	};
	
	this.LiveEvent.prototype.is_valid = function() {
		return((this.type >= 0) && (this.type <= 5) && this.senderID);
	};
	
	this.elements = {};
	this.handleFriendRequest = function(evt) {
		$(evt.currentTarget).parent().remove();
		if (evt.data.accepted) {
			KNF.Live.handleEvent(new KNF.Live.LiveEvent(KNF.Live.TYPE_FRIEND_REQUEST, "", evt.data.id, "", "true"));
		} else {
			KNF.Live.handleEvent(new KNF.Live.LiveEvent(KNF.Live.TYPE_FRIEND_REQUEST, "", evt.data.id, "", "false"));
		}

		var flash = Flash.get("megaLive");
		if (flash) flash.handleAccept(1, evt.data.id, evt.data.accepted);
		return(false);
	};
	
	this.handleChatRequest = function(evt) {
		$(evt.currentTarget).parent().remove();
		if (evt.data.accepted) {
			KNF.Live.handleEvent(new KNF.Live.LiveEvent(KNF.Live.TYPE_CHAT_REQUEST, "", evt.data.id, "", "true"));
		} else {
			KNF.Live.handleEvent(new KNF.Live.LiveEvent(KNF.Live.TYPE_CHAT_REQUEST, "", evt.data.id, "", "false"));
		}

		var flash = Flash.get("megaLive");
		if (flash) flash.handleAccept(2, evt.data.id, evt.data.accepted);
		return(false);
	};
	
	this.handleGameRequest = function(evt) {
		$(evt.currentTarget).parent().remove();
		if (evt.data.accepted) {
			KNF.Live.handleEvent(new KNF.Live.LiveEvent(KNF.Live.TYPE_GAME_REQUEST, "", evt.data.id, "", "true"));
		} else {
			KNF.Live.handleEvent(new KNF.Live.LiveEvent(KNF.Live.TYPE_GAME_REQUEST, "", evt.data.id, "", "false"));
		}
		
		var flash = Flash.get("megaLive");
		if (flash) flash.handleAccept(3, evt.data.id, evt.data.accepted);
		return(false);
	};

	this.handleEvent = function(evt) {
		if (evt.is_valid()) {
			if (!this.elements[evt.senderID]) {
				this.elements[evt.senderID] = new this.MessageBox(evt.senderName, evt.senderID);
			}

			var msg = $("<div class=\"Message\"/>");
			switch(evt.type) {
				case this.TYPE_MESSAGE:
					$("<img class=\"img\" src=\"" + evt.senderImage + "\" alt=\"\" width=\"60\" height=\"60\"/>").css("cursor", "pointer").click({"login": evt.senderName}, KNF.Live.gotoProfile).appendTo(msg);
					msg.append(evt.message);
					break;
				case this.TYPE_MESSAGE_RESPONSE:
					$("<img class=\"img\" src=\"" + KNF.User.profileImageTiny + "\" alt=\"\" width=\"60\" height=\"60\"/>").appendTo(msg);
					msg.append(evt.message);
					break;
				case this.TYPE_FRIEND_REQUEST:
					$("<img class=\"img\" src=\"/images/evo4/megalive/sym-addfriend.png\" alt=\"\" width=\"60\" height=\"60\"/>").appendTo(msg);
					if (evt.message && evt.message.length) {
						if (evt.message == "true") {
							msg.append("Du hast die Kontaktanfrage angenommen.");
						} else {
							msg.append("Du hast die Kontaktanfrage abgelehnt.");
						}
						KNF.Live.hideAddfriend(evt.senderID);
					} else {
						msg.append("möchte Dich als Kontakt hinzufügen. Annehmen?<div class=\"spc5\"/>");
						var yes = $("<a href=\"#\" id=\"fr_yes_" + evt.senderID + "\" class=\"btn-red bw30\">Ja</a>");
						var no = $("<a href=\"#\" id=\"fr_no_" + evt.senderID + "\" class=\"btn-blue bw30\">Nein</a>");
						yes.click({"id": evt.senderID, "accepted": true}, KNF.Live.handleFriendRequest);
						no.click({"id": evt.senderID, "accepted": false}, KNF.Live.handleFriendRequest);
						msg.append(yes, "\n", no);
					}
					break;
				case this.TYPE_FRIEND_REQUEST_RESPONSE:
					$("<img class=\"img\" src=\"/images/evo4/megalive/sym-addfriend.png\" alt=\"\" width=\"60\" height=\"60\"/>").appendTo(msg);
					if (evt.message && evt.message.length) {
						if (evt.message == "true") {
							msg.append("hat die Kontaktanfrage angenommen.<div class=\"spc5\"/>");
							$("<a href=\"#\" class=\"btn-red bw130\">Jetzt chatten</a>").click({"id": evt.senderID}, KNF.Live.startChat).appendTo(msg);
						} else {
							msg.append("hat die Kontaktanfrage abgelehnt.");
						}
						KNF.Live.hideAddfriend(evt.senderID);
					} else {
						msg.append("Deine Kontaktanfrage wurde gesendet.");
					}
					break;
				case this.TYPE_CHAT_REQUEST:
					$("<img class=\"img\" src=\"/images/evo4/megalive/sym-chat.png\" alt=\"\" width=\"60\" height=\"60\"/>").appendTo(msg);
					if (evt.message && evt.message.length) {
						if (evt.message == "true") {
							msg.append("Du hast die Chatanfrage angenommen.");
						} else {
							msg.append("Du hast die Chatanfrage abgelehnt.");
						}
					} else {
						msg.append("möchte mit Dir chatten! Annehmen?<div class=\"spc5\"/>");
						var yes = $("<a href=\"#\" id=\"chat_yes_" + evt.senderID + "\" class=\"btn-red bw30\">Ja</a>");
						var no = $("<a href=\"#\" id=\"chat_no_" + evt.senderID + "\" class=\"btn-blue bw30\">Nein</a>");
						yes.click({"id": evt.senderID, "accepted": true}, KNF.Live.handleChatRequest);
						no.click({"id": evt.senderID, "accepted": false}, KNF.Live.handleChatRequest);
						msg.append(yes, "\n", no);
					}
					break;
				case this.TYPE_GAME_REQUEST:
					$("<img class=\"img\" src=\"/images/evo4/megalive/sym-game.png\" alt=\"\" width=\"60\" height=\"60\"/>").appendTo(msg);
					if (evt.message && evt.message.length) {
						if (evt.message == "true") {
							msg.append("Du hast die Spielanfrage angenommen.");
						} else {
							msg.append("Du hast die Spielanfrage abgelehnt.");
						}
					} else {
						msg.append("möchte mit Dir spielen! Annehmen?<div class=\"spc5\"/>");
						var yes = $("<a href=\"#\" id=\"game_yes_" + evt.senderID + "\" class=\"btn-red bw30\">Ja</a>");
						var no = $("<a href=\"#\" id=\"game_no_" + evt.senderID + "\" class=\"btn-blue bw30\">Nein</a>");
						yes.click({"id": evt.senderID, "accepted": true}, KNF.Live.handleGameRequest);
						no.click({"id": evt.senderID, "accepted": false}, KNF.Live.handleGameRequest);
						msg.append(yes, "\n", no);
					}
					break;
			}
			msg.appendTo(this.elements[evt.senderID].content);
			KNF.Live.scrollDown(evt.senderID);
		}
	};
	
	this.gotoProfile = function(evt) {
		document.location.href = "/profile/" + evt.data.login;
		return(false);
	};

	this.scrollDown = function(id) {
		var h = 0;
		$("div", this.elements[id].content).each(function (i, obj) {h += $(obj).outerHeight();});
		$(this.elements[id].content).scrollTop(h);
	};

	this.Event = function(evtArray) {
		if (evtArray && evtArray.length) {
			for (var i = 0, c = evtArray.length; i < c; i++) {
				var evt = evtArray[i];
				KNF.Live.handleEvent(new KNF.Live.LiveEvent(evt.type, evt.partnerName, evt.partnerID, evt.partnerImage, evt.message));
			}
			
		}
	};
	
	this.removeAll = function(partnerID) {
		if (this.elements[partnerID]) {
			$(this.elements[partnerID].box).remove();
			this.elements[partnerID] = null;
		}
		return(false);
	};

	this.close = function() {
		var flash = Flash.get("megaLive");
		if (flash) flash.hideChat();
		return(false);
	};

	this.hide = function() {
		$("#megalive_messages .MessageBox:visible").hide();
		return(false);
	};

	this.hideAddfriend = function(partnerID) {
		if (this.elements[partnerID]) {
			$(".MessageBoxAddfriend", this.elements[partnerID].box).remove();
		}
	};

	this.show = function(senderID, mayFlirt) {
		KNF.Live.flirtLimitPopup = false;
		if (this.elements[senderID]) {
			this.elements[senderID].mayFlirt = mayFlirt;
			$(this.elements[senderID].box).fadeIn("fast");
			KNF.Live.scrollDown(senderID);
		}
		return(false);
	};
	
	this.init = function() {
		$(window).resize(function() {
			$("#megalive_messages").css({"right": Math.max(0, ($(window).width() - 1000) / 2)});
		});
		$(function() {$(window).resize();});
	};
};


