var closeicon = "close_info.gif";
var imgpath = "/res/gfx/";

var update_delay = 18000; // in ms
var msgcount = 0;
var pblock = false;
var loading = "<div style='text-align:center; margin:10px;'><img src='"
		+ imgpath + "spinner.gif'></div>";
var loading2 = "<img src='" + imgpath + "spinner.gif'> Bitte warten...";
imgPreloader = new Image();
imgPreloader.src = imgpath + "spinner.gif";

function isdefined(variable) {
	return (typeof (variable) == "undefined") ? false : true;
}
function eventinfo(id) {
	PopUp(660, 550, '/ausgehen/events/detail/?id=' + id, true);
}

function locinfo(id) {
	PopUp(460, 550, '/ausgehen/locations/detail/?id=' + id);
}

function startchat(id, join, room) {
	PopUp(710, 460, '/community/chat/?id=' + id + '&join=' + join + '&roomid='
			+ room);
}

function displayChange(id) {
	if ($(id).getStyle('display') == 'block')
		$(id).setStyle('display', 'none');
	else
		$(id).setStyle('display', '');
}

// Alle Elemente checken
function checkAll(elem, name) {
	if (elem.checked == true) {
		var value = true;
	} else
		var value = false;
	var sObj = document.getElementsByName(name);
	for ( var i = 0; i < sObj.length; i++) {
		sObj[i].checked = value;
	}
}

function addfriend(id) {
	new Request( {
		url :'/ajax/friendlist.php',
		method :'get',
		onSuccess : function(text, html) {
			alert(text);
		}
	}).send('add=' + id);
}

function ignore(id) {
	if (confirm("Dieses Mitglied wirklich ignorieren?")) {
		new Request( {
			url :'/ajax/friendlist.php',
			method :'get',
			onSuccess : function(text, html) {
				alert(text);
			}
		}).send('ignore=' + id);
	}
}

function initUpdate(time) {
	window.setTimeout("updateMSG()", firstupdate * 1000);
	updatenl = window.setInterval("updateMSG()", update_delay);
//	window.setTimeout("updateMSG()", time * 1000);
}

function updateMSG() {
	new Request( {
		url :'/ajax/checkmails_v3.php',
		method :'get',
		onSuccess : function(text, nodes) {
			var nl = nodes.getElementsByTagName('m');
			msgcount = nl.length;

			for ( var i = 0; i < nl.length; i++) {
				var nli = nl.item(i);
				var nick = nli.getAttribute('nick').toString();
				var id = nli.getAttribute('id').toString();
				var big1 = nli.getAttribute('big').toString();
				var hm = nli.getAttribute('hm');
				showMessage(id, nick, big1, false, hm);
			}

		}
	}).send();
}

/* open a centered popup */
function PopUp(w, h, ziel, scroll) {
	h = h - 20;
	var x = 0, y = 0, parameter = "";
	if (w < screen.availWidth || h < screen.availHeight) {
		x = (screen.availWidth - w - 12) / 2;
		y = (screen.availHeight - h - 104) / 2;
		if (window.opera)
			y = 0; // Opera positioniert unter den Symbolleisten
		if (x < 0 || y < 0) {
			x = 0;
			y = 0;
		} else
			parameter = "width=" + w + ",height=" + h + ",";
	}
	if (scroll == true)
		parameter += "scrollbars=yes,";
	else
		parameter += "scrollbars=no,";
	parameter += "left=" + x + ",top=" + y
			+ ",menubar=no,location=no,toolbar=no,status=no,resizable=no";
	var Fenster = window.open(ziel, "PopUp", parameter);
	if (Fenster)
		Fenster.focus();
	return !Fenster;
}

function showMessage(id, nick, big1, noblock, hm) {
	var width = 450;
	var height = 390;
	var bigll = '';

	if (big1 == 1) {
		width = 625;
		height = 460;
		bigll = '&big=1';
	}

	try {
		if ((!pblock || noblock) && hm != 1) {
			var w = window.open("/community/msg/?id=" + id + "&nick=" + nick
					+ bigll, "Shortmessage" + id, "scrollbars=1,status,width="
					+ width + ",height=" + height);
		}

		if (!w || (pblock && !noblock) || hm == 1) {
			if ($('infobalken')) {
				pblock = true;
				if ($('infobalken').innerHTML.length < 2) {
					var inf = '';
					if (hm != 1)
						inf = "<a href='/community/popupcheck/'>Die Nachrichten sollten sich automatisch öffnen, wenn nicht klicke bitte hier.</a><br /><br />";
					$('infobalken').innerHTML = "<span id='infolength'>"
							+ inf
							+ "<img src='/res/wpgfx/message.gif'> <strong>Du hast neue Nachrichten von:</strong><br /></span>";
				}
				if (!$('msg' + id))
					$('infobalken').innerHTML += '<span id="msg' + id
							+ '"><a href="javascript:msg(\'' + id + '\',\''
							+ nick + '\',\'' + big1 + '\');">' + nick
							+ '</a>, </span>';

				if ($('infobalken').getStyle('display') == 'none') {
					$('infobalken').setStyle('opacity', '0');

					$('infobalken').get('tween', {
						property :'opacity',
						duration :500,
						transition :Fx.Transitions.Sine.easeInOut,
						onComplete : function() {
							if ($('TB_load' + this.id)) {
								$('TB_load' + this.id).dispose();
							}
						}.bind(this)
					}).start(1);
					$('infobalken').setStyle('display', 'block');
				}
			}

		} else {
			w.focus();
		}
	} catch (e) {
		window.open("/community/msg/?id=" + id + "&nick=" + nick + bigll,
				"Shortmessage" + id, "scrollbars=1,status,width=" + width
						+ ",height=" + height);
	}

}
function msg(id, nick, big1) {
	showMessage(id, nick, big1, true, 0)
	$('msg' + id).get(
			'tween',
			{
				property :'opacity',
				duration :250,
				transition :Fx.Transitions.Sine.easeInOut,
				onComplete : function() {
					$('msg' + id).dispose();
					if ($('infobalken').innerHTML.length
							- $('infolength').innerHTML.length < 30)
						$('infobalken').setStyle('display', 'none');
				}
			}).start(0);

}

function emoticon(text) {
	var txtarea = document.post.body;
	text = ' ' + text + ' ';
	if (txtarea.createTextRange && txtarea.caretPos) {
		var caretPos = txtarea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text
				+ text + ' '
				: caretPos.text + text;
		txtarea.focus();
	} else {
		txtarea.value += text;
		txtarea.focus();
	}
}

if (typeof main != 'undefined') {

	var BDAYcheck = function() {
		new Request( {
			url :'/ajax/bday.php',
			method :'get',
			onSuccess :bdayinfo
		}).send();
	}
	function bdayinfo(text, nodes) {
		if (text.length > 10) {
			TB_show("Geburtstagserinnerung",
					'/ajax/bday.php?width=600&height=185', false);
			SP_init();
		}
		Cookie.write('bdayinfo', 1, {
			duration :1,
			path :"/"
		});
	}

	function PBcheck() {
		Cookie.write('pblock', 1, {
			duration :1,
			path :"/"
		});

		var myTest = window
				.open(
						"about:blank",
						"",
						"directories=no,height=10,width=10,menubar=no,resizable=no,scrollbars=no,status=no,titlebar=no,top=0,location=no");
		if (!myTest) {

			new Element('div').setProperty('id', 'popupblock').injectInside(
					document.body);
			$('popupblock').setStyle('display', 'none');
			$('popupblock').innerHTML = "<h1>Leider mussten wir feststellen, dass dein Browser Popups blockt.</h1>Du kannst nur Nachrichten von anderen Mitgliedern empfangen, wenn dein Browser keine Popups mehr blockt.<br /><br /><a href=\"/community/popupcheck/\">Hier findest Du eine Anleitung wie du Popups f�r diese Seite aktivieren kannst.</a>";

			TB_show("Popupblocker aktiviert",
					'#TB_inline?height=170&width=300&inlineId=popupblock',
					false);
		} else
			myTest.close();

	}

}

if (typeof main != 'undefined') {
	// window.addEvent('domready', function() {
	// mailtimer=updateEmail.periodical(60000); });
	// window.addEvent('domready', TT_build);
	if (islogin > 0)
		window.addEvent('domready', initUpdate.pass(update_delay));
	if (Cookie.read('pblock') != 1 && islogin > 0)
		window.addEvent('load', PBcheck);
	if (Cookie.read('bdayinfo') != 1 && islogin > 0)
		window.addEvent('load', BDAYcheck);
}

/* Tooltip inizialisation */
function TT_build() {
	// if (Cookie.read('ttdisabled')!=1)
	// var Tips1 = new Tips($$('.showtip'));
}

/* MESSAGE.JS */
function QMSend(id) {
	var txt = $('qmsg').value;
	if (txt.length > 1 && $('qmsg').value != 'QuickMessage') {
		new Request( {
			url :'/ajax/msg.php',
			method :'get'
		}).send('message=' + encodeURIComponent(txt) + '&id=' + id);
		$('msgdiv').innerHTML = '<b>Message gesendet!</b>';
	}
}

function sendit(e) {
	if (stayopen != 1) {
		return true;
	} else {
		new Request( {
			url :'/ajax/msg.php',
			method :'get',
			onComplete :handleResponseMessage
		}).send('message=' + encodeURIComponent($('body').value) + '&id='
				+ $('id').value);
		$('body').value = '';
		if (e && e.preventDefault)
			e.preventDefault(); // DOM style
		return false; // IE style
	}
}

function getHistory(id) {
	new Request.HTML(
			{
				url :'/ajax/v3_msghistory.php?id=' + $('id').value,
				update :$('history'),
				onComplete : function() {
					$('info2').innerHTML = "<b>Es ist eine neue Nachricht vorhanden!</b>";
					timerID = setTimeout("clearInfo('info2','')", 5000);
					window.focus();
				}
			}).get();
}

function msgstayOpen() {
	new Request( {
		url :'/ajax/v3_msg.php',
		method :'get'
	}).send('msgstayopen=1&id=' + $('id').value);
	stayopen = 1;
	$('stayopen').innerHTML = 'Fenster bleibt geöffnet';
}

function handleResponseMessage(text, nodes) {
	var cont = nodes.getElementsByTagName("p")[0];
	var content = cont.firstChild.data;

	$('info').innerHTML = 'Nachricht gesendet...';

	if (cont.getAttribute('close') != 1) {
		var re = '<input onClick=\"sendit();\" value=\"Senden\" class=\"button\" style="margin: 0px; width: 200px;\" tabindex=\"2\" type=\"button\" />';
		timerID = setTimeout("clearInfo('info','" + re + "')", 1000);
		$('body').focus();

		var nhist = '<table width="99%" border="0" cellspacing="0" cellpadding="0" align="center"><tr><td bgcolor="#EFEFEF"><b>Deine Nachricht:</b> </td></tr><tr><td bgcolor="#FFFFFF"><b>' + content + '</b></td></tr></table>';

		$('history').innerHTML = nhist + $('history').innerHTML;
	}

}

function clearInfo(info, what) {
	$(info).innerHTML = what;
	$('body').focus();
}

/* Profil_v3.js */

window.addEvent('domready', SP_init);

var SP_userid = 0;
var myTimer = null;
var SP_lastevent;

function SP_init() {
	$$("a.nick").each( function(el) {
		if (SmallProfilTime > 0)
			el.onmouseover = SP_bind;
		el.onclick = SP_click;
	});

	$$("a.user").each( function(el) {
		if (SmallProfilTime > 0)
			el.onmouseover = SP_bind;
		if (profilePopup >0) {
			el.onclick = SP_click;
			el.href = "#";
		}
	});

}

function SP_bind(event) {
	var event = new Event(event);
	event.preventDefault();
	this.blur();
	if (this.href.lastIndexOf('/user/') >0) {
		SP_userid = parseInt(this.href.substr(this.href.lastIndexOf('/user/')+6));
	}
	else {

		if (this.id.substr(0, 1) == 'u')
			SP_userid = parseInt(this.id.substr(1));
		else
			SP_userid = parseInt(this.id);
	}
	SP_lastevent = event;
	// clear old timer
	if (myTimer != null)
		myTimer = $clear(myTimer);
	myTimer = showQP.delay(SmallProfilTime * 1000, this, event);

	this.onmouseout = function() {
		myTimer = $clear(myTimer); // Cancels quickpage
	}

	this.onmousemove = function(event) {
		var event = new Event(event);
		event.preventDefault();
		this.blur();
		SP_lastevent = event;
	}

	this.onmouseover = SP_bind;
	if (profilePopup >0) {
		this.onclick = SP_click;
	}
	return false;
}

function SP_click(event) {
	var event = new Event(event);
	event.preventDefault();
	this.blur();
	if (this.href.lastIndexOf('/user/',0) >0)
		npage(parseInt(this.href.substr(this.href.lastIndexOf('/user/')+6)));
	else {
	
		if (this.id.substr(0, 1) == 'u')
			npage(parseInt(this.id.substr(1)));
		else
			npage(parseInt(this.id));
	}
	this.onmouseover = SP_bind;
	this.onclick = SP_click;
	return false;
}

function showQP(event) {
	var event = SP_lastevent;
	var height = 280;
	var width = 505;
	SP_close();

	var screenHeight = window.innerHeight ? window.innerHeight : screen.height;
	var screenWidth = window.innerWidth ? window.innerWidth
			: document.body.clientWidth;
	var posX = event.client.x > screenWidth / 2 ? event.page.x - width + 10
			: event.page.x - 10;
	var posY = event.client.y > screenHeight / 2 ? event.page.y - height + 10
			: event.page.y - 10;

	var layer = new Element('div', {
		'styles' : {
			'visibility' :'visible',
			'width' :width + 'px',
			'height' :height + 'px',
			'z-index' :'50',
			'position' :'absolute',
			'top' :posY + 'px',
			'left' :posX + 'px'
		}
	})
	layer.setAttribute('id', 'SmallProfil');
	layer.injectInside(document.body);

	if (!profilePopup) {
		var profilePopup = 0;
	}

	var jsLoader = new Element('script');
	jsLoader.setAttribute('id', 'jsLoader');
	jsLoader.src = '/ajax/v3_smallprofil.php?id=' + SP_userid;
	jsLoader.injectInside(document.body);
}

function SP_close() {
	if ($('bglayer'))
		$('bglayer').dispose();
	if ($('SmallProfil'))
		$('SmallProfil').dispose();
	if ($("jsLoader"))
		$("jsLoader").dispose();
	this.onmousemove = null;
}

Distance = new function() {
	return {
		trim : function(sString) {
			while (sString.substring(0, 1) == ' ') {
				sString = sString.substring(1, sString.length);
			}
			while (sString.substring(sString.length - 1, sString.length) == ' ') {
				sString = sString.substring(0, sString.length - 1);
			}
			return sString;
		},
		getCords : function() {
			var cook = Cookie.read("dist");
			cook = cook.split(":");
			return cook;
		},
		compute : function(a, b, c, d) {
			function r(a) {
				return a * m.PI / 180;
			}
			;
			var m = Math;
			var e = m
					.round((m.acos((m.sin(r(b)) * m.sin(r(d)))
							+ (m.cos(r(b)) * m.cos(r(d)) * m.cos(r(a) - r(c)))) * 6371) * 10) / 10;
			if (!e.toString().substring(m.floor(e).toString().length)) {
				e = e.toString() + ',0';
			} else {
				e = e.toString().replace(/\./, ',');
			}
			return e;
		},
		get : function(longitude, latitude) {
			var home = Distance.getCords();

			if (longitude == 0 || home == false) {
				return 'nicht verfügbar';
			} else {
				return Distance.compute(longitude, latitude, home[0], home[1]) + ' km';
			}
		}
	}
}

function npage(bid) {
	if (nickClick == 0)
		npageshow(bid, 0, '');
	else
		SmallProfil.showdirect(bid);
}

function npageshow(bid, id, zusatz) {

	var h = 600;
	if ((h + 150) < screen.availHeight)
		h = screen.availHeight - 150;

	if (profilePopup == 1)
		var popup = window
				.open(
						"/profil/?id=" + bid + '&np=' + id + '&' + zusatz,
						'np' + bid,
						"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=yes,resizable=no,width=758,height="
								+ h + ",top=10,left=10");
	else
		window.location = '/profil/?id=' + bid + '&np=' + id + '&' + zusatz;

}

function opengroup(bid) {
	if (profilePopup == 1)
		parent.opener.location = '/community/groups/detail/?id=' + bid;
	else
		window.location = '/community/groups/detail/?id=' + bid;
}

function openevent(bid) {
	if (profilePopup == 1)
		parent.opener.location = '/community/calendar/detail/?id=' + bid;
	else
		window.location = '/community/calendar/detail/?id=' + bid;
}