$.fn.jShare = function() {
    var url = [];
    var fb = [];
    var google = [];
    var yeah = [];
    var wtf = [];
    var count = [];
	var dbcount = [];
    var el = $(this);
	var jchild = [];
	
    function failWait() {
        el.each(function(i, e) {
            var ul = "<ul>";
			ul = ul + "<li><img class='icon smile' style='margin-bottom: -4px;' src='img/blank.png'> " + yeah[i] + " ";
			ul = ul + "<img class='icon wtf' style='margin-bottom: -4px;' src='img/blank.png'> " + wtf[i] + "</li>";
			ul = ul + "<li>" + fb[i] + "</li><li>" + google[i] + "</li></ul>";
            var likes = "Likes";
            if (count[i] == 1) {
                likes = "Like";
            }
			if (count[i] == 0) { $(this).css("color", "#999999"); }
            $(this).html("<span>&hearts; " + count[i] + " " + likes + "</span>" + ul);
			
			if (dbcount[i] * 1 < count[i] * 1)
			{
				jchild[i] = {
					"permalink" : url[i],
					"rating": count[i]
				}
			}
        });
        gapi.plusone.go();
		
		var j = {"media": jchild};
		$.post("graph.php", j, "json");
    }

    el.each(function(i, e) {
		$(this).html("...");
        url[i] = $(this).attr("href");
        fb[i] = '<iframe src="http://www.facebook.com/plugins/like.php?layout=button_count&show_faces=false&width=120&action=like&font=verdana&colorscheme=light&height=21&href=' + url[i] + '" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:200px; height:20px; text-align: right;" allowTransparency="true"></iframe>';
        google[i] = "<g:plusone size='medium' href='" + url[i] + "'></g:plusone>";
        count[i] = 0;
        yeah[i] = 0;
        wtf[i] = 0;
		dbcount[i] = 0;
        // Facebook
        $.getJSON("http://graph.facebook.com/?id=" + url[i], function(a) {
            if (a.shares != "undefined" && a.shares) {
                count[i] = count[i]+(a.shares*1);
            }
        });
        $.getJSON("http://www.mypoo.de/graph.php?url=" + url[i], function(a) {
			dbcount[i] = a.rating*1;
            yeah[i] = a.yeah*1;
            wtf[i] = a.wtf*1;
			count[i] = count[i]+yeah[i]+wtf[i];
        });
    });
    setTimeout(failWait, 4000);
};

function bewerten(id, klick)
{
	$.ajax({
		type: 'POST',
		url: 'bewertung.php',
		data: 'id=' + id + '&rate=' + klick,
		success: function(html) { $('#vote_' + id).html(html); }
		});
}
function bewerten_kommentar(id, klick)
{
	$.ajax({
		type: 'POST',
		url: 'bewertung.php',
		data: 'kommentar=' + id + '&rate=' + klick,
		success: function(html) { $('#vote_kommentar_' + id).html(html); }
		});
}
function gut(id, klick)
{
	if (klick < 3)
	{
		$.ajax({
			type: 'POST',
			url: 'ajax_gut.php',
			data: 'status=' + id + '&klick=' + klick,
			success: function(html) { $('#' + id).html(html); }
			});
		$("#klick1_" + id).hide();
		$("#klick2_" + id).hide();
	}
	else
	{
		$.ajax({
			type: 'POST',
			url: 'ajax_gut.php',
			data: 'status=' + id,
			success: function(html) { $('#' + id).html(html); }
			});
	}
}
function bewerten_bad(id, klick)
{
	$.ajax({
		type: 'POST',
		url: 'bewertung_bad.php',
		data: 'id=' + id + '&rate=' + klick,
		success: function(html) { $('#vote_bad_' + id).html(html); }
		});
}
function status_klappen(datum)
{
	klapptext = document.getElementById("klapptext_" + datum);
	klappfeld = document.getElementById("status_hide_" + datum);

	klapptext.style.display = "none";
	$("#status_hide_" + datum).slideDown("slow");
}
function statusKommentar(key)
{
	var k = new Array();
	// Wenn Array
	if ($.isArray(key))
	{
		$.each(key, function(x, y) {
			k.push('{ "id": "' + y + '" }');
		});
	}
	else
	{
		k.push('{ "id": "' + key + '" }');
	}
	
	// Baue JSON String auf
	var text = '{"items": [' + k.join(", ") + ']}';
	$.ajax({
		type: 'POST',
		url: 'status.php',
		data: "key=" + escape(text),
		dataType: "json",
		success: function(data) { 
			$.each(data.items, function(x, y) {
				$("#kommentare_" + y.id).html("<ul class='status_kommentar'></ul>");
			});
			$.each(data.items, function(x, y) {
				$("#kommentare_" + y.id + " > ul").append('<li>\
					<small>\
					<div style="float: left; width: 40px; height: 40px; background: url(avatar.php?id=' + y.user + '&size=40) no-repeat;" class="round avatar"></div>\
					<div style="margin-left: 50px;">\
					' + y.del + '\
					<a href="profil.php?id=' + y.user + '">' + y.username + '</a> \
					<span class="meta"> @ ' + y.datum + '</span><br/>\
					' + y.inhalt + '\
					</div><div class="clear"></div>\
					</small>\
					</li>');
			});
		}
	});
}

function blass(bild, wie)
{
	if (wie == "in")
	{
		$("#"+bild).fadeTo("fast",1);
	}
	if (wie == "out")
	{
		$("#"+bild).fadeTo("normal",0,4);
	}
}
function facebox_link(ziel)
{
	jQuery.facebox(function($){jQuery.get(ziel,function(data){jQuery.facebox(data);})});
}
function facebox_submit(ziel, feld)
{
	var inhalt = escpae(document.getElementById(feld).value);
	jQuery.facebox(function($){jQuery.get(ziel + "&" + feld + "=" + inhalt,function(data){jQuery.facebox(data);})});
}

function init_tinymce()
{
	tinyMCE.init({
	    theme : "advanced",
	    mode: "exact",
	    skin : "o2k7",
	    elements : "frm_inhalt",
	    plugins: "emotions",
	    theme_advanced_toolbar_location : "top",
	    theme_advanced_buttons1 : "forecolor,bold,italic,underline,strikethrough,charmap,separator,"
	    + "justifyleft,justifycenter,justifyright,justifyfull,"
	    + "bullist,numlist,outdent,indent,separator,link,unlink,image,separator,"
	    +"code,emotions",
	    theme_advanced_buttons2 : "",
	    theme_advanced_buttons3 : "",
	    height:"350px",
	    width:"95%"
	  });
	  
	tinyMCE.init({
	    theme : "advanced",
	    mode: "exact",
	    skin : "o2k7",
		skin_variant : "black",
	    elements : "frm_kommentar",
	    plugins: "emotions",
	    theme_advanced_toolbar_location : "top",
	    theme_advanced_buttons1 : "bold,italic,underline,strikethrough,separator,"
	    + "link,unlink,code,emotions",
	    theme_advanced_buttons2 : "",
	    theme_advanced_buttons3 : "",
	    height:"60px",
	    width:"552px"
	  });
}
init_tinymce();

/* *****************************************
POPUP FUNKTIONEN
***************************************** */
function popup_einladen()
{
	var email = document.getElementById("einladen_email").value;
	var name = document.getElementById("einladen_name").value;
	facebox_link("einladen.php?einladen_email=" + email + "&einladen_name=" + name);
}
function popup_login()
{
	var user = document.getElementById("login_user").value;
	var pass = document.getElementById("login_pass").value;
	facebox_link("login.php?login_user=" + escape(user) + "&login_pass=" + escape(pass));
}
function popup_status()
{
	var s_u = document.getElementById("s_u").value;
	var s_d = document.getElementById("s_d").value;
	var status = document.getElementById("status_inhalt").value;
	facebox_link("statuskommentar.php?s_u=" + s_u + "&s_d=" + s_d + "&status_inhalt=" + escape(status));
}
function popup_melden()
{
	var id = document.getElementById("melden_id").value;
	var melden = document.getElementById("melden_inhalt").innerHTML;
	$.ajax({
		type: 'POST',
		url: 'melden.php',
		data: "id=" + id + "&melden_inhalt=" + escape(melden),
		success: function(html) { jQuery.facebox("Vielen Dank, deine Meldung wurde weiter geleitet. Du kannst dieses Fenster jetzt schliessen."); }
		});
}
function popup_media_edit()
{
	var id = document.getElementById("media_id").value;
	var seite = document.getElementById("media_seite").value;
	var media = tinyMCE.activeEditor.getContent();
	
	$.ajax({
		type: 'POST',
		url: 'media_edit.php',
		data: 'id=' + id + '&media_inhalt=' + escape(media),
		success: function(html) { parent.location.href = "media.php?id=" + seite; }
		});
}
function popup_forum_edit()
{
	var id = document.getElementById("forum_id").value;
	var seite = document.getElementById("forum_thread").value;
	var titel = document.getElementById("forum_titel").value;
	var media = tinyMCE.activeEditor.getContent();
	$.ajax({
		type: 'POST',
		url: 'forum_edit.php',
		data: 'id=' + id + '&forum_inhalt=' + escape(media) + "&forum_titel=" + escape(titel),
		success: function(html) { parent.location.href = "forum.php?id=" + seite + "&edit_done=1"; }
		});
	
}

/*
jQUERY PLUGINS
*/

/**
 * Edit-in-place with contentEditable property (FF2 is not supported)
 * Project page - http://valums.com/edit-in-place/
 * Copyright (c) 2008 Andris Valums, http://valums.com
 * Licensed under the MIT license (http://valums.com/mit-license/)
 * Version 0.4 (27.02.2009)
 */
(function(){
var d = document, w = window;

/**
 * Get element by id
 */	
function $(element){
	if (typeof element == "string")
		element = d.getElementById(element);
	return element;
}

/**
 * Attaches event to a dom element
 */
function addEvent(el, type, fn){
	if (w.addEventListener){
		el.addEventListener(type, fn, false);
	} else if (w.attachEvent){
		var f = function(){
		  fn.call(el, w.event);
		};			
		el.attachEvent('on' + type, f)
	}
}


if (jQuery){
	jQuery.fn.editable = function(onChange){
		return this.each(function(){
			editableAreas.add(this, onChange);
		});
	};
}

editableAreas = {
	enterDisabled : false
	,instances : []
	,active : null
	,inited : false
	,init : function(){
		var self = this;
		// attach enter keypress capturer to document
		addEvent(d, 'keypress', function(e){
			// find which key was pressed (code from jQuery library)
			if ( !e.which && ((e.charCode || e.charCode === 0) ? e.charCode : e.keyCode)){
				e.which = e.charCode || e.keyCode;	
			}

			if (self.enterDisabled && (e.which == 13)) {
				if (e.preventDefault) e.preventDefault();				
				else e.returnValue = false;
			}
		});
		
		addEvent(d, 'click', function(e){
			var target = e.target ? e.target : e.srcElement || document;

			while (target.nodeName != "HTML"
				&& target.nodeName != "BODY"
				&& target.contentEditable != true && target.contentEditable != 'true')
				// contentEditable is boolean in Opera
			{										
				target = target.parentNode;				
			}

			if (self.active && (self.active.el !== target)){
				// User clicked outside of editable area
				self.enterDisabled = false;
				self.active.onChange.call(self.active.el, self.active.el);
				self.active = null;												
			}
			
			if ( ! self.active){				
				var i = self.indexOfEditable(target);
				if (i !== -1){
					if (target.nodeName != 'DIV'){						
						//disable line breaks for h1..h5,p,etc ..
						self.enterDisabled = true;
					}
					self.active = self.instances[i];
				}			
			}
		});
		
		this.inited = true;				
	}
	,add : function(el, onChange){
		el = $(el);
		onChange = onChange ||	function(){};
		// FF2 doesn't support contentEditable
		el.contentEditable = true;
		this.instances.push({el:el, onChange:onChange});
		
		if (!this.inited) this.init();		
	}
	,indexOfEditable : function(el){
		for (var i=0, length = this.instances.length; i < length; i++){				
			if (this.instances[i].el === el){
				return i;
			}	
		}				
		return -1;
	}
	
	};
})();

function chatStart(user, name) {
	// Existiert das Fenster bereits?
	if ($("#chat_user_" + user).attr("id"))
	{
		$("#chat_user_" + user).css("background", "#c00");
	}
	else
	{
		if (user > 0)
		{
			$("#chat_tabs").append(
				"<div id='chat_user_" + user + "' rel='chat_child' style='background: #777;'><input type='hidden' id='chat_last_" + user + "'><div class='chat_sidebar_name'> \
						<img src='img/chat_close.png' align='right' id='chat_close_" + user + "' style='margin-top: 3px; cursor: pointer;' alt='Schliessen' title='Schliessen'> \
						<img src='avatar.php?id=" + user + "&size=22' style='margin-bottom: -5px'> \
						" + name + " \
						<div class='clear'></div> \
						<div class='chat_window'> \
							<div class='chat_input'> \
								<input type='text' id='input_user_" + user + "'> \
							</div> \
							<div class='chat_output' id='chat_output_" + user + "'></div> \
							<div class='clear'></div> \
						</div> \
				</div></div>"
			);
		}
		else
		{
			$("#chat_tabs").append(
				"<div id='chat_user_" + user + "' rel='chat_child' style='background: #777;'><input type='hidden' id='chat_last_" + user + "'><div class='chat_sidebar_name'> \
						<img src='img/chat_home.png' style='margin-bottom: -5px'> \
						" + name + " \
						<div class='clear'></div> \
						<div class='chat_window'> \
							<div class='chat_input'> \
								<input type='text' id='input_user_" + user + "'> \
							</div> \
							<div class='chat_output' id='chat_output_" + user + "'></div> \
							<div class='clear'></div> \
						</div> \
				</div></div>"
			);
		}
		$("#chat_user_" + user).bind("mouseover", function() {
			$("#chat_user_" + user + " .chat_window").show();
			$("#chat_user_" + user).css("background", "#333");
		});
		$("#chat_user_" + user).bind("mouseout", function() {
			$("#chat_user_" + user + " .chat_window").hide();
			$("#chat_user_" + user).css("background", "#777");
		});
		
		// Schliessen
		$("#chat_close_" + user).bind("mouseover", function() {
			$(this).attr("src", "img/chat_close_.png");
		});
		$("#chat_close_" + user).bind("mouseout", function() {
			$(this).attr("src", "img/chat_close.png");
		});
		$("#chat_close_" + user).bind("click", function() {
			$.ajax({
				type: "POST",
				url: "ajax_chat.php",
				data: "was=close&an=" + user,
				success: function(html) {
					$("#chat_user_" + user).remove();
				}
			});
		});
		
		// Input
		$("#input_user_" + user).bind("keypress", function(e) {
			var id = "#input_user_" + user;
			if (e.which == 13)
			{
				$.ajax({
					type: "POST",
					url: "ajax_chat.php",
					data: "was=msg&an=" + user + "&msg=" + escape($(id).val()),
					success: function() {
						$(id).val("");
					}
				});
			}
		});
	}
}

function chatUpdate() {
	var debug = "";
	$("[rel=chat_child]").each(function() {
		var id = $(this).attr("id");
		var user = id.split("_");
		
		$.ajax({
			type: "POST",
			url: "ajax_chat.php",
			data: "was=get&last=" + $("#chat_last_" + user[2]).val() +"&chat=" + user[2],
			success: function(html) {
				if (html > "")
				{
					$("#chat_output_" + user[2]).prepend(html);
					var last = $("#chat_output_" + user[2] + " div:first-child").attr("id");
					$("#chat_last_" + user[2]).val(last);
					var von = last.split("_");
					if (von[1] != $("#chatter").val())
					{
						$("#chat_user_" + user[2]).css("background", "#f90");
					}
				}
			}
		});
		
		debug = debug + user[2] + ", ";
	});
	
	// $("#chat_debug").html(debug);
	
	setTimeout("chatUpdate()", 4000);
}

function ssp_ergebnis()
{
	$("#ssp_ergebnis").html("<img src='img/ajax-loader.gif'>");
	$.ajax({
		type: "POST",
		url: "ajax_ssp.php",
		data: "ergebnis=1",
		success: function(html) {
			$("#ssp_ergebnis").html(html);
		}
	});
}
function ssp(was)
{
	$.ajax({
		type: "POST",
		url: "ajax_ssp.php",
		data: "was=" + was,
		success: function(html) {
			$("#ssp").hide();
			if (html == "offen")
			{
				$("#ssp_offen").show();
			}
			if (html == "fertig")
			{
				ssp_ergebnis();
				$("#ssp").show();
			}
		}
	});
}


jQuery.fn.aPosition = function() {
	thisLeft = this.offset().left;
	thisTop = this.offset().top; 
	thisParent = this.parent();
	parentLeft = thisParent.offset().left;
	parentTop = thisParent.offset().top;
	return {
	left: thisLeft-parentLeft, 
	top: thisTop-parentTop
	}
}
$(document).ready(function() {
	$("#suchesubmit").click(function() { $("#suchform").submit(); });
	
	$(".fade")
		.fadeTo(0,0.7)
		.mouseenter(function() {
			$(this).fadeTo(0, 1);
		})
		.mouseleave(function() {
			$(this).fadeTo(500, 0.7);
		});
	
	$("[rel='setinfo']")
		.hide()
		.css("z-index", "1000");
	$("[rel='setbild']")
		.fadeTo(0, 0.7)
		.css("z-index", "500")
		.mouseenter(function() {
			var t = $(this);
			t
				.fadeTo(0, 1)
				.animate({ height: 80, marginTop: -7 }, 150);
			
			var name = t.attr("name");					
			var top = t.position().top;
			var left = t.position().left;
			
			var info = $("#" + name);
			
			info
				.css("left", (left + 67 - info.width()) + "px")
				.css("top", top + 80 + "px")
				.fadeTo(500, 1);
		})
		.mouseleave(function() {
			var t = $(this);
			t
				.animate({ height: 66, marginTop: 0 }, 150)
				.fadeTo(500, 0.7);
			var name = $(this).attr("name");
			$("#" + name).hide();
		});
	
	$("[rel='medialiste']")
		.mouseenter(function() {
			$(this)
				.children("[rel='mediameta']").show();
		})
		.mouseleave(function() {
			$(this)
				.children("[rel='mediameta']").hide();
		})
	
	$("#frm_status")
		.focus(function() {
			if ($(this).val() == "Was gibts Neues?") { $(this).val(""); }
		})
		.blur(function() {
			if ($(this).val() == "") { $(this).val("Was gibts Neues?"); }
		});
	
	$("ul.seitenmenu > li")
		.hover(function() {
				$(this).animate({ paddingLeft: 10 }, 150);
			},
			function() {
				$(this).animate({ paddingLeft: 0 }, 150);
			});
			
	ssp_ergebnis(); // Schere, Stein, Papier

	$('input[rel=datum]').datepicker({
		dateFormat: 'dd.mm.yy',
		firstDay: 1
	});
	
	$('a[rel*=facebox]').facebox({
		noAutoload: true
	  });
	  
	// Statuseingabe
	$("#frm_status").focus(function() {
		$(this).addClass("index_status_aktiv");
		$("#frm_status_hidden").removeClass("hidden");
	});
				
	$("td[rel=preview_rechts]").mouseover(function() {
		$(this).css("color","#cc0");
	});
	$("td[rel=preview_rechts]").mouseout(function() {
		$(this).css("color","#666");
	});
	
	$("[rel*=gut]").each(function() {
		gut($(this).attr("id"));
	});
	
	
	$("#frm_suche").css("color","#ccc");
	$("#frm_suche").attr("value","Suche...");
	$("#frm_suche").focus(function() {
		$(this).css("color","#fff");
		if ($(this).attr("value") == "Suche...")
		{
			$(this).attr("value","");
		}
	});
	$("#frm_suche").blur(function() {
		if ($(this).attr("value") == "")
		{
			$(this).css("color","#ccc");
			$(this).attr("value","Suche...");
		}
	});
	
	$(".popup li").mouseover(function() {
		$(this).css("background-color", "#ddd");
	});
	$(".popup li").mouseout(function() {
		$(this).css("background-color", "transparent");
	});
				
	var keys = new Array();
	
	$("[rel=antwort_status]").each(function() {
		var key = $(this).attr("name");
		keys.push(key);
		
		$(this).click(function() {
			$("#antwort_" + key).show();
			$("#input_" + key).focus();
		});
		
		$("#antwort_close_" + key).click(function() {
			$("#antwort_" + key).hide();
		});
		
		$("#antwort_do_" + key).click(function() {
			$("#antwort_" + key).fadeOut();
			$("#antwort_info_" + key).addClass("hidden");
			$("#antwort_load_" + key).show();
			
			$.ajax({
				type: 'POST',
				url: 'status.php',
				data: 'aktion=put&key=' + key + '&inhalt=' + escape($("#input_" + key).val()),
				success: function(html) { 
					$("#input_" + key).val("");
					$("#antwort_load_" + key).hide();
					$("#antwort_" + key).hide();
					statusKommentar(key);
				},
				error: function(html) {
					$("#antwort_info_" + key).html("Konnte nicht gespeichert werden");
					$("#antwort_info_" + key).removeClass("hidden");
					$("#antwort_load_" + key).hide();
					$("#antwort_" + key).fadeIn();
					statusKommentar(key);
				}
			});
			
		});
	});
	
	statusKommentar(keys);
	
	/*
	$("#c_chat").mouseover(function() {
		$("#chat_start").show();
		$("#c_bar").css("background-color", "#333");
	});
	$("#c_chat").mouseout(function() {
		$("#chat_start").hide();
		$("#c_bar").css("background-color", "#666");
	});
	$("#chat_suche").bind("keyup", function() {
		$.ajax({
			type: "POST",
			url: "ajax_chat.php",
			data: "was=suche&suche=" + escape($(this).val()),
			success: function(html) {
				$("#chat_suche_out").html(html);
			}
		});						
	});
	chatUpdate();
	*/
	$("[rel=preview_rechts]").click(function() {
		document.location.href='about.php';
	});
	
	$(".rating_yeah")
		.click(function() {
			var id = $(this).attr("id").split("_"); // id[1]
			$.ajax({
				type: 'POST',
				url: 'bewertung.php',
				data: 'id=' + id[1] + '&rate=1',
				success: function(html) { 
					$('#' + id[0] + '_' + id[1] + " > .rating_count").html(html); 
				}
			});
		})
		.mouseenter(function() {
			$(this).css("background-color", "#fff");
		})
		.mouseleave(function() {
			$(this).css("background-color", "#eee");
		});
	$(".rating_wtf")
		.click(function() {
			var id = $(this).attr("id").split("_"); // id[1]
			$.ajax({
				type: 'POST',
				url: 'bewertung_bad.php',
				data: 'id=' + id[1] + '&rate=1',
				success: function(html) { 
					$('#' + id[0] + '_' + id[1] + " > .rating_count").html(html); 
				}
			});
		})
		.mouseenter(function() {
			$(this).css("background-color", "#fff");
		})
		.mouseleave(function() {
			$(this).css("background-color", "#eee");
		});
	
	
	$(".shares").jShare();
});
