document.write('<script type="text/javascript" src="/js/templates.js"></script>');
document.write('<script type="text/javascript" src="/js/nightloop.js"></script>');
document.write('<script type="text/javascript" src="/js/messenger.js"></script>');
document.write('<script type="text/javascript" src="/js/groups.js"></script>');
document.write('<script type="text/javascript" src="/js/charts.js"></script>');
// document.write('<script type="text/javascript"
// src="/js/tooltip.js"></script>');

glow.ready(function() {
	glow.dom.get('#noJs').hide();

	generic.init();

	generic.userShortInfo();
	
	comment.get();

	navigation.init();
	

	
});
/** global variables */
var panel = [];

/** glow-extension */
/* var $ = glow.dom.get; */
var bind = glow.events.addListener;
/*
 * var voting = {
 * 
 * check : function(rObj) { for (var i=0; i<rObj.length; i++) if
 * (rObj[i].checked) return rObj[i].value; return false; },
 * 
 * switchResult : function() { state =
 * glow.dom.get('#resultDiv').css('display');
 * 
 * if(state == 'none') glow.dom.get('#resultDiv').show(); else
 * glow.dom.get('#resultDiv').hide(); return false; },
 * 
 * doit : function() { if(!generic.uid) { generic.callback = 'voting.doit';
 * login(); return false; }
 * 
 * questionID = document.voteForm.questionID.value; vItem =
 * this.check(document.voteForm.voteItem);
 * 
 * if(vItem == false) return false;
 * 
 * glow.net.post("/ajax/vote/registervote/", { qid: questionID, answer: vItem
 *  }, { async : false, onLoad: function(response) { r = response.json();
 * if(r.success == true) { glow.dom.get('#voteDiv').html(r.message);
 * glow.dom.get('#resultDiv').show(); } else
 * glow.dom.get('#voteDiv').html(glow.dom.get('#voteDiv').html() + r.message); }
 * }); } };
 */

/**
 * loads and handles commentlists to given object object.item, object.type
 * required
 * 
 * @param params
 * @return
 */
var comment = {
	options : false,
	jumpComment : null,

	set : function(object) {
		this.options = generic.extendObject( {
			amount : null,
			item : null,
			type : null,
			point : null,
			start : null,
			targetId : null,
			spamAlert : 0,
			timeout : 60
		}, object || {});

		if(!this.observing) {
			this.observing = true;
			glow.dom.get('#commentForm').each(function() {
				formobserve(this, 'comment.save');
			});
		}
	},

	_net : function(src, target) {
	/*	if (this.options.targetId === null)
			return false;
*/
		glow.net.post('/ajax/comments/' + src + '/', this.options, {
			async : false,
			onLoad : function(response) {
				glow.dom.get(target).html(response.text());
			}
		});
	},

	get : function() {
		if (document.getElementById('action' + this.options.targetId)) {
			target = '#action' + this.options.targetId + ' .commentList';
			document.getElementById('commentBox' + this.options.targetId).className = "comments";
		}
		else
			target = '#comments';
		this._net('list', target);
	},

	save : function() {
		this.options.start = 0;

		if (!generic.uid) {
			generic.callback = 'comment.save';
			login();
			return false;
		}
		
		if (this.options.spamAlert > generic.time()) {
			wait = (this.options.spamAlert - generic.time()) / 1000;
			glow.dom.get('#commentForm .info').show();
			glow.dom
					.get('#commentForm .info')
					.html(
							'Du muss noch ' + wait + ' Sekunden warten, bis Du hier Deinen nächsten Kommentar schreiben kannst.');
		} else {
			this.options.uid = generic.uid;
			glow.net.post('/ajax/comments/save/', generic.extendObject(
					this.options, glow.dom.get("#commentForm").val()), {
				async : false,
				onLoad : function(response) {
					r = response.json();

					if (r.success) {
						document.forms['commentForm'].reset();
						comment.options.amount++;
						comment.options.spamAlert = generic.time() + comment.options.timeout * 1000;

						if (top.frames['imageUpload']) {
							top.frames['imageUpload'].document.getElementById('itemId').value = r.success;
							top.frames['imageUpload'].document.getElementById('itemType').value = 'comment';
							top.frames['imageUpload'].document.getElementById('imageUpload').submit();
							glow.dom.get('#animation').toggleClass('invisible');
						}
						else {
							comment.get();
							generic.userShortInfo();
							comment.hideJumpComment();
						}
						window.parent.generic.animateEarnedPoints('#commentForm .point', r.points, r.message);
						glow.dom.get("#commentForm .icon").remove();
					} else {
						glow.dom.get('#commentForm .info').show();
						generic.message('#commentForm .info', r.message);
					}
				}
			});
		}
		return false;
	},
	
	deleteFromBoard : function(dom, id) {
		if (confirm('Wirklich löschen?')) {
			glow.dom.get(dom).hide();		
			generic.animateEarnedPoints(glow.dom.get(dom.parentNode).get('.point'), false, 'Eintrag gel&ouml;scht ...');
			window.setTimeout(function() { glow.dom.get(dom.parentNode.parentNode.parentNode).addClass('opa5'); }, 2000);
			
			glow.net.post('/ajax/comments/delete/', { 'id' : id, 'type' : 'board' });
		}
	},
	
	deleteOwn : function(dom, id) {
		if (confirm('Wirklich löschen?')) {
			glow.net.post('/ajax/comments/delete/', { 'id' : id }, {
			async : false,
			onLoad : function(response) {
				r = response.json();
				if (r.success) {
					glow.dom.get(dom).hide();
					generic.animateEarnedPoints(glow.dom.get(dom.parentNode.parentNode).get('.point'), r.points, 'Kommentar gel&ouml;scht ...');
					window.setTimeout(function() { glow.dom.get(dom.parentNode.parentNode.parentNode).addClass('opa5'); }, 2000);
				}
			}});
		}
	},
	
	goHere : function(id, itemId, itemType, pointId, target) {
		if (this.jumpComment === null) {
			this.jumpComment = glow.dom.get('#Kommentar-schreiben');
		}
		this.set({ 
			amount : 0,
			start : 0,
			item : itemId,
			type : itemType,
			point : pointId,
			targetId : target
		});
		
		glow.dom.get('#Kommentar-schreiben .info').hide();
		this.jumpComment.appendTo(id);
	},
	
	hideJumpComment : function() {
		document.getElementById('commentText').value = '';
		if (this.jumpComment !== null)
			this.jumpComment.appendTo('#hideJumpComment');
	},
	
	showHidden : function(self) {
		glow.dom.get(self).hide();
		glow.dom.get(self.parentNode).get('.comment').each(function() {
			glow.dom.get(this).removeClass('invisible');
		});
	}
};

var rating = {
	options : null,
	rateText : [ 'mieserabel', 'nicht so toll', 'erträglich', 'gut',
			'fucking amazing' ],

	set : function(object) {
		this.options = generic.extendObject( {
			item : null,
			type : null,
			value : null,
			rates : null,
			myValue : null,
			rated : false
		}, object || {});

		if (this.options.rated == false)
			this.init();
	},

	init : function() {
		this.myRating = glow.dom.get('#rating .stars');
		this.originalBgPos = this.myRating.css('background-position');
		glow.dom.get('#rating .deeplink').html('');

		glow.dom.get('#rating .stars a').each(
				function() {
					var r = this.href.substr(-1);
					this.title = rating.rateText[(r - 1)];
					bind(this, 'mouseover', function() {
						rating.myRating.css('background-position',
								'-100px -' + (40 + r * 20) + 'px');
						//glow.dom.get('#rating .point').html(rating.rateText[(r - 1)]);
					});
					bind(this, 'mouseout', function() {
						rating.myRating.css('background-position',
								rating.originalBgPos);
						glow.dom.get('#rating .deeplink').html('');
					});
					bind(this, 'click', function() {
						rating.rate(r);
						return false;
					});
				});
	},

	rate : function(r) {
		this.options.myValue = r || this.options.myValue;

		if (!generic.uid) {
			generic.callback = 'rating.rate';
			login();
			return false;
		}

		this.options.uid = generic.uid;
		glow.net.post('/ajax/rating/save/', this.options, {
			async : false,
			onLoad : function(response) {
				r = response.json();

				if (r.success) {
					rating.options.rated = true;
					rating.myRating.css('backgroundPosition',
							rating.originalBgPos);
					generic.userShortInfo();
					generic.animateEarnedPoints('#rating .deeplink', r.points,
							r.message);

					x = parseInt(rating.options.myValue)
							+ parseInt(rating.options.value);
					y = rating.options.rates + 1;

					rating.myRating.css('background-position',
							'0 -' + (40 + (Math.ceil(x / y) * 20)) + 'px');
					glow.dom.get('#rating .current').html(
							'(' + Math.round(x * 10 / y) / 10 + '/5)');
				} else {
					generic.message('#rating .deeplink', r.message);
					rating.myRating.css('background-position',
							rating.originalBgPos);
				}
				glow.dom.get('#rating .stars a').each(function() {
					glow.events.removeAllListeners(this);
				});
			}
		});
	}
};

var form = {
	invalid : function(e) {
		c = e.value.length > 0 ? 'valid' : 'invalid';

		if (e.parentNode.getElementsByTagName('span').length == 1)
			e.parentNode.getElementsByTagName('span')[0].className = 'icon fr ' + c;
		else {
			s = document.createElement("span");
			s.setAttribute(
					(navigator.appName.indexOf("Explorer") != -1 ? 'className'
							: 'class'), 'icon fr ' + c);
			e.parentNode.insertBefore(s, e.parentNode.firstChild);
		}
		alert(glow.dom.get(e));
	},

	valid : function(elm) {
		alert(glow.dom.get(elm));
	}
};

/**
 * observe forms for valid values
 * 
 * @param form
 * @return
 */
function formobserve(form, callback) {
	glow.dom.get('.button').each(function() {
		bind(this, 'mouseover', function() {
			glow.dom.get(this).addClass('hover');
		});
		bind(this, 'mouseout', function() {
			glow.dom.get(this).removeClass('hover');
		});
	});

	inputs = glow.dom.get('#' + glow.dom.get(form).attr('id') + ' .req');

	for (i = 0; i < inputs.length; i++) {
		inputs[i].onblur = inputs[i].onkeyup = function() {
			checkform(this);
		};
		if (inputs[i].value.length > 0)
			checkform(inputs[i]);
	}
	
	if (document.getElementById('commentText'))
		new elasticTextarea('#commentText');
	if (document.getElementById('bmText'))
		new elasticTextarea('#bmText');
	
	bind(form, 'submit', function() {
		return checkform(this, true, callback);
	});
}

function elasticTextarea(element) {
	var mimics = [
		'padding-top',
		'padding-right',
		'padding-bottom',
		'padding-left',
		'font-size',
		'line-height',
		'font-family',
		'width',
		'font-weight'];

	var textarea	=	glow.dom.get(element),
		twin		=	glow.dom.create('<div></div>'),
		lineHeight	=	parseInt(textarea.css('line-height'), '10') || parseInt(textarea.css('font-size'), '10'),
		minheight	=	parseInt(textarea.css('height'), '10') || lineHeight*3,
		maxheight	=	parseInt(textarea.css('max-height'), '10') || Number.MAX_VALUE,
		goalheight	=	0,
		i 			=	0;

	twin.css( {
		'display': 'none',
		'position': 'absolute',
		'word-wrap': 'break-word'
	});

	if (maxheight < 0) { maxheight = Number.MAX_VALUE; }

	textarea.after(twin);
	
	var i = mimics.length;
	while(i--){
		twin.css(mimics[i].toString(),textarea.css(mimics[i].toString()));
	}
	
	function setHeightAndOverflow(height, overflow){				
		curratedHeight = Math.floor(parseInt(height,10));
		if(textarea.css('height') != curratedHeight){
			textarea.css('height', curratedHeight + 'px');
			textarea.css('overflow','overflow');
		}
	}
	
	function updateElasticArea() {
		var textareaContent = textarea.val().replace(/&/g,'&amp;').replace(/  /g, '&nbsp;').replace(/<|>/g, '&gt;').replace(/\n/g, '<br />');

		var twinContent = twin.html();
		
		if(textareaContent+'&nbsp;' != twinContent){
			twin.html(textareaContent+'&nbsp;');
			twinHeight = parseInt(twin.css('height'))||0;
			if(Math.abs(twinHeight + lineHeight - parseInt(textarea.css('height'))) > 3){
				var goalheight = twinHeight + lineHeight;
				if(goalheight >= maxheight) {
					setHeightAndOverflow(maxheight,'auto');
				} else if(goalheight <= minheight) {
					setHeightAndOverflow(minheight,'hidden');
				} else {
					setHeightAndOverflow(goalheight,'hidden');
				}
			}						
		}				
	};
	
	textarea.css('overflow','hidden');
	bind(textarea, 'keyup', function(){updateElasticArea();});
	updateElasticArea();
}

function checkform(e, submit, callback) {

	if (submit == true) {
		inputs = glow.dom.get('#' + glow.dom.get(e).attr('id') + ' .req');
		for (i = 0; i < inputs.length; i++) {
			checkform(inputs[i]);
		}

		if (glow.dom.get('#' + glow.dom.get(e).attr('id') + ' .invalid').length > 0) {
			glow.dom.get('#' + glow.dom.get(e).attr('id') + ' .info').show();
			generic.message('#' + glow.dom.get(e).attr('id') + ' .info',
							'Es sind nicht alle erforderlichen Felder ausgef&uuml;llt oder sie enthalten Fehler');
			return false;
		} else {
			glow.dom.get('#' + glow.dom.get(e).attr('id') + ' .info div').html('');

			return generic.doCallback(callback);
		}
	}
	
	this.itemId = null;
	this.itemType = null;
	this.response = null;
	this.optValue = false;
	this.maxLen = null;
	this.minLen = null;
	this.fieldName = null;
	this.noSpace = null;
	this.compareField = null; 
	this.alphanum = null;
	
	this.classes = e.className.split(' ');
	for (cl in this.classes) {
		if (this.classes[cl].substr(0, 3) == 'max')
			this.maxLen = this.classes[cl].split('-')[1];
		if (this.classes[cl].substr(0, 3) == 'min')
			this.minLen = this.classes[cl].split('-')[1];
		if (this.classes[cl].substr(0, 5) == 'field')
			this.fieldName = this.classes[cl].split('-')[1];
		if (this.classes[cl].substr(0, 7) == 'nospace')
			this.noSpace = true;
		if (this.classes[cl].substr(0, 3) == 'opt')
			this.optValue = true;
		if (this.classes[cl].substr(0, 7) == 'compare')
			this.compareField = this.classes[cl].split('-')[1];
		if (this.classes[cl].substr(0, 8) == 'alphanum')
			this.alphanum = true;
		
	}
	
	if(this.optValue == false || (this.optValue == true && e.value.length > 0) || (this.optValue == true && this.compareField  && glow.dom.get('#' + this.compareField).val().length > 0)) {
		
		e2 = e.value.replace(/^\s+/g, '').replace(/\s+$/g, '');
		c = e2.length > 0 ? 'valid' : 'invalid';
	
		var regmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,10})$/;
		if(glow.dom.get(e).hasClass('email'))
			if(regmail.test(e.value) == false) 
				c = 'invalid';
		
		var regspace = /\s+/;
		if(this.noSpace) {
			if(regspace.test(e.value) == true)
				c = 'invalid';
		}
		
		var regalphanum = /^([a-zA-Z0-9_\-.]+)$/;
		if(this.alphanum) {
			if(regalphanum.test(e.value) == false)
				c = 'invalid';
		}
		
		if (this.minLen) {
			if(e.value.length < this.minLen)
				c = 'invalid';
		}
		
		if (this.maxLen) {
			if(e.value.length > this.maxLen)
				c = 'invalid';
		}
		
		if(this.compareField) {
			
			if(e.value == glow.dom.get('#' + this.compareField).val())
				c = 'valid';
			else
				c = 'invalid';
		}
	
	
		if (e.parentNode.getElementsByTagName('span').length == 1)
			e.parentNode.getElementsByTagName('span')[0].className = 'icon fr ' + c;
		else {
			s = document.createElement("span");
			s.setAttribute((navigator.appName.indexOf("Explorer") != -1 ? 'className' : 'class'), 'icon fr ' + c);
			e.parentNode.insertBefore(s, e.parentNode.firstChild);
		}
	}
	else
		e.parentNode.getElementsByTagName('span')[0].className = '';
}

function observeLoginForm() {
	if (this.obs !== true) {
		formobserve(glow.dom.get('#loginForm'), 'performLogin');
		this.obs = true;
	}
	bind('#login_passA', 'focus', function() {
		glow.dom.get(this).hide();
		glow.dom.get('#login_passB').css('display', 'inline');
		document.getElementById('login_passB').focus();
	});
		
}

var reset = false;
function updateStatusTweet(reset) {

	if(reset == false)
		var tweet = glow.dom.get('#statusTweet').val();
	else
		var tweet = false;

	if(tweet.length > 140)
		tPanel('F&uuml;r die Eingabe \"Was machst du gerade\" sind max. 140 Zeichen erlaubt!', 500);
	else if(tweet.length > 0)
	{
		glow.net.post("/ajax/user/updateStatusTweet/", 
				{ text: tweet }, 
					{
		        	onLoad: function(response)
		        	{
						r = response.json();
						if(r.success)
						{
							generic.userShortInfo();
						}
					}
				});		
	}

	if(reset == true)
	{
		glow.net.post("/ajax/user/updateStatusTweet/", 
				{ }, 
					{
		        	onLoad: function(response)
		        	{
						r = response.json();
						if(r.success)
						{
							generic.userShortInfo();
						}
					}
				});		
	}
	
	
}

function switchStatusTweet() {
		glow.dom.get('#actualStatusTweet').toggleClass('invisible'); 
		glow.dom.get('#statusForm').toggleClass('invisible');
}

function invite() {
	
	mail = glow.dom.get('#email_friend').val();
	
	if (this.callback !== true) {
		this.mail = mail;
	}
	
	if (this.callback === true) {
		mail = this.mail;
	}
	
	if (!generic.uid) {
		this.callback = true;
		generic.callback = 'invite';
		login();
		return false;
	}
		
	/* glow.dom.get('#submitButton').hide(); */
	
	glow.net.post("/ajax/user/invite/", 
		{ email: mail }, 
		{
		async : false,
		onLoad : function(response) {
			r = response.json();
			if(r.success == true)
			{
				glow.dom.get('#inviteFriends .info').show();
				generic.message('#inviteFriends .info', r.message);
				glow.dom.get('#email_friend').val('');
			}
			
		}
	});	
	glow.dom.get('#submitButton').show();
	/* return false; */
}


function pointer(type, id, desc) {
	
	if (this.callback !== true) {
		this.id = id;
		this.type = type;
		this.desc = desc;
	}
	
	if (this.callback === true) {
		id = this.id;
		type = this.type;
		desc = this.desc;
	}
	
	if (!generic.uid) {
		this.callback = true;
		generic.callback = 'pointer';
		login();
		return false;
	}
	
	panel['pointer'] = new glow.widgets.Panel("#panel", {
		template : pointerPanel,
		width : '520px',
		modal : true,
		closeOnEsc : true,
		hideWindowedFlash : true,
		anim : 'fade'
	});

	panel['pointer'].show();

	glow.events.addListener(panel['pointer'], "afterHide",
			function(event) {
				glow.dom.get('.pointerPanel').html('');
			});

	intro = 'Schau dir das mal an: <br />';
	glow.dom.get('.pointerPanel #itemInfo').html(intro + desc);
	glow.dom.get('#pointerForm #itemId').val(id);
	glow.dom.get('#pointerForm #itemType').val(type);
	document.getElementById("form_receiver").focus();
	formobserve(glow.dom.get('#pointerForm'), 'setPointer');
}

function setPointer()
{
	id = glow.dom.get('#pointerForm #itemId').val();
	type = glow.dom.get('#pointerForm #itemType').val();
	user = glow.dom.get('#pointerForm #form_receiver').val();

	glow.net.post("/ajax/itempointer/set/", {
		itemId: id,
		itemType: type,
		receiver: user
		}, {
		async : false,
		onLoad : function(response) {
			r = response.json();
			glow.dom.get('#pointerForm #itemId').val('');
			glow.dom.get('#pointerForm #itemType').val('');
			glow.dom.get('#pointerForm #form_receiver').val('');
			panel['pointer'].hide();
			generic.userShortInfo();
		}
	});	
	return false;
}

function removePointer(pointerid)
{
	glow.net.post("/ajax/itempointer/remove/", {
		id: pointerid
		}, {
		async : false,
		onLoad : function(response) {
			r = response.json();
			if(r.success == true)
			{
				glow.dom.get('#pointer_' + pointerid).hide();
				generic.userShortInfo();
			}
			else
				tPanel('Es ist ein Fehler aufgetreten!', 500);
		}
	});	
}

function quickMessage(id, userName, subject) {
	
	if (this.callback !== true) {
		this.id = id;
		this.userName = userName;
		this.subject = subject;
	}
	
	if (this.callback === true) {
		id = this.id;
		userName = this.userName;
		subject = this.subject;
	}
	
	if (!generic.uid) {
		this.callback = true;
		generic.callback = 'quickMessage';
		login();
		return false;
	}
	
	// if(typeof(panel['quickMessage']) == 'undefined' )
	panel['quickMessage'] = new glow.widgets.Panel("#panel", {
		template : quickMessagePanel,
		width : '520px',
		modal : true,
		closeOnEsc : true,
		hideWindowedFlash : true,
		anim : 'fade'
	});

	panel['quickMessage'].show();

	glow.events.addListener(panel['quickMessage'], "afterHide",
			function(event) {
				glow.dom.get('.quickMessagePanel').html('');
			});

	glow.dom.get('.quickMessagePanel #receiverName').html(userName);
	glow.dom.get('.quickMessagePanel #form_receiver').val(userName);
	glow.dom.get('.quickMessagePanel #form_subject').val(subject);
	formobserve(glow.dom.get('#quickMessageForm'), 'sendMessage');

	if (userName.length < 3)
		document.getElementById("form_receiver").focus();
	else if (subject.length > 4)
		document.getElementById("form_content").focus();
	else
		document.getElementById("form_subject").focus();
}

function tPanel(text, wValue) {
	if (typeof(wValue) == 'undefined')
		wValue = 520;

	panel['textPanel'] = new glow.widgets.Panel("#panel", {
		template : textPanel,
		width : wValue + 'px',
		modal : true,
		closeOnEsc : true,
		hideWindowedFlash : true,
		anim : 'fade'
	});

	panel['textPanel'].show();
	glow.dom.get('.confirmPanel .panel-bd').html(text);

	glow.events.addListener(panel['textPanel'], "afterHide",
			function(event) {
				glow.dom.get('.confirmPanel').html('');
			});
}

function sendMessage() {
	glow.net.post("/ajax/messenger/send/", glow.dom.get("#quickMessageForm")
			.val(), {
		async : false,
		onLoad : function(response) {
			r = response.json();
			if (r.success) {
				glow.dom.get('.quickMessagePanel #form_receiver').val('');
				glow.dom.get('.quickMessagePanel #form_subject').val('');
				glow.dom.get('.quickMessagePanel #form_content').val('');
				glow.dom.get('.quickMessagePanel #receiverName').html('');
				panel['quickMessage'].hide();
				generic.userShortInfo();

			} else {
				glow.dom.get('#quickMessageForm .info').show();
				generic.message('#quickMessageForm .info', r.message);
			}
		}
	});
	return false;

}

function quickRegister() {
	if (typeof (panel['quickRegister']) == 'undefined')
		panel['quickRegister'] = new glow.widgets.Panel("#panel", {
			template : quickRegisterPanel,
			width : '450px',
			modal : true,
			closeOnEsc : true,
			hideWindowedFlash : true,
			anim : 'fade'
		});

	if (typeof (panel['login']) != 'undefined')
		panel['login'].hide();

	panel['quickRegister'].show();
	
	glow.dom.get('#quickRegisterForm .tt').each(function() {			
		new tooltip(this);
	});

	whatever = function(t) {
		if (this.value.length < 4)
			return false;

		if (t > 0)
			timeout();

		glow.net.post("/ajax/user/checkusername/", glow.dom.get(
				"#quickRegisterForm").val(), {
			async : false,
			onLoad : function(response) {
				r = response.json();
				if (r.success) {
					glow.dom.get('#quickRegisterForm .info').show();
					generic.message('#quickRegisterForm .info',
							"Leider ist der gewünschte Benutzername "
									+ r.userName + " schon vergeben!");
					glow.dom.get("#test .icon")
							.attr("class", "icon fr invalid");
				} else {
					generic.message('#quickRegisterForm .info', "");
					glow.dom.get('#quickRegisterForm .info').hide();
				}
			}
		});
	};

	glow.events.addListener('#form_userName', 'blur', whatever);
	glow.events.addListener('#form_userName', 'focus', whatever);
	glow.events.addListener('#form_userName', 'keyup', whatever);

	document.getElementById('form_userName').focus();
	formobserve(glow.dom.get('#quickRegisterForm'), 'doRegister');
	
}

function doRegister() {
	glow.net.post("/ajax/user/register/", glow.dom.get("#quickRegisterForm")
			.val(), {
		async : false,
		onLoad : function(response) {
			r = response.json();
			if (r.success) {
				generic.uid = r.uid;
				glow.net.get("/ajax/user/register_ok/", {
					async : false,
					onLoad : function(response2) {
						t = response2.text();
					}
				});

				glow.dom.get('.quickRegisterPanel .body').html(t);
				generic.userShortInfo();

			} else {
				glow.dom.get('#quickRegisterForm .info').show();
				generic.message('#quickRegisterForm .info', r.message);
			}
		}
	});
	return false;
}

function logout() {
	glow.net.post('/ajax/user/logout/', {}, {
		async : false
	});
	window.location = '/';
}

function lostPW() {
	// if (typeof (panel['lostpw']) == 'undefined')
		panel['lostpw'] = new glow.widgets.Panel("#panel", {
			template : lostpwPanel,
			width : '390px',
			modal : true,
			anim : 'fade'
		});

	panel['lostpw'].show();
	document.getElementById('form_userName').focus();
	formobserve(glow.dom.get('#lpwForm'), 'sendLostPW');
		
	glow.events.addListener(panel['lostpw'], "hide",
			function(event) {
				glow.dom.get('.lostPanel').html('');
			});
	return false;
}


function sendLostPW() {
	glow.net.post("/ajax/user/lostpw/", glow.dom.get("#lpwForm").val(), {
		async : false,
		onLoad : function(response) {
			r = response.json();
			if (r.success) {
				panel['lostpw'].hide();
				location.reload();
			} else {
				glow.dom.get('#lpwForm .info').show();
				generic.message('#lpwForm .info', r.message);
			}
		}
	});
	return false;
}

function login() {
	if (typeof (panel['login']) == 'undefined')
		panel['login'] = new glow.widgets.Panel("#panel", {
			template : loginPanel,
			width : '390px',
			modal : true,
			anim : 'fade'
		});

	panel['login'].show();
	document.getElementById('form_userName').focus();
	formobserve(glow.dom.get('#quickLoginForm'), 'quickLogin');
}

function performLogin() {
	glow.net.post("/ajax/user/login/", glow.dom.get("#loginForm").val(), {
		async : false,
		onLoad : function(response) {
			r = response.json();
			if (r.success) {
				location.href = location;
			} else {
				glow.dom.get('#loginForm .info').show();
				generic.message('#loginForm .info', r.message);
			}
		}
	});
	return false;
}

function quickLogin() {
	glow.net.post("/ajax/user/login/", glow.dom.get("#quickLoginForm").val(), {
		async : false,
		onLoad : function(response) {
			r = response.json();
			if (r.success) {
				generic.uid = r.uid;
				panel['login'].hide();
				generic.userShortInfo();
				
				glow.dom.get('#commentForm').removeClass('invisible');
				glow.dom.get('#commentAuthorImage').css('visibility', 'hidden');
				glow.dom.get('#commentMeta').addClass('invisible');

				if (typeof (generic.callback) != 'undefined')
					generic.doCallback(generic.callback);
			} else {
				glow.dom.get('#quickLoginForm .info').show();
				generic.message('#quickLoginForm .info', r.message);
			}
		}
	});
	return false;
}

function friend(cmd, user, rld, e, info) {
	if (!generic.uid) {
		login();
		return false;
	}
	
	if(cmd == 'cancel' || cmd == 'deny')
	{
	var conf = confirm('Bist du sicher?');
	if(conf == false)
		return false;
	}

	var cssID = info;
	var href = e;
	
	glow.net.post("/ajax/friendship/action/", {
		command : cmd,
		friendID : user,
		reload : rld
	}, {
		async : false,
		onLoad : function(response) {
			r = response.json();
			if (r.success) {
				if (rld == 'panel')
					generic.userShortInfo();
				else if (rld == 'full')
					location.reload();
			
				glow.dom.get(href).hide();		
				generic.animateEarnedPoints(cssID + ' .point', r.points, r.message);
			
				if (cssID.substr(-4) == 'List')
					window.setTimeout(function() { glow.dom.get(cssID).addClass('opa5'); }, 2000);
								
										
			
			
			} else {
				glow.dom.get('#' + cssID + ' .info').show();
				generic.message('#' + cssID + ' .info', r.message);
			}
		}
	});
}

var user = {
	shortPanel : function(target, uid) {
		glow.net.post("/ajax/user/shortpanel/", {
			id : uid
		}, {
			async : false,
			onLoad : function(response) {
				glow.dom.get(target).html(response.text());
			}
		});
	}
};

var generic = {

	init : function() {
		this.navigation();
		this.addDefaultPanel();
		
		glow.dom.get('.gallery').each(function() {
			this.style.cursor = 'pointer';
			bind(this, 'click', function() { 
				gallery.index = 0; 
				gallery.show(); 
			});
		});
		
		/*glow.dom.get('.tt').each(function() {
		new tooltip(this);
	});*/
	},
	
	abuse : function(type, item) {		
// if (typeof (panel['abuse']) == 'undefined')
			panel['abuse'] = new glow.widgets.Panel("#abusePanel", {
				template : abusePanel,
				width : '390px',
				modal : true,
				anim : 'fade'
			});

		panel['abuse'].show();
		
		glow.dom.get('#form_itemType').val(type);
		glow.dom.get('#form_itemId').val(item);
		
		if(generic.uid > 0)
		{
			glow.net.post("/ajax/user/userdata/", {
				id : generic.uid
			}, {
				async : true,
				onLoad : function(response) {
					r = response.json();
					glow.dom.get('#form_name').val(r.userName);
					glow.dom.get('#form_email').val(r.email);
					document.getElementById('form_name').focus();
					document.getElementById('form_email').focus();
					document.getElementById('form_reason').focus();
				}
			});	
		}
		else
			document.getElementById('form_name').focus();
		
		formobserve(glow.dom.get('#abuseForm'), 'generic.abuseSend');

		glow.events.addListener(panel['abuse'], "hide",
				function(event) {
					glow.dom.get('.abusePanel').html('');
				});
	},
	
	abuseSend : function() {
		glow.net.post("/ajax/generic/abuse/", 
		glow.dom.get('#abuseForm').val(), 
		{
			async : true,
			onLoad : function(response) {
				panel['abuse'].hide();
				tPanel(response.text());
			}
		});
		return false;
	},
	
	lottery : function() {
		
		if (!generic.uid) {
			generic.callback = 'generic.lottery';
			login();
			return false;
		}
		
		glow.net.post('/ajax/lottery/participate/', {
			'id' : this.lotteryId
		}, {
			onLoad : function(response) {
				glow.dom.get('#lottery .participate-button').hide();
				
				r = response.json();
			
				if (r.success) {
					generic.animateEarnedPoints('#lottery .point', r.points, r.message);
				} else {
					glow.dom.get('#lottery .info').show();
					generic.message('#lottery .info', r.message);
				}
			}
		});
	}, 
	
	confirm : function(text,callback) {
			panel['confimPanel'] = new glow.widgets.Panel("#panel", {
				template : confirmPanel,
				width : '520px',
				modal : true,
				closeOnEsc : true,
				hideWindowedFlash : true,
				anim : 'fade'
			});

			panel['confimPanel'].show();
			glow.dom.get('.confirmPanel .panel-bd').html(text);
			
			glow.events.addListener(panel['confimPanel'], "afterHide",
					function(event) {
						glow.dom.get('.confirmPanel').html('');
					});
	},

	loginRequired : function() {
		if (!generic.uid) {
			generic.callback = 'generic.loginRequired';
			login();
			return false;
		}

		return true;
	},

	/**
	 * activate navi dropdowns
	 * 
	 */
	navigation : function() {
		glow.dom.get('#navi .m').each(function() {
			bind(this, 'mouseover', function() {
				glow.dom.get(this.getElementsByTagName('ul')[0]).show();
			});
			bind(this, 'mouseout', function() {
				glow.dom.get(this.getElementsByTagName('ul')[0]).hide();
			});
		});
	},

	/**
	 * display animated message - about recently earned points
	 * 
	 * @param e
	 *            element
	 * @param i
	 *            num points
	 */
	animateEarnedPoints : function(e, i, optionalMessage) {
		if (optionalMessage)
			optionalMessage = optionalMessage + '<br />';

		v = i < 0 ? ' verloren' : ' erhalten';
		i = i < 0 ? (i * -1) : i;
		p = i == 1 ? 'Punkt' : 'Punkte';
		
		if(i != 0)
			pointsMessage = 'Du hast <strong>' + i + '</strong> ' + p + v;
		else
			pointsMessage = '';
		
		glow.dom.get(glow.dom.get(e)
				.html(
						optionalMessage + pointsMessage));
		animatePoints = glow.anim.css(e, 3, {
			'opacity' : {
				from : '1',
				to : '0'
			}
		});
		glow.events.addListener(animatePoints, "complete", function() {
			glow.dom.get(e).html('');
		});

		animatePoints.start();
	},

	/**
	 * unix-timestamp
	 * 
	 * @return int unix-timestamp
	 */
	time : function() {
		ts = new Date();
		Y = ts.getFullYear();
		d = ts.getDate();
		m = ts.getMonth() + 1;
		H = ts.getHours();
		i = ts.getMinutes();
		s = ts.getSeconds();

		return Date.UTC(Y, m, d, H, i, s);
	},

	/**
	 * adds a default-panel to the document
	 */
	addDefaultPanel : function() {
		glow.dom.create('<div id="panel"></div>').appendTo(glow.dom.get(document.body));
	},

	/**
	 * extend object values
	 * 
	 * @param destination
	 * @param source
	 * @return object
	 */
	extendObject : function(destination, source) {
		for (property in source) {
			destination[property] = source[property];
		}
		return destination;
	},

	userShortInfo : function() {
		glow.net.post("/ajax/user/userprofileshort/", { 'url' : location.href }, {
			onLoad : function(response) {
				glow.dom.get("#userShortInfo").html(response.text());
			}
		});
	},

	message : function(e, str) {
		glow.dom.get(e).html(str);
	},

	doCallback : function(c) {
		var c = c;
		if (c) {
			try {
				return window[c]();
			} catch (e) {
				try {
					r = generic[c]();
					generic.callback = null;
					return r;
				} catch (e) {
					try {
						arr = c.split('.');
						return eval(arr[0] + '["' + arr[1] + '"]()');
					} catch (e) {
					}
				}
			}
		}
	},

	member : function(a) {
		if (typeof (a) == 'undefined' && this.uid)
			window.location = this.href;

		if (!this.uid) {
			this.href = a.href;
			generic.callback = 'generic.member';
			login();
			return false;
		} else
			return true;
	},

	load : function(e, bool) {
		e = glow.dom.get(e);
		if (bool) {
			e
					.css(
							'background',
							e.css('background-color') + ' URL(/images/loader.gif) 50% 50% no-repeat');
			e.html('');
		} else
			e.css('background-image', 'none');
	},

	favour : function(pointID, itemID, itemType, cssID) {
		if (typeof (pointID) != 'undefined')
			this.atts = {
				point : pointID,
				item : itemID,
				type : itemType,
				css : cssID
			};

		if (!generic.uid) {
			generic.callback = 'generic.favour';
			login();
			return false;
		}
		
		var atts = this.atts;
		
		glow.net.post('/ajax/favorites/favour/', this.atts, {
			async : false,
			onLoad : function(response) {
				r = response.json();

				if (r.success) {
					generic.userShortInfo();
					generic.animateEarnedPoints('#' + atts.css + ' .point',
							r.points, r.message);
					
					generic.updateFavourBox(atts.item);
					
					return true;
				} else {
					glow.dom.get('#' + atts.css + ' .info').show();
					generic.message('#' + atts.css + ' .info', r.message);
				}
			}
		});
	},

	removeFavour : function(e, id, itemID, itemType) {
		var cssID = e.parentNode.parentNode.id;
		var href = e;

		glow.net.post('/ajax/favorites/remove/', {
			favId : id,
			type : itemType,
			item : itemID
		}, {
			async : false,
			onLoad : function(response) {
				r = response.json();
				if (r.success) {
					glow.dom.get(href).hide();
					generic.userShortInfo();
					generic.animateEarnedPoints('#' + cssID + ' .point',
							r.points, r.message);
					window.setTimeout(function() {
						glow.dom.get('#' + cssID).addClass('opa5');
					}, 2000);
				} else {
					glow.dom.get('#' + cssID + ' .info').show();
					generic.message('#' + cssID + ' .info', r.message);
				}
			}
		});
	},
	
	updateFavourBox : function(p) {
		id = fb = null; 
		var id = '#favourBox' + p;
		fb = glow.dom.get(id);
		fb.removeClass('invisible');
		
		this.helper = [];
		
		if (glow.dom.get(id + ' .avatarList').length > 0) {
			if (this.helper[p] == null) {
				np = fb.get('div > a');
				np.html((parseInt(np.html())+1) + ' Personen');
				this.helper[p] = true;
			}
			else
				return;
			
			glow.net.post('/ajax/favorites/favlist/', { 'list' : generic.uid }, {
				onLoad : function(response) {
					glow.dom.get(id + ' .avatarList ul').append(response.text());
				}	
			});
		}
		else if (glow.dom.get(id).html() == 0) {
			glow.dom.get(id).html('Dir gef&auml;llt das.');
		}
		else {
			np = fb.get('div > a');
			num = parseInt(np.html())+1;
			if (num > 0) {
				np.html(num + ' Personen');
				oc = np.attr('onclick');
				np.attr('onclick', oc.replace("');r", "," + generic.uid + "');r"));
			}
		}
	},
	
	getFavourList : function(e, ids) {
		if (e.loaded == true)
			return false;
				
		e.loaded = true;
		var target = glow.dom.create('<div></div>');
		target.addClass('avatarList');
		glow.dom.get(e.parentNode).after(target);
		
		glow.net.post('/ajax/favorites/favlist/', { 'list' : ids }, {
			onLoad : function(response) {
				target.append(glow.dom.create('<ul>' + response.text() + '</ul>'));
			}
		});
	},

	download : function(a, pointID, itemID, itemType, cssID) {
		if (typeof (a) != 'undefined')
			this.theLink = {
				href : a.href
			};

		if (pointID)
			this.atts = {
				point : pointID,
				item : itemID,
				type : itemType
			};

		if (!generic.uid) {
			generic.callback = 'generic.download';
			login();
			return false;
		}

		window.open(this.theLink.href, '_blank');
		return false;
	},
	
	getCookie : function(name) {
		nameEQ = name + '=';
  		cs = document.cookie.split(';');
		for(i = 0; i < cs.length; i++) {
			c = cs[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;
	},
	
	setCookie : function(type, value) {
   		d = new Date();
   		d.setTime(d.getTime()+(60*60*24*365));
   		expires = '; expires=' + d.toGMTString();
		
   		document.cookie = type + '=' + value + expires + '; path=/';
	},
	
	removeAction : function(a, id, bool) {		
		glow.net.post('/ajax/user/removeaction/', { 'id' : id, 'stat' : bool});
		if (bool == '0') {
			glow.dom.get('#action' + id).addClass('opa5');
			glow.dom.get(a).toggleClass('invisible');
			glow.dom.get(a.nextSibling).toggleClass('invisible');
		} 
		else {
			glow.dom.get('#action' + id).removeClass('opa5');
			glow.dom.get(a).toggleClass('invisible');
			glow.dom.get(a.previousSibling).toggleClass('invisible');		}
	}
};

function calendar() {
	this.options = generic.extendObject( {
		instance : null,
		cssID : null,
		target : null,
		buttons : null,
		selectedDate : null,
		actualDate : null,
		visible : false,
		firstYear : 2009,
		lastYear : 2011
	}, arguments[0] || {});

	this.selectedDate = this.options.selectedDate;
	this.actualDate = this.options.actualDate;

	this.show = function(clicked, a) {
		if (glow.dom.get(clicked).hasClass('icon'))
			toggleClass = true;
		else if (clicked.tagName == 'INPUT') {
			toggleClass = true;
			clicked = document.getElementById(a);
		} else
			toggleClass = false;

		if (toggleClass)
			clicked.className = clicked.className == 'icon close' ? 'icon cal'
					: 'icon close';

		if (glow.dom.get(this.options.cssID).css('display') == 'block'
				&& clicked !== true)
			return this.hide();

		if (clicked !== true)
			glow.dom.get('select').each(function() {
				this.style.visibility = 'hidden';
			});

		this.selectedDate = this.selectedDate || this.actualDate;

		p = {
			elements : this.options.selectable ? 'SELM,SELY'
					: 'NM,TODAY,PM,TXTM,TXTY',
			FirstYear : this.options.firstYear,
			LastYear : this.options.lastYear,
			ActualDate : this.actualDate,
			SelectedDate : this.selectedDate,
			DateFormat : 'd.m.Y',
			'NextMonth[href]' : '#',
			'NextMonth[onclick]' : this.options.instance
					+ '.actualDate = [DATE]; ' + this.options.instance
					+ '.show(true); return false',
			'NextYear[href]' : '#',
			'NextYear[onclick]' : this.options.instance
					+ '.actualDate = [DATE]; ' + this.options.instance
					+ '.show(true); return false',
			'PrevMonth[href]' : '#',
			'PrevMonth[onclick]' : this.options.instance
					+ '.actualDate = [DATE]; ' + this.options.instance
					+ '.show(true); return false',
			'PrevYear[href]' : '#',
			'PrevYear[onclick]' : this.options.instance
					+ '.actualDate = [DATE]; ' + this.options.instance
					+ '.show(true); return false',
			'SelectYear[onchange]' : this.options.instance
					+ '.actualDate = [DATE]; ' + this.options.instance
					+ '.show(true); return false',
			'SelectMonth[onchange]' : this.options.instance
					+ '.actualDate = [DATE]; ' + this.options.instance
					+ '.show(true); return false',
			'TodayButton[onclick]' : this.options.instance
					+ '.actualDate = [DATE]; ' + this.options.instance
					+ '.show(true); return false',
			'SelectDate[href]' : '#',
			'SelectDate[target]' : '',
			'SelectDate[onclick]' : this.options.instance
					+ '.selectedDate = [DATE]; ' + this.options.instance
					+ '.actualDate = [DATE]; ' + this.options.instance
					+ '.setDate(); ' + this.options.instance
					+ '.hide(); return false;'
		};
		// 'SelDate[onclick]' : this.options.instance + '.selectedDate = [DATE];
		// ' + this.options.instance + '.actualDate = [DATE]; ' +
		// this.options.instance + '.show(true); return false;'
		// ?von=23.10.2009

		var cssID = this.options.cssID;

		glow.net.post('/ajax/calendar/show/', p, {
			async : false,
			onLoad : function(response) {
				glow.dom.get(cssID).html(response.text());
				glow.dom.get(cssID).css('display', 'block');
			}
		});
	};

	this.setDate = function() {
		glow.dom.get(this.options.target).attr('value', this.actualDate);
	};

	this.calIcon = glow.dom.get(this.options.cssID).prev();

	this.hide = function() {
		if (this.calIcon.html() == '') {
			glow.dom.get(this.options.cssID).css('display', 'none');
			glow.dom.get(this.options.cssID).html('');

			if (this.calIcon.hasClass('icon')) {
				this.calIcon.addClass('cal');
				this.calIcon.removeClass('close');
			}
			if (glow.dom.get('.hoverCal .calendar').length == 0)
				glow.dom.get('select').each(function() {
					this.style.visibility = 'visible';
				});
		} else
			location.href = '/Events/Terminkalender/?von='
					+ this.selectedDate + '&bis=' + this.selectedDate;
	};

	if (this.options.visible)
		this.show(true);

	if (this.calIcon.hasClass('icon')) {
		this.calIcon.css('display', 'block');
	}

	if (this.options.buttons != null) {
		for (b in this.options.buttons)
			glow.dom.get(this.options.buttons[b]).css('display', 'block');
	}
}



function hideAllButOne(toHide, toShow) {
	glow.dom.get(toHide).each(function() {
		glow.dom.get(this).hide();
	});
	glow.dom.get('#' + toShow).show();
}
function toggleAllButOne(toggleAll, toggleButOne, all, butOne) {
	var a = all;
	var b = butOne;
	glow.dom.get(toggleAll).each(function() {
		glow.dom.get(this).removeClass(b);
		glow.dom.get(this).addClass(a);
	});
	toggleButOne.removeClass(all);
	toggleButOne.addClass(butOne);
}

function getPosition(element) {
	var elem = element, tagname = '', x = 0, y = 0;
  
	while ((typeof(elem) == 'object') && (typeof(elem.tagName) != 'undefined')) {
		y += elem.offsetTop;
		x += elem.offsetLeft;
		tagname = elem.tagName.toUpperCase();

		if (tagname == 'BODY')
			elem = 0;

		if (typeof(elem) == 'object')
			if (typeof(elem.offsetParent) == 'object')
				elem = elem.offsetParent;
	}
	position = new Object();
  	position.x = x;
  	position.y = y;
	return position;
}


/** slider */
if (typeof (max) == 'undefined') {
	var max = [];
	var slider = [];
	var bind_buttons = [];
}
function setSlider(hash) {
	pId = '#p_' + hash;
	if (typeof (bind_buttons[hash]) == 'undefined') {
		sbr = '#sbr_' + hash;
		sbl = '#sbl_' + hash;
		bind(sbr, 'click', function() {
			slider[hash].val(max[hash]);
			setSlider(hash);
		});
		bind(sbl, 'click', function() {
			slider[hash].val(0);
			setSlider(hash);
		});
		bind_buttons[hash] = 1;
	} else {
		x = slider[hash].val() / -100 * max[hash];
		glow.dom.get(pId).css('left', x + 'px');
	}
}

var navigation = {
	nav : null,
	init : function() {
		this.m_news = glow.dom.get('#m-news');
		var s_news = glow.dom.get('#s-news');
		bind(this.m_news, 'mouseover', function() {
			s_news.show();
			glow.dom.get('#s-news .shadow')
					.css(
							'height',
							(10 + parseInt(glow.dom.get('#s-news')
									.css('height'))) + 'px');
		});
		bind(this.m_news, 'mouseout', function() {
			s_news.hide();
		});
		
		this.m_events = glow.dom.get('#m-events');
		var s_events = glow.dom.get('#s-events');
		bind(this.m_events, 'mouseover', function() {
			s_events.show();
			glow.dom.get('#s-events .shadow')
					.css(
							'height',
							(10 + parseInt(glow.dom.get('#s-events')
									.css('height'))) + 'px');
		});
		bind(this.m_events, 'mouseout', function() {
			s_events.hide();
		});

		this.m_blog = glow.dom.get('#m-blog');
		var s_blog = glow.dom.get('#s-blog');
		bind(this.m_blog, 'mouseover', function() {
			s_blog.show();
			glow.dom.get('#s-blog .shadow')
					.css(
							'height',
							(10 + parseInt(glow.dom.get('#s-blog')
									.css('height'))) + 'px');
		});
		bind(this.m_blog, 'mouseout', function() {
			s_blog.hide();
		});

		this.m_ent = glow.dom.get('#m-ent');
		var s_ent = glow.dom.get('#s-ent');
		bind(this.m_ent, 'mouseover',
				function() {
					s_ent.show();
					glow.dom.get('#s-ent .shadow')
							.css(
									'height',
									(10 + parseInt(glow.dom.get('#s-ent').css(
											'height'))) + 'px');
				});
		bind(this.m_ent, 'mouseout', function() {
			s_ent.hide();
		});

		this.m_comm = glow.dom.get('#m-comm');
		var s_comm = glow.dom.get('#s-comm');
		bind(this.m_comm, 'mouseover', function() {
			s_comm.show();
			glow.dom.get('#s-comm .shadow')
					.css(
							'height',
							(10 + parseInt(glow.dom.get('#s-comm')
									.css('height'))) + 'px');
		});
		bind(this.m_comm, 'mouseout', function() {
			s_comm.hide();
		});
	}
};

var voting = {
	check : function(rObj)
	{	
	    for (var i=0; i<rObj.length; i++) if (rObj[i].checked) return rObj[i].value;
	    return false;
	},

	switchResult : function()
	{
		state = glow.dom.get('#resultDiv').css('display');

		if(state == 'none')
			glow.dom.get('#resultDiv').show();
		else
			glow.dom.get('#resultDiv').hide();
		return false;
	},

	doit : function()
	{
		questionID = document.voteForm.questionID.value;
		
		if(!generic.uid && document.voteForm.guest.value != '1')
		{
			generic.callback = 'voting.doit';
			login();
			return false;
		}

		
		vItem = this.check(document.voteForm.voteItem);
		
		if(vItem == false)
			return false;
		
		glow.net.post("/ajax/vote/registervote/", {
				qid: questionID,
				answer: vItem
				
				}, {
			async : false,
			onLoad: function(response) 
			{		
				r = response.json();
				if(r.success == true)
				{
					
					glow.dom.get('#voteDiv').html(r.message);
					glow.dom.get('#resultDiv').show();
				}
				else
					glow.dom.get('#voteDiv').html(glow.dom.get('#voteDiv').html() + r.message);				
	        }
		});
	}
};


var gallery = {
	index : 0,
	folder : false,
	show : function() {	
		if (typeof(panel['galleryPanel']) == 'undefined') { 
			panel['galleryPanel'] = new glow.widgets.Panel("#panel", {
				template : galleryPanel,
				width : (this.width +16) +'px',
				modal : true,
				autoPosition: true,
				closeOnEsc : true,
				hideWindowedFlash : true,
				anim : 'fade'
			});
		}
		
		document.getElementById('gallery-image').src = this.images[this.index].file;
			
		
		document.getElementById('gallery-caption').innerHTML = this.images[this.index].caption + '<span class="grey fr">' + this.images[this.index].source + '</span>';
		document.getElementById('x-of-y').innerHTML = 'Bild ' + (this.index +1) + ' von ' + this.images.length;			
		
		panel['galleryPanel'].show();

	},
	browse : function(bool, e) {
		e.blur();
		if (bool)
			this.index = this.index +1 < this.images.length ? this.index +1 : 0;
		else
			this.index = this.index -1 >= 0 ? this.index -1 : this.images.length -1;

		this.show();
	}	
};







function widget(opts) {
	this.title = opts.title;
	this.id = opts.id;
	this.len = opts.len;
	this.rss = opts.rss;
	this.tab = opts.tab;
	this.start = 0;
	this.step = 3;
	this.hasList = opts.hasList || true;
	this.collapsed = opts.collapsed == 1 ? 'rightArrow' : 'downArrow';
		
	this.len = this.len - (this.len%this.step);
	
	this.widget = glow.dom.get('#' + this.id);
	
	if (this.widget.hasClass('on')) {
		// '<a href="#" rel="' + this.id + '" class="icon toggle ' +
		// this.collapsed + '"></a>' +
		this.widget.get('.opts').html(
			'<a href="#" rel="' + this.id + '" class="icon removeWidget"></a>');
	}
		
	bind(this.widget.get('.removeWidget'), 'click', function() {
		if (confirm('Widget wirklich entfernen?') == true) {
			glow.dom.get('#' + this.rel).destroy();
			saveWidgets();
		}
		return false;
	});
	
	bind(this.widget.get('.toggle'), 'click', function() {
		glow.dom.get('#' + this.rel + ' .w-body').toggleClass('invisible');

		me = glow.dom.get(this);
		if (me.hasClass('downArrow')) {
			me.removeClass('downArrow');
			me.addClass('rightArrow');
		}
		else {
			me.removeClass('rightArrow');
			me.addClass('downArrow');
		}
		
		return false;
	});
	
	var that = this;
	if (glow.dom.get('#'+this.id).hasClass('rss')) {
		bind('#next-' + this.id, 'click', function() { that.browse(true, this); return false;});
		bind('#prev-' + this.id, 'click', function() { that.browse(false, this); return false;});
	}
	
	this.browse = function(bool, a) {
		if (glow.dom.get(a).hasClass('opa5'))
			return false;
				
		this.start = bool ? this.start +1 : this.start -1;

		if (this.start == 0) {
			this.start = 0;
			glow.dom.get(a).addClass('opa5');
		} else
			glow.dom.get('#prev-' + this.id).removeClass('opa5');
		
		if (this.start == this.len / this.step) {
			this.start = this.len / this.step;
			glow.dom.get(a).addClass('opa5');
		} else
			glow.dom.get('#next-' + this.id).removeClass('opa5');
		
		glow.net.post('/ajax/widget/browse/', {
			'start' : this.start,
			'rss' : this.rss,
			'tab' : this.tab ,
			'title' : that.id
		}, {
			async  : false,
			onLoad : function(response) {				
				that.widget.get('ul').html(response.text());
				that.monitor();
			}
		});
	};
	
	this.monitor = function() {
		if (glow.dom.get('#' + this.id).hasClass('rss')) {
			glow.dom.get('#' + this.id + ' ul li').each(function(i) {
				glow.events.removeAllListeners(this);
				this.id = i;

				/*
				 * bind(this, 'mouseover', function() { hideAllButOne('#' +
				 * this.parentNode.parentNode.parentNode.id + ' .hideMe',
				 * this.parentNode.parentNode.parentNode.id.replace('body-','')
				 * +''+ this.id); toggleAllButOne('#' +
				 * this.parentNode.parentNode.parentNode.id + ' .rssItem
				 * strong', glow.dom.get(this).get('strong'), 'blue', 'orange');
				 * });
				 */
			});
		}
	};
	
	this.monitor();
}

function initWidgets() {
	new glow.widgets.Sortable(
		'#page .widget-col-1, #page .widget-col-2', {
		draggableOptions : {
			handle : 'h4'
		},
	    onSort : saveWidgets
	});
}
function saveWidgets() {
	if (!generic.uid)
		return false;
	
    var order1 = [];
    var order2 = [];
    glow.dom.get('.widget-col-1 .widget').sort().each(function () {
        order1.push(glow.dom.get(this).attr('rel'));
    });
    glow.dom.get('.widget-col-2 .widget').sort().each(function () {
        order2.push(glow.dom.get(this).attr('rel'));
    });
    
    glow.net.post('/ajax/widget/update/', {
    	c1 : order1.join(','),
    	c2 : order2.join(',')
    }, {
    	async : false
    });	
}


var showWidget;
var hideWidget;
var direction;

function showWidgetPool() {
	showWidget = glow.anim.slideDown("#widget-pool", 1);
	showWidget.start();
	direction = 'show';
}
function hideWidgetPool() {
	hideWidget = glow.anim.slideUp("#widget-pool", 1);
	hideWidget.start();
	direction = 'hide';
}
function toggleWidgetPool() {
			
	if (parseInt(glow.dom.get('#widget-pool').css('height')) > 0) {
		if (direction == 'show')
			hideWidgetPool();
		else
			showWidgetPool();
	}
	else {
		if (typeof(hideWidget) != 'undefined')
			hideWidget.stop();
		showWidgetPool();
	}
}



function magicTab(id, opts) {
	
	this.animation = opts.animation || false;	
	
	this.container = document.getElementById(id + '-container');
	var that = this;
	
	this.a = glow.dom.get('#' + id + ' a');
	this.a.each(function() {
		glow.events.addListener(this, 'click', function() {
			that.click(this);
			return false;		
		}) ;
	});
	
	this.click = function(a) {
		id = '#' + a.href.split('#')[1];

		copy = glow.dom.get(id);
		if (this.animation !== false)
			copy.css('height', 0);
		copy.prependTo(this.container);

		if (this.animation !== false) {
			d = glow.anim.slideDown(id, 1);
			d.start();
		}
	}
}