//Application Specific global js functions

function hideNotification(nid) {
	var Slider = new Fx.Slide('user_notification' + nid, {duration: 500});
	Slider.hide();
	jslink('/DE/start', {'id': nid}, 'User::close_notification');
	return true;
}

function correctHeight(el) {
	el.effect('height').set(el.getScrollSize().y);
	el.effect('height').set('auto');
}

var SMail = new Class ({	
	initialize: function(/*options*/){
		//this.setOptions(options);
	},	
	send: function() {
		if($('theMailTopic') && $('theMailTopic').getValue().trim().length<=0) {
			alert('Bitte einen Betreff eingeben');
			return false;
		}
		if($('theMailText').getValue().trim().length<=3) {
			alert('Bitte mehr als 3 Zeichen je Mail schreiben!');
			return false;
		}
		myS.get("mail").slideOut().chain(
			function() {
				$('mailForm').addClass('hidden');
				$('mailSending').removeClass('hidden');
				myS.get("mail").slideIn();
			}
		);
		
		if(document.location.href.test('profile/')) {
			var delay = 2000;
		}else{
			var delay = 500;
		}
		
		sendform('mailForm', 'GFCMail::send', 
			function(ret) {
				myS.get("mail").slideOut().chain(
					function(ret) {
						$('mailSending').addClass('hidden');
						$('mailSendingFin').removeClass('hidden');
						$('mailSendingFin').setHTML('<div style="height:150px; margin: 0pt auto; text-align: center;"><strong>'+(ret=='true'?LANG.app.was_sent:ret.substring(1,ret.length-1))+'</strong></div><br/><br/><br/>');
						myS.get("mail").slideIn();
						(function (){
							if(document.location.href.test('profile/')) {
								$('pmenu_overview').fireEvent("click");
							}
							if($('winContainer')) $('winContainer').addClass('hidden');
							if($('answerMail') && $('mail_'+$('answerMail').value).getElement('.m_state')) {
								$('mail_'+$('answerMail').value).getElement('.m_state').setHTML('<img src="/images/icons/16-email-reply.png" title="'+LANG.app.answered+'" alt="'+LANG.app.answered+'"/>');								
								$('mail_'+$('answerMail').value).removeClass('m_unread');
								$('mail_'+$('answerMail').value).addClass('m_responded');
							}
							$('mailSending').addClass('hidden');
							$('mailSendingFin').addClass('hidden');
							$('mailForm').removeClass('hidden');
							$('theMailText').value='';
							if($('theMailTopic')) $('theMailTopic').value='';
						}).delay(delay);
					}.pass(ret)
				);
			}
		);
		return false;
	},
	oldMailCount: 0,	
	showCount: function (count) {
		if(count<0) count = this.oldMailCount+count;
		this.oldMailCount = count;
		if(count<=0) 
			top.document.title = top.document.title.replace(/ - [0-9]* Mails?/, '')
		else if(top.document.title.search(/Mails?/)>0)
			top.document.title = top.document.title.replace(/ - [0-9]* Mails?/, " - "+count+" Mail"+(count!=1?"s":""))
		else
			top.document.title = top.document.title+" - "+count+" Mail"+(count!=1?"s":"");
		
		if($('menu_mailcounter')) {
			if(count<=0) 
				$('menu_mailcounter').innerHTML = $('menu_mailcounter').innerHTML.replace(/&nbsp;\([0-9]*\)/, '')
			else if($('menu_mailcounter').innerHTML.search(/&nbsp;\([0-9]*\)/)>0)
				$('menu_mailcounter').innerHTML = $('menu_mailcounter').innerHTML.replace(/&nbsp;\([0-9]*\)/, "&nbsp;("+count+")");
			else
				$('menu_mailcounter').innerHTML = $('menu_mailcounter').innerHTML+"&nbsp;("+count+")";
		}
		
	}
});
mySMail = new SMail();


function sendform(theForm, phpfunc, jsfunc) {
	var myRequest = new Request({
		'method': 'post',
		'url': $(theForm).get('action'),
		'onComplete': function(ret){
			if(ret=='error_login_required'){location.href='/'+LANG.LANG+'/nologin/';
			}else{jsfunc.attempt(ret);}
		},
		'onFailure': jsfunc.pass('failure'),
		'onSuccess': function(){
			if($$('.load')) $each($$('.load'), function(el){
				el.addClass('ok'); new Fx.Style(el, 'opacity').set(1);
			})
		},
		'onRequest': function(el){
			if($$('.load')) $each($$('.load'), function(el){
				el.removeClass('ok');  new Fx.Style(el, 'opacity').set(1);
			})
		}.pass($(theForm))
	}).send( $(theForm).toQueryString()+'&jscall='+phpfunc );
	/*
	if(!window.ie && $(theForm).getElement('input[name=jscall]')) {
		$(theForm).set('send', {method: 'post', );
		$(theForm).send();
	}else{
		var myCall = new Element('input', {'class': 'hidden', 'type': 'hidden', 'name': 'jscall', 'value': phpfunc});
		$(theForm).set('send', {method: 'post', onComplete: jsfunc, onFailure: jsfunc.pass('failure'), onSuccess: function(){if($$('.load')) $each($$('.load'), function(el){el.addClass('ok'); new Fx.Style(el, 'opacity').set(1);})}, onRequest: function(el){if($$('.load')) $each($$('.load'), function(el){new Fx.Style(el, 'opacity').set(1);})}.pass($(theForm))});
		$(theForm).adopt(myCall).send();
	}*/
	return false;
}

function jslink(url, params, phpfunc, jsfunc, errorFallback) {
	if($type(jsfunc)==false) jsfunc = Class.empty;
	params['jscall'] = phpfunc;
	var call = new Request({url: url, method: 'post', data: params, onComplete: function(ret){if(ret=='error_login_required'){location.href='/'+LANG.LANG+'/nologin/';}else{jsfunc.attempt(ret);}}, onFailure: errorFallback}).send();
	return call;
}

function alterNate(elm){
	if (!elm.base) elm.base = elm.value
	if (elm.value == elm.base) elm.value = "";
	//else if (elm.value == "") elm.value = elm.base;
}

/**
 * an alternate alterNate :) using DOM defaults and returning default value on no changes
 */
function alterNate2(el)
{
	if (el.value == el.defaultValue)
		el.value = '';
	else if (el.value == '')
		el.value = el.defaultValue;
}

function revertp(p) {
	
	p = p.replace(/<!--(.*?)-->/gi, '');
	p = p.replace(/\n/gi, '');
	
	//remove Smilie img stuff
	p = p.replace(/<img class="?smilie"?(.*?)src="\/images\/smilies\/(.*?)\.gif"\/?>/gi, '[s]$2[/s]');
	
	p = p.replace(/<b>/gi, '[b]');
	p = p.replace(/<\/b>/gi, '[/b]');
	p = p.replace(/<i>/gi, '[i]');
	p = p.replace(/<\/i>/gi, '[/i]');
	p = p.replace(/<u>/gi, '[u]');
	p = p.replace(/<\/u>/gi, '[/u]');
	p = p.replace(/<s>/gi, '[s]');
	p = p.replace(/<\/s>/gi, '[/s]');
	p = p.replace(/<ul>/gi, '[list]');
	p = p.replace(/<li>/gi, '[*]');
	p = p.replace(/<\/li>/gi, '');
	p = p.replace(/<\/ul>/gi, '[/list]');
	
	p = p.replace(/\[s\]zwinker2\[\/s\]/gi, ':D');
	p = p.replace(/\[s\]icon_biggrin\[\/s\]/gi, ':D');
	p = p.replace(/\[s\]icon_smile\[\/s\]/gi, ':)');
	p = p.replace(/\[s\]icon_sad\[\/s\]/gi, ':(');
	p = p.replace(/\[s\]icon_surprised\[\/s\]/gi, ':o');
	p = p.replace(/\[s\]icon_eek\[\/s\]/gi, ':shock:');
	p = p.replace(/\[s\]icon_confused\[\/s\]/gi, ':?');
	p = p.replace(/\[s\]icon_cool\[\/s\]/gi, '8)');
	p = p.replace(/\[s\]icon_lol\[\/s\]/gi, ':lol:');
	p = p.replace(/\[s\]icon_mad\[\/s\]/gi, ':x');
	p = p.replace(/\[s\]icon_razz\[\/s\]/gi, ':P');
	p = p.replace(/\[s\]icon_redface\[\/s\]/gi, ':oops:');
	p = p.replace(/\[s\]icon_cry\[\/s\]/gi, ':cry:');
	p = p.replace(/\[s\]icon_evil\[\/s\]/gi, ':evil:');
	p = p.replace(/\[s\]icon_twisted\[\/s\]/gi, ':twisted:');
	p = p.replace(/\[s\]icon_rolleyes\[\/s\]/gi, ':roll:');
	p = p.replace(/\[s\]icon_wink\[\/s\]/gi, ';)');
	p = p.replace(/\[s\]icon_exclaim\[\/s\]/gi, ':!:');
	p = p.replace(/\[s\]icon_question\[\/s\]/gi, ':?:');
	p = p.replace(/\[s\]icon_idea\[\/s\]/gi, ':idea:');
	p = p.replace(/\[s\]icon_arrow\[\/s\]/gi, ':arrow:');
	p = p.replace(/\[s\]icon_neutral\[\/s\]/gi, ':|');
	p = p.replace(/\[s\]icon_mrgreen\[\/s\]/gi, ':mrgreen:');

	p = p.replace(/<img ([^>]*?)src="([^"]*)"([^>]*?)\/?>/gi, '[img]$2[/img]');
	
	p = p.replace(/<a ([^>]*?)href="([^"]*)"([^>]*?)>([^"]*)<\/a>/gi, '[url=$2]$4[/url]');
	
	p = p.replace(/<br \/>/gi, '\n');
	p = p.replace(/<br>/gi, '\n');
	p = p.replace(/<wbr>/gi, '');
	p = p.replace(/<br\/>/gi, '\n');
	p = p.replace(/<blockquote>.*?<p>(.*?)/gi, '[quote]$1');
	p = p.replace(/<\/p><\/blockquote>/gi, '\[/quote]');
	return p.trim();
}

function surl(smilie) {
	return '<img class="smilie" alt="'+smilie+'" src="/images/smilies/'+smilie+'.gif"/>';
}

function wpautop(p) {
	p = p.replace(/\r\n/g, '\n');
	p = p.replace(/\r/g, '\n');
	p = p.replace(/\[b\]/g, '<b>');
	p = p.replace(/\[\/b\]/g, '</b>');
	p = p.replace(/\[i\]/g, '<i>');
	p = p.replace(/\[\/i\]/g, '</i>');
	p = p.replace(/\[u\]/g, '<u>');
	p = p.replace(/\[\/u\]/g, '</u>');
	p = p.replace(/\[s\]/g, '<s>');
	p = p.replace(/\[\/s\]/g, '</s>');
	p = p.replace(/\[list\]/g, '<ul>');
	p = p.replace(/\[\*\]/g, '<li>');
	p = p.replace(/\[\/list\]/g, '</ul>');
	
	p = p.replace(/([\n\ \.]):-x/g, '$1'+surl('icon_mad'));
	p = p.replace(/([\n\ \.]):\)/g, '$1'+surl('icon_smile'));
	p = p.replace(/([\n\ \.]):D/g, '$1'+surl('icon_biggrin'));
	p = p.replace(/([\n\ \.]):oops:/g, '$1'+surl('icon_redface'));
	p = p.replace(/([\n\ \.]):-D/g, '$1'+surl('icon_biggrin'));
	p = p.replace(/([\n\ \.]):grin:/g, '$1'+surl('icon_biggrin'));
	p = p.replace(/([\n\ \.]):\)/g, '$1'+surl('icon_smile'));
	p = p.replace(/([\n\ \.]):-\)/g, '$1'+surl('icon_smile'));
	p = p.replace(/([\n\ \.]):smile:/g, '$1'+surl('icon_smile'));
	p = p.replace(/([\n\ \.]):\(/g, '$1'+surl('icon_sad'));
	p = p.replace(/([\n\ \.]):-\(/g, '$1'+surl('icon_sad'));
	p = p.replace(/([\n\ \.]):sad:/g, '$1'+surl('icon_sad'));
	p = p.replace(/([\n\ \.]):o/g, '$1'+surl('icon_surprised'));
	p = p.replace(/([\n\ \.]):-o/g, '$1'+surl('icon_surprised'));
	p = p.replace(/([\n\ \.]):eek:/g, '$1'+surl('icon_surprised'));
	p = p.replace(/([\n\ \.]):shock:/g, '$1'+surl('icon_eek'));
	p = p.replace(/([\n\ \.]):\?/g, '$1'+surl('icon_confused'));
	p = p.replace(/([\n\ \.]):-\?/g, '$1'+surl('icon_confused'));
	p = p.replace(/([\n\ \.]):\?\?\?:/g, '$1'+surl('icon_confused'));
	p = p.replace(/([\n\ \.])8\)/g, '$1'+surl('icon_cool'));
	p = p.replace(/([\n\ \.])8-\)/g, '$1'+surl('icon_cool'));
	p = p.replace(/([\n\ \.]):cool:/g, '$1'+surl('icon_cool'));
	p = p.replace(/([\n\ \.]):lol:/g, '$1'+surl('icon_lol'));
	p = p.replace(/([\n\ \.]):x/g, '$1'+surl('icon_mad'));
	p = p.replace(/([\n\ \.]):-x/g, '$1'+surl('icon_mad'));
	p = p.replace(/([\n\ \.]):mad:/g, '$1'+surl('icon_mad'));
	p = p.replace(/([\n\ \.]):P/g, '$1'+surl('icon_razz'));
	p = p.replace(/([\n\ \.]):-P/g, '$1'+surl('icon_razz'));
	p = p.replace(/([\n\ \.]):razz:/g, '$1'+surl('icon_razz'));
	p = p.replace(/([\n\ \.]):cry:/g, '$1'+surl('icon_cry'));
	p = p.replace(/([\n\ \.]):evil:/g, '$1'+surl('icon_evil'));
	p = p.replace(/([\n\ \.]):twisted:/g, '$1'+surl('icon_twisted'));
	p = p.replace(/([\n\ \.]):roll:/g, '$1'+surl('icon_rolleyes'));
	p = p.replace(/([\n\ \.]):wink:/g, '$1'+surl('icon_wink'));
	p = p.replace(/([\n\ \.]);\)/g, '$1'+surl('icon_wink'));
	p = p.replace(/([\n\ \.]);-\)/g, '$1'+surl('icon_wink'));
	p = p.replace(/([\n\ \.]):!:/g, '$1'+surl('icon_exclaim'));
	p = p.replace(/([\n\ \.]):\?:/g, '$1'+surl('icon_question'));
	p = p.replace(/([\n\ \.]):idea:/g, '$1'+surl('icon_idea'));
	p = p.replace(/([\n\ \.]):arrow:/g, '$1'+surl('icon_arrow'));
	p = p.replace(/([\n\ \.]):\|/g, '$1'+surl('icon_neutral'));
	p = p.replace(/([\n\ \.]):-\|/g, '$1'+surl('icon_neutral'));
	p = p.replace(/([\n\ \.]):neutral:/g, '$1'+surl('icon_neutral'));
	p = p.replace(/([\n\ \.]):mrgreen:/g, '$1'+surl('icon_mrgreen'));
	
	p = p.replace(/\[img\]([^\]]*)\[\/img\]/g, '<img src="$1"/>');
	
	p = p.replace(/\[url\]([^\]]*)\[\/url\]/g, '<a href="$1">$1</a>');
	p = p.replace(/\[url=([^\]]*)\]([^\]]*)\[\/url\]/g, '<a href="$1">$2</a>');
	
	p = p.replace(/\[quote\](.*?)/g, '<blockquote><b>Zitat:</b><br />$1');
	p = p.replace(/\[\/quote\]/g, '</blockquote>');
	p = p.replace(/\n/g, '<br />');
	return p;
}

function insertbb(aTag, eTag) {
  if(arguments[2]) 
  	var input = document.getElementById(arguments[2]);
  else
  	var input = document.getElementById('message');
  input.focus();
  /* für Internet Explorer */
  if(typeof document.selection != 'undefined') {
    /* Einfügen des Formatierungscodes */
    var range = document.selection.createRange();
    var insText = range.text;
    range.text = aTag + insText + eTag;
    /* Anpassen der Cursorposition */
    range = document.selection.createRange();
    if (insText.length == 0) {
      range.move('character', -eTag.length);
    } else {
      range.moveStart('character', aTag.length + insText.length + eTag.length);      
    }
    range.select();
  }
  /* für neuere auf Gecko basierende Browser */
  else if(typeof input.selectionStart != 'undefined')
  {
    /* Einfügen des Formatierungscodes */
    var start = input.selectionStart;
    var end = input.selectionEnd;
    var insText = input.value.substring(start, end);
    input.value = input.value.substr(0, start) + aTag + insText + eTag + input.value.substr(end);
    /* Anpassen der Cursorposition */
    var pos;
    if (insText.length == 0) {
      pos = start + aTag.length;
    } else {
      pos = start + aTag.length + insText.length + eTag.length;
    }
    input.selectionStart = pos;
    input.selectionEnd = pos;
  }
  /* für die übrigen Browser */
  else
  {
    /* Abfrage der Einfügeposition */
    var pos = input.value.length;

    /* Einfügen des Formatierungscodes */
    var insText = prompt("Bitte geben Sie den zu formatierenden Text ein:");
    input.value = input.value.substr(0, pos) + aTag + insText + eTag + input.value.substr(pos);
  }
  
  if (typeof updateLivePreview == 'function') updateLivePreview();
}
/**
 * History
 *
 * @version		1.0
 *
 * @license		MIT License
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	2008 Author
 */

var History = $extend(history, {

	implement: function(obj) {
		return $extend(this, obj);
	}

});

History.implement(new Events($empty));

History.implement({

	state: null,

	start: function() {
		if (this.started) return this;
		this.state = this.getHash();
		if (Browser.Engine.trident) {
			var iframe = new Element('iframe', {
				'src': "javascript:'<html></html>'",
				'styles': {
					'position': 'absolute',
					'top': '-1000px'
				}
			}).inject(document.body).contentWindow;
			var writeState = function(state) {
				iframe.document.write('<html><body onload="top.History.$listener(\'', encodeURIComponent(state) ,'\');">Moo!',state,'</body></html>');
				iframe.document.close();
			};
			$extend(this, {
				'$listener': function(state) {
					state = decodeURIComponent(state);
					if (this.state != state) this.setHash(state).changeState(state);
				}.bind(this),
				'setState': function(state, force) {
					if (this.state != state || force) {
						if (!force) this.setHash(state).changeState(state, true);
						writeState(state);
					}
					return this;
				},
				'trace': function() {
					var state = this.getHash();
					if (state != this.state) writeState(state);
				}
			});
			var check = (function() {
				if (iframe.document && iframe.document.body) {
					check = $clear(check);
					if (!iframe.document.body.innerHTML) this.setState(this.state, true);
				}
			}).periodical(50, this);
		} else {
			if (Browser.Engine.presto915) {
				new Element('img', {
					'src': "javascript:location.href='javascript:History.trace();';",
					'styles': {
						'position': 'absolute',
						'top': '-1000px'
					}
				}).inject(document.body);
			}
		}
		this.trace.periodical(150, this);
		this.started = true;
		return this;
	},

	changeState: function(state, manual) {
		var stateOld = this.state;
		this.state = state;
		this.fireEvent('changed', [state, stateOld, manual]);
	},

	trace: function() {
		var state = this.getHash();
		if (state != this.state) this.changeState(state);
	},

	getHash: function() {
		var href = location.href, pos = href.indexOf('#') + 1;
		return (pos) ? href.substr(pos) : '';
	},

	setHash: function(state) {
		location.hash = '#' + state;
		return this;
	},

	setState: function(state) {
		if (this.state !== state) this.setHash(state).changeState(state, true);
		return this;
	},

	getState: function() {
		return this.state;
	}

});
/**
 * History.Routing
 *
 * @version		2.0
 *
 * @license		MIT License
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	2008 Author
 */

History.implement(new Options());

History.implement({

	options: {
		separator: ';'
	},

	routes: [],

	register: function(route) {
		if (this.routes.push(route) == 1) this.addEvent('changed', this.match);
	},

	unregister: function(route) {
		this.routes.remove(route);
	},

	match: function(state, previous, manual) {
		if (!manual) this.routes.each(Function.methodize('match', this.state));
	},

	generate: function() {
		return this.routes.map(Function.methodize('generate')).clean().join(this.options.separator);
	},

	update: function() {
		return this.setState(this.generate());
	}

});

History.Route = new Class({

	Implements: [Events, Options],

	/**
	 * pattern:	Regular expression that matches the string updated from onGenerate
	 * defaults:	Default values array, initially empty.
	 * flags:	When regexp is a String, this is the second argument for new RegExp.
	 * skipDefaults:default true; generate is not called when current values are similar to the default values.
	 * generate:	Should return the string for the state string, values are first argument
	 * onMatch:	Will be called when the regexp matches, with the new values as argument.
	 */
	options: {
		skipDefaults: true,
		defaults: [],
		pattern: null,
		flags: '',
		generate: function(values) {
			return values[0];
		},
		onMatch: $empty
	},

	initialize: function(options){
		this.setOptions(options);
		this.pattern = this.options.pattern || '(.*)';
		if ($type(this.pattern) == 'string') this.pattern = new RegExp(this.pattern, this.options.flags);
		this.values = this.defaults = this.options.defaults.slice();
		History.register(this);
		return this;
	},

	setValues: function(values) {
		if (this.values.toString() == values.toString()) return this;
		this.values = values;
		History.update();
		return this;
	},

	setValue: function(index, value) {
		if (this.values[index] == value) return this;
		this.values[index] = value;
		History.update();
		return this;
	},

	build: function(values) {
		var tmp = this.values.slice();
		this.values = values;
		var state = History.generate();
		this.values = tmp;
		return state;
	},

	destroy: function() {
		History.unregister(this);
	},

	generate: function() {
		if (this.options.skipDefaultMatch && (String(this.values) == String(this.defaults))) return null;
		return this.options.generate.call(this, this.values);
	},

	match: function(state) {
		var bits = state.match(this.pattern);
		var defaults = this.defaults;
		if (bits) {
			bits.splice(0, 1);
			for (var i = 0, j = bits.length; i < j; i++) bits[i] = $pick(bits[i], defaults[i] || null);
			if (String(bits) != String(defaults)) this.values = bits;
		} else {
			this.values = this.defaults.slice();
		}
		this.fireEvent('onMatch', [this.values, this.defaults]);
	}

});

Function.methodize = function(name) {
	var args = Array.slice(arguments, 1);
	return function(obj) {
		return obj[name].apply(obj, args);
	};
};



/**
 * Extends Array with 2 helpers: isSimilar(array) and complement(array)
 * 
 */
Array.extend({

	/**
	 * isSimilar - Returns true for similar arrays, type-insensitive
	 * 
	 * @example
	 *  [1].isSimilar(['1']) == true
	 *  [1, 2].isSimilar([1, false]) == false
	 *  
	 * @return	{Boolean}
	 * @param	{Object} Array
	 */
	isSimilar: function(array) {
		return (this.toString() == array.toString());
	},

	/**
	 * complement - Fills up empty array values from another array, length is the same
	 * 
	 * @example
	 *  [1, null].complement([3, 4]) == [1, 4]
	 *	[undefined, '1'].complement([2, 3, 4]) == [2, '1']

	 * @return	{Array} this
	 * @param	{Object} Array
	 */
	complement: function(array) {
		for (var i = 0, j = this.length; i < j; i++) this[i] = $pick(this[i], array[i] || null);
		return this;
	}
});

//get width of text element
function widthEl(el){
	if (document.layers){
	w=document.layers[el].clip.width;
	} else if (document.all && !document.getElementById){
	w=document.all[el].offsetWidth;
	} else if(document.getElementById){
	w=$(el).offsetWidth;
	}
	return w;
}

//get height of text element
function heightEl(el){
	if (document.layers){
	h=document.layers[el].clip.height;
	} else if (document.all && !document.getElementById){
	h=document.all[el].offsetHeight;
	} else if(document.getElementById){
	h=$(el).offsetHeight;
	}
	return h;
}

function textCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit)
	field.value = field.value.substring(0, maxlimit);
	else
	countfield.setHTML(maxlimit - field.value.length);
}


var MooPrompt = box = new Class({
	setOptions: function(options){
		this.options = {
			buttons: 1,
			width: 300, // Set width of the box
			height: 0, // Set height of the box (0 = sized to content)
			maxHeight: 500, // Maximum height of the dialog box
			vertical: 'middle', // top middle bottom
			horizontal: 'center', // left center right
			delay: 0, // Delay before closing (0=no delay)
			overlay: false, // Cover the page
			effect: 'grow'
				// 'grow' - Expands box from a middle point and fades in content
				// 'slide' - Slides in the box from the nearest side.
			// button1: 'Ok' --- supply this for setting button text
			// onButton1: function --- supply function for button action
		};
		$extend(this.options, options || {});
	},
	
	initialize: function(title, content, options){
		this.setOptions(options);
		this.title = title;
		this.text = content;
		if (document.all && document.compatMode) {
			/*this.iframe = new Element('iframe').setStyles({
				'position': 'absolute', 'top': 0, 'left': 0,
				'height': Window.getScrollHeight()+'px', 'width': Window.getScrollWidth()+'px'
			}).setProperties({
				'frameborder': 0, 'scrolling': 'no'
			}).injectInside(document.body);*/
		}
		if (this.options.overlay) {
			if ($('cbOverlay')) {
				this.overlay = $('cbOverlay');
			} else {
				this.overlay = new Element('div').setProperty('id', 'cbOverlay');
				this.overlay.addEvent('click', this.close.pass([this.options['onButton'+this.options.buttons]], this));
				this.overlay.setStyles({
					'position': 'absolute', 'top': 0, 'left': 0, 'width': '100%', 'visibility': 'hidden'
				}).injectInside(document.body);
			}
		}
		this.container = new Element('div').setProperty('class', 'cbContainer');
		this.container.setStyles({
			'position': 'absolute', 'visibility': 'hidden'
		}).injectInside(document.body);
		this.box = new Element('div').setProperty('class', 'cbBox');
		this.box.setStyles({
			'width': this.options.width+'px',
			'overflow': 'auto'
		}).injectInside(this.container);
		this.header = new Element('h3').setProperty('class', 'cbHeader').appendText(this.title).injectInside(this.box);
		this.content = new Element('div').setProperty('class', 'cbContent').injectInside(this.box);
		if ($type(content) == 'element' ) {content.injectInside(this.content);
		} else {this.content.appendText(this.text);}
		this.buttons = new Element('div').setProperty('class', 'cbButtons').injectInside(this.box);
		for (var i = 1; i <= this.options.buttons; i++) {
			if (typeof(this.options['button'+i]) == 'undefined') {
				this.options['button'+i] = 'Button';
			}
			if ($type(this.options['button'+i]) == 'element') {
				this['button'+i] = this.options['button'+i]
				this['button'+i].injectInside(this.buttons);
			} else {
				this['button'+i] = new Element('input').setProperties({type: 'button', value: this.options['button'+i]}).injectInside(this.buttons);
			}
			if ($type(this.options['button'+i]) != 'function') {
				this.options['button'+i] = function() {};
			}
			this['button'+i].onclick = this.close.pass([this.options['onButton'+i]], this);
		}
		this.boxHeight = (this.box.offsetHeight < this.options.maxHeight) ? this.box.offsetHeight : this.options.maxHeight;
		this.boxHeight = (this.options.height > 0) ? this.options.height : this.boxHeight;
		this.box.setStyle('display', 'none');
		this._position();
		this.eventPosition = this._position.bind(this);
		window.addEvent('scroll', this.eventPosition).addEvent('resize', this.eventPosition);
		if (this.options.overlay && this.overlay.getStyle('visibility') == 'hidden') {
			this.fx1 = new Fx.Style(this.overlay, 'opacity', {duration:500}).custom(0, .8);
		}
		if (this.options.effect == 'grow') {
			this.container.setStyle('top', (Window.getScrollTop()+(Window.getHeight()/2))+'px');
			var style = {}; style.height = 0; style.width = 0;
			if (this.options.horizontal != 'center') {
				style[this.options.horizontal] = (this.options.width/2)+'px';
			}
			if (this.options.vertical == 'top') {
				style[this.options.vertical] = (Window.getScrollTop()+(this.boxHeight/2))+'px';
			} else if (this.options.vertical == 'bottom') {
				style.top = (Window.getScrollTop()+Window.getHeight()-(this.boxHeight/2)-25)+'px';
			}
			this.container.setStyles(style);
			this.container.setStyle('visibility', '');
			this.fx2 = new Fx.Styles(this.container, {duration: 500});
			this.fx2.custom({
				'width': [0, this.options.width], 'margin-left': [0, -this.options.width/2], 'margin-right': [0, -this.options.width/2],
				'height': [0, this.boxHeight], 'margin-top': [0, -this.boxHeight/2], 'margin-bottom': [0, -this.boxHeight/2]
			}).chain(function() {
				this.box.setStyles({
					'visibility': 'hidden', 'display': '', 'height': this.boxHeight+'px'
				});
				new Fx.Style(this.box, 'opacity', {duration: 500}).custom(0, 1).chain(function() {
					this.box.setStyle('filter', '');
					if (this.options.delay > 0) {
						var fn = function () {
							this.close()
						}.bind(this).delay(this.options.delay);
					}
				}.bind(this));
			}.bind(this));
		} else {
			this.container.setStyles({
				'height': this.boxHeight, 'width': this.options.width,
				'left': '', 'visibility': 'hidden'
			});
			this.box.setStyles({
				'visibility': '', 'display': '', 'height': this.boxHeight+'px'
			});
			this.fx2 = new Fx.Styles(this.container, {duration: 500});
			var special = {};
			if (this.options.horizontal != 'center') {
				special[this.options.horizontal] = [-this.options.width, 0];
			} else {
				this.container.setStyles({
					'left': '50%', 'margin-left': (-this.options.width/2)+'px', 'margin-right': (-this.options.width/2)+'px'
				});
			}
			if (this.options.vertical == 'top') {
				special[this.options.vertical] = [Window.getScrollTop()-this.boxHeight, Window.getScrollTop()];
			} else if (this.options.vertical == 'bottom') {
				special.top = [Window.getScrollTop()+Window.getHeight(), Window.getScrollTop()+Window.getHeight()-this.boxHeight-25];
			} else {
				this.container.setStyles({
					'top': (Window.getScrollTop()+(Window.getHeight()/2))+'px', 'margin-top': (-this.boxHeight/2)+'px', 'margin-bottom': (-this.boxHeight/2)+'px'
				});
			}
			special.opacity = [0, 1];
			this.fx2.custom(special).chain(function() {
				if (this.options.delay > 0) {
					var fn = function () {
						this.close()
					}.bind(this).delay(this.options.delay);
				}
			}.bind(this));
		}
	},
	
	_position: function() {
		var wHeight = (Window.getScrollHeight() > Window.getHeight()) ? Window.getScrollHeight() : Window.getHeight();
		var lr = (this.options.effect == 'grow') ? this.options.width/2 : 0;
		var tb = (this.options.effect == 'grow') ? this.boxHeight/2 : 0;
		if (this.iframe) {
			this.iframe.setStyles({
				'height': Window.getScrollHeight()+'px',
				'width': Window.getScrollWidth()+'px'
			});
		}
		if (this.options.overlay) {
			this.overlay.setStyles({height: wHeight+'px'});
		}
		switch(this.options.vertical) {
			case 'top':
				this.container.setStyle('top', (Window.getScrollTop()+tb)+'px');
				break;
			case 'middle':
				this.container.setStyle('top', (Window.getScrollTop()+(Window.getHeight()/2))+'px');
				break;
			case 'bottom':
				this.container.setStyle('top', (Window.getScrollTop()+Window.getHeight()-this.boxHeight+tb-25)+'px');
				break;
		}
		if (this.options.horizontal == 'center') {
			this.container.setStyle('left', '50%');
		} else {
			this.container.setStyle(this.options.horizontal, lr+'px');
		}
	},
	
	close: function(fn) {
		for (var i = 1; i <= this.options.buttons; i++) {
			this['button'+i].onclick = null;
		}
		if ($type(this.fx1) == 'object') {
			this.fx1.clearTimer();
		}
		this.fx2.clearTimer();
		if (typeof(fn) == 'function') {fn();}
		if (this.options.overlay && this.overlay.getStyle('opacity') == 0.8) {
			new Fx.Style(this.overlay, 'opacity', {duration:250}).custom(0.8, 0);
		}
		new Fx.Style(this.container, 'opacity', {duration:250,
			onComplete: function() {
				window.removeEvent('scroll', this.eventPosition).removeEvent('resize', this.eventPosition);
				if (this.options.overlay) {
					this.overlay.remove();
				}
				this.container.remove();
				if (this.iframe) {
					this.iframe.remove();
				}
			}.bind(this)
		}).custom(1, 0);
	}
});
MooPrompt.implement(new Chain);

//add a new status entry for the user
function ajaxCreateStatus(id,text){
	jslink('/', {id:id,statusText:text}, 'User::set_status',addStatusEntry);
}

//add list entry to front end
function addStatusEntry(html){
	var returnString = Json.evaluate(html);
	if(!returnString['status'].contains('Sekunden speichern')){
		$('activity-updater').set('value','Tippe hier eine aktuelle Nachricht an alle');
	}
	var myListElement = new Element('li', {id: 'status_li_entry_'+returnString['id']});
	var ul = $('activity');
	var countEl = $('activity').getElements('li').length;
	if(countEl > 8){
		var endEl = $('activity').getLast();
		endEl.destroy();
	}
	var endEl = $('activity:last-child');
	myListElement.innerHTML = '<div><img src="/images/blank.gif" class="status" alt="Status"/><font style="color:#D33871;">(ich)</font> '+returnString['status']+'</div><div id="statusentrydate" class="date delstatus" onclick="ajaxStatusPrompt(\''+returnString['id']+'\',\'delete\')">gerade eben</div>';
	myListElement.inject(ul,'top');
}

// remove status entry from backend
function ajaxDeleteStatus(id){
	jslink('/', {id:id}, 'User::del_status',deleteStatusEntry);
}

function updateStatus(category){
	if($chk(category)){
		cat = category;
	}else{
		cat = '';
	}
	$('activityTitle').set('html','aktualisieren...');
	jslink('/DE/activity/',  {id:0,'category':cat}, 'User::ajax_get_history',updateStatusList);
	$('activityTitle').set('html','Pinnwand');
}

// remove list entry from front end
function deleteStatusEntry(html){
	var returnString = Json.evaluate(html);
	$('status_li_entry_'+returnString).fade(0).destroy();
}

//update the status entries
function updateStatusList(html){
	var ul = $('activity');
	if(html.contains('null')){
		html=html.split('null');
		ul.innerHTML = html[0];
	}else{
		ul.innerHTML = html;
	}
	
}


//Neuen Status Eintrag anlegen 
function ajaxStatusPrompt(id,mode) {
	switch(mode){
	case 'add':
		var userForm = new Element('form').setProperties({
			'action': '/',
			'method': 'post',
			'id': 'editForm'
		});
		userForm.innerHTML = 'Dein Status<br /><textarea name="statusText" id="statusText" /></textarea>';
		var boxHtml = new MooPrompt('Login prompt', userForm, {
			width: 400,
			height: 190,
			buttons: 2,
			button1: 'speichern',
			button2: 'abbrechen',
			overlay: true,
			onButton1: function() {
				ajaxCreateStatus(id,$('statusText').get('value'));
			}
		});
		$$('.cbHeader').setHTML("Teile mit, was du gerade tust!");
		break;
	case 'delete':
		var boxText = new Element('div').setProperties({
			'id': 'alertText',
			'style': 'margin:10px 0'
		});
		boxText.innerHTML = 'Möchtest du deine Statusmeldung löschen?';
		var boxHtml = new MooPrompt('Login prompt', boxText, {
			width: 400,
			height: 100,
			buttons: 2,
			button1: 'löschen',
			button2: 'abbrechen',
			overlay: true,
			onButton1: function() {
				ajaxDeleteStatus(id);
			}
		});
		$$('.cbHeader').setHTML("Bestätigung");		
		break;
	}
}

function toggleDisplay(thisElement,thisClass) {
	if($(thisElement)) {
		if($(thisElement).hasClass(thisClass))
			$(thisElement).removeClass(thisClass);
		else	$(thisElement).addClass(thisClass);
	}
}

//Bindings for all actions
window.addEvent('domready', function(){
	$$('.statuslink').addEvent('click', function(){
		linkdata = this.id.split('_');
		ajaxStatusPrompt(linkdata[1],'add');
	});
	if(($$('.activity-updater-button'))&&($('activity-updater'))){
		$$('.activity-updater-button').addEvent('click',function(){
			id = this.id.split('_');
			var statusValue = $('activity-updater').get('value')
			if(($('activity-updater').get('value') != "Tippe hier eine aktuelle Nachricht an alle") && (statusValue != '')){
				ajaxCreateStatus(id[1],$('activity-updater').get('value'));
			}
		});	
		
		$('activity-updater').addEvents({
			'blur':function(){
				if($('activity-updater').get('value') == ""){
					$('activity-updater').set('value','Tippe hier eine aktuelle Nachricht an alle');
				}
			},
			'mousedown':function(){
				if($('activity-updater').get('value') == "Tippe hier eine aktuelle Nachricht an alle"){
						$('activity-updater').set('value','');
					}
				}	
			});	
	}
	$$('.delstatus').addEvents({
	    'mouseenter': function(){
			linkdata = this.id.split('_');
			oldText = $(this).innerHTML;
			$(this).setHTML("<b>löschen?</b>");
	    },
	    'mouseleave': function(){
	    	$(this).setHTML(oldText);
	    },'click': function(){
	    	ajaxStatusPrompt(linkdata[1],'delete');
	    }
	});
	if($('activity')){
		var countBoxesOpacityStep = 1 /  $('activity').getElements('li').length;
		startOpacity = 1;
		var fade_in=1;
		var fade_out=.5;
		
		$('activity').getElements('li').each(function(el){
			// el.set('opacity',startOpacity);
			// startOpacity = startOpacity - countBoxesOpacityStep;
		});
		$('activity').getElements('li').addEvents({
			mouseenter: function(){
			initialOpacity = this.get('opacity');
			this.fade(fade_in);
			},
			mouseleave: function(){
				this.fade(initialOpacity);
			}
		});
	}
});
