///////////////////////////////////////////////////////
/// recombining ///////////////////////////////////////

///////////////////////////////////////////////////////
// /export/home/www/meinverein/meinverein-test/webroot/js/common.js/global.js

//global Vars
var MV_Overlay;
var filterSlide;
var filterIndi;

var domwalker;


///////////////////////////////////////////////////////
// album.js


//Class für Albumgalerie
/*
element =  image galerieWrapper
*/

var AlbumGalerie = new Class({
	initialize: function(element){

		this.element = element;
		this.Preview = this.element.getElement('.preview');
		this.showRoom = this.element.getElement('.show_room');

		//[REMOVESCRIPT] Breite angepasst, vorher 55, jetzt 56
		var width = 56;
		this.Slider = new hSlider(this.Preview, width, 10, 3);

		this.tmpImage;
		this.tmpHighlighted = false; //tmp aktives bild im reiter
		//for calc
		this.middle = (this.showRoom.getSize().y) / 2;

		//albumInfo
		this.media_info = this.element.getElement('.media_info');
		this.MediaDetails = this.element.getElement('#MediaDetails');
		this.allComments = this.element.getElement('#allComments');
		this.links 			= $('links');
		this.abuse 			= this.element.getElement('#abuse');
		this.linksDropdown	= new DropDownList({'type': 'link'});
		//for toggling
		this.ToggleItemOne = this.MediaDetails.getParent('.toggle_item');
		this.ToggleItemTwo = this.allComments.getParent('.toggle_item');
		if(this.abuse != null)
			this.ToggleItemThree = this.abuse.getParent('.toggle_item');
		else
			this.ToggleItemThree = null;
		if(this.ToggleItemOne.hasClass('closed')){this.ToggleItemOne.toggleClass('closed');}
		if(!this.ToggleItemTwo.hasClass('closed')){this.ToggleItemTwo.toggleClass('closed');}
		if(this.ToggleItemThree != null && !this.ToggleItemThree.hasClass('closed')){this.ToggleItemThree.toggleClass('closed');}

		//form
		this.CommentForm = this.ToggleItemTwo.getElement('form');
		this.createSubmitOnComment();

		//this Request für bild info/comments
		this.Loader = new Element('dd', {'class' : 'loading_comment'});
		this.RequestInfo = new Request({
			onSuccess: function(result){this.dumpImageInfo(result);$('albumOverlayMediaId').set('value',this.RequestInfo.mediaId);}.bind(this)
		});

		//erstes Bild laden
		var startImageType = this.element.getElement('.start_image_type');
		var startImage = this.element.getElement('.start_image');
		var startImageSrc = this.element.getElement('.start_image_src');

		if (startImageType && startImageType.get('title') == 'video') {

			//alert('start video');
			var startImageWidth = this.element.getElement('.start_image_width');
			var startImageHeight = this.element.getElement('.start_image_height');
			var startImageDuration = this.element.getElement('.start_image_duration');

			this.loadVideo(startImageSrc.get('title'), startImage.get('title'), startImageWidth.get('title'), startImageHeight.get('title'), startImageDuration.get('title'), false);
		}
		else {
			//alert('start image');
			this.loadImage(startImageSrc.get('title'), startImage.get('title'), false);
		}

		//togglefunction
		this.creatEventOnToggler();
	},
	createTmpLoader: function()
	{
		this.tmpLoader = new Element('span', {'class' : 'galerie_loader'});
	},

	loadImage : function(dir, imageId, elem){
		this.RequestInfo.cancel();
		//imageinfo update
		this.MediaDetails.set('html', '');
		var tmpLoader1 = this.Loader.clone().inject(this.MediaDetails);
		this.allComments.getElement('dl').set('html', '');
		var tmpLoader2 = this.Loader.clone().inject(this.allComments.getElement('dl'));
		//show pic
		//this.showRoom.set('html', '');
		this.linksDropdown.removeBoxes();
		this.clearShowroom();
		this.createTmpLoader();
		this.tmpLoader.inject(this.showRoom);
		this.tmpImage = new Asset.image(dir, {'id': 'MV_Image', onload: function(){this.dumpImage();}.bind(this)});
		this.RequestInfo.options.url = '/overlay/load_media_info/' + imageId+'/'+$('actAlbumId').getProperty('value');
		if($('actMediaId'))
			$('actMediaId').setProperty('value', imageId);
		this.RequestInfo.mediaId = imageId;
		this.RequestInfo.send();
		this.currentMediaId = imageId;

		if(!Browser.Engine.trident4){
			this.changeHighlighted(elem);
		}

	},

	loadVideo : function(dir, vidId, width, height, duration, elem){
		//videoinfo update
		this.MediaDetails.set('html', '');
		var tmpLoader1 = this.Loader.clone().inject(this.MediaDetails);
		this.allComments.getElement('dl').set('html', '');
		var tmpLoader2 = this.Loader.clone().inject(this.allComments.getElement('dl'));

		this.RequestInfo.options.url = '/overlay/load_media_info/' + vidId+'/'+$('actAlbumId').getProperty('value');
		this.RequestInfo.mediaId = vidId;
		this.RequestInfo.send();
		//show vid
		this.linksDropdown.removeBoxes();
		this.showRoom.set('html', '<div id="MV_Player"></div>');
		startVideoPlayer(dir, width, height, duration);

		if(!Browser.Engine.trident4){
			this.changeHighlighted(elem);
		}
	},

	dumpImage : function(){
		//this.showRoom.set('html', '');
		this.clearShowroom();
		this.tmpImage.setStyle('opacity', '0');
		if(this.tmpImage.get('height') < 471){this.tmpImage.setStyle('top', this.middle - (this.tmpImage.get('height')/2));}
		this.tmpImage.inject(this.showRoom);
		this.tmpImage.fade(1);
	},

	dumpImageInfo : function(response){
		var tmpWrapper = new Element('div', {'html': response});
		this.ToggleItemOne.getElement('.headline').set('html', tmpWrapper.getElement('.details').get('title') + '<em class="toggle_indicator"></em>');
		this.creatEventOnToggler();
		this.MediaDetails.set('html', tmpWrapper.getElement('.details').get('html'));
		if(this.MediaDetails.getElement('.rating')){ var tmprating = new Rating(this.MediaDetails.getElement('.rating'));}
		this.allComments.getElement('dl').set('html', tmpWrapper.getElement('.comments').get('html'));
		if(this.links)
			this.links.getElement('.removalList').set('html', tmpWrapper.getElement('.links').get('html'));

		//abuse
		if(this.ToggleItemThree) {
			this.ToggleItemThree.getElement('.toggle_content').set('html', tmpWrapper.getElement('.abuses').get('html'));
		}

		this.linksDropdown.createLoadedBoxes();
	},
	clearShowroom: function()
	{

		//@NOTE [SU] Added to destroy Flash player properly
		//this.showRoom.empty();

		//@NOTE [SU] Das kann doch dann weg oder?


		if($('MV_Player'))
			$('MV_Player').destroy();
		if($('videoplayer'))
			$('videoplayer').destroy();
		if($('MV_Image'))
			$('MV_Image').destroy();

		this.showRoom.getElements('span[class^=start]').each(function(item, index)
		{
			item.destroy();
		});

		if(this.tmpLoader)
			this.tmpLoader.destroy();


	},
	creatEventOnToggler : function() {
		this.media_info.getElements('.toggle_indicator').each(function(elem){
			elem.removeEvents('click');
			elem.addEvent('click', function(e){
				e.stop();
				var thisToggler = elem.getParent('.toggle_item');
				var togglerStatus = false;
				if(!thisToggler.hasClass('closed')){
					var togglerStatus = true;
				}

				var tmpLength = thisToggler.getParent().getElements('li[class^=toggle_item]').each(function(item, index) {
					item.addClass('closed');
				});

				if(togglerStatus == false)
					thisToggler.removeClass('closed');

				/**
				 * Micha: Entfernt da mehr als 2 Punkte rechts möglich sein müssen
				 */
				/*
				if(!thisToggler.hasClass('closed')){
					thisToggler.toggleClass('closed');
				}
				else{
					var tmpLength = thisToggler.getParent().getElements('.closed').length;
					console.log(tmpLength);
					if(tmpLength == 2){
					this.ToggleItemOne.toggleClass('closed');
					this.ToggleItemTwo.toggleClass('closed');
						if(this.ToggleItemThree != null)
							this.ToggleItemThree.toggleClass('closed');
					}
					else if (tmpLength == 1)
					{
						this.ToggleItemOne.toggleClass('closed');
						this.ToggleItemTwo.toggleClass('closed');
				}
					else
					{
						thisToggler.toggleClass('closed');
					}
				}*/
				return false;
			}.bind(this));
		}.bind(this));
	},

	createSubmitOnComment : function() {
		if (this.CommentForm) {
			this.CommentForm.addEvent('submit', function(e) {
				e.stop();
				this.FormLoader = this.Loader.clone().inject(this.allComments.getElement('dl'), 'top');
				this.CommentForm.set('send', {
					onComplete: function(response) {
						this.FormLoader.destroy();

						//destroy "no-comment" if available
						if (this.allComments.getElement('.noComment')) {
							this.allComments.getElement('dl').empty();
						}

						var tmpWrapper = new Element('div', {'html' : response});
						var dd = new Element('dd', {'html' : tmpWrapper.getElement('dd').get('html')}).inject(this.allComments.getElement('dl'), 'top');
						var dt = new Element('dt', {'html' : tmpWrapper.getElement('dt').get('html')}).inject(this.allComments.getElement('dl'), 'top');
					}.bind(this)
				});
				this.CommentForm.send();
				this.CommentForm.getElement('textarea').set('value', '');
				return false;
			}.bind(this));
		}
	},

	changeHighlighted : function(elem) {
		if(elem){
			elem = elem.getParent('.media_wrapper');

			//clicked elem highglighten/altes zurücksetzten
			if(this.tmpHighlighted){
				this.tmpHighlighted.setStyle('margin-top', '0');
				this.tmpMW_Overlay.destroy();
			}
			this.tmpHighlighted = elem;
			elem.setStyle('margin-top', '2px');
			this.tmpMW_Overlay = generateItems(elem.getElement('a'), 'span', new Array('mw_overlay'), 'bottom');
			this.tmpMW_Overlay.setStyles({'color': 'black', 'opacity':'0.4', 'display': 'block'});
		}
	}
});



///////////////////////////////////////////////////////
// countdown.js


//Class für countdown
/*
element =  <ul class="countdown">
*/
var Countdown = new Class({

	initialize: function(element){
		this.element = element;
		var date = this.element.title.split('-');
			var year = date[0];
			var month = date[1];
			var day = date[2];
			var hour = date[3];
			var minute = date[4];
			var second = date[5];

		this.deathTime = new Date(year,month-1,day,hour,minute,second);
		this.element.removeProperty('title');

		//Container outout
			this.days = this.element.getElement('.cd-days');
			this.weeks = this.element.getElement('.cd-weeks');
			this.months = this.element.getElement('.cd-months');
			this.hours = this.element.getElement('.cd-hours');
			this.minutes = this.element.getElement('.cd-minutes');
			this.seconds = this.element.getElement('.cd-seconds');

		this.period = this.setTimeLeft.periodical(1000, this);
	},

	setTimeLeft : function(){
		var actualTime = new Date();


		// calc countdown
		if(actualTime < this.deathTime)  {

			var y=0, mon=0, w=0, d=0, h=0, min=0, sec=0;

			/*
				// calc Years
				while(actualTime < this.deathTime) {
				y++;
				actualTime.setFullYear(actualTime.getFullYear()+1);
				}
				actualTime.setFullYear(actualTime.getFullYear()-1);
				y--;
			*/



			/*
			while(actualTime < this.deathTime) {
				mon++;
				actualTime.setMonth(actualTime.getMonth()  );
			}
			actualTime.setMonth(actualTime.getMonth() - 1 );
			mon--;
			*/

			//calc months
			/*
			while(actualTime.getTime()+(52*7*24*60*60*1000) < this.deathTime.getTime()) {
			mon++;
			actualTime.setTime(actualTime.getTime()+(52*7*24*60*60*1000));
			}
			*/

			//calc weeks
			while(actualTime.getTime()+(7*24*60*60*1000) < this.deathTime.getTime()) {
			w++;
			actualTime.setTime(actualTime.getTime()+(7*24*60*60*1000));
			}
			while(w>=4) {
			 mon++;
			 w=w-4;
			}



			// calc days
			while(actualTime.getTime()+(24*60*60*1000) < this.deathTime.getTime()) {
			d++;
			actualTime.setTime(actualTime.getTime()+(24*60*60*1000));
			}


			// calc hours
			h = Math.floor((this.deathTime - actualTime)/(60*60*1000));

			actualTime.setTime(actualTime.getTime() + h*60*60*1000);

			// calc min
			min = Math.floor((this.deathTime - actualTime)/(60*1000));
			actualTime.setTime(actualTime.getTime() + min*60*1000);

			// calc seconds
			sec = Math.floor((this.deathTime - actualTime)/1000);

		 //ab in die Container
		this.days.set('html', d);
		this.weeks.set('html', w);
		this.months.set('html', mon);
		this.hours.set('html', h);
		this.minutes.set('html', min);
		this.seconds.set('html', sec);

		}
		// set null
		else{
			this.days.set('html', '0');
			this.weeks.set('html', '0');
			this.months.set('html', '0');
			this.hours.set('html', '0');
			this.minutes.set('html', '0');
			this.seconds.set('html', '0');

			$clear(this.period);
		}

	}
});



///////////////////////////////////////////////////////
// domwalker.js



var Domwalker = new Class({

	parentNodes : new Array(),
	currentDepth : 0,
	maxDepth : 10000,
	currentStep : 0,
	currentIdentifier : '',

	functions : new Array(),

	init : function() {

		this.parentNodes = new Array();
		this.currentDepth = 0;
		this.currentStep = 0;

		// console.log('Domwalker initialized.');
	},

	log_ie6 : function(text, indent) {
		if (!this.pre) {
			this.pre = new Element('pre', {
						'style' : 'background:white;border: 1px solid red;'
					});
			this.pre.inject(document.body);
		}
		ind = '';
		for (var i = 0; i < indent; i++)
			ind += ' ';

		var txt = ind + text + "\r\n";
		this.pre.appendChild(document.createTextNode(txt));
	},

	hurry : function(topElement) {

		this.init();

		this.walk(topElement);
		// console.log('Domwalker total steps: ' + this.currentStep)

	},

	walk : function(startElement) {

		this.currentStep++;
		this.currentDepth++;

		// Die Funktion get ist im IE7 bei mindestens einem Objekt
		// komischerweise nicht definiert.
		// Keiner weiß warum.
		if (typeof(startElement.get) != 'function')
			return;

		var id = startElement.get('id');
		if (this.currentDepth <= this.maxDepth && id != 'topBanner'
				&& id != 'Skyscraper') {

			// console.log('step: ' + this.currentStep + ' depth: ' +
			// this.currentDepth + ' tag: ' + startElement.get('tag') + ' (' +
			// this.renderParentNodes()) + ')';
			var classes = startElement.get('class');
			if (classes.length > 0) {
				classes.split(" ").each(function(element) {
							this.currentIdentifier = 'class:' + element;

							if (this.functions[this.currentIdentifier]) {

								this.functions[this.currentIdentifier](startElement);
							}

						}.bind(this));
			}

			this.currentIdentifier = 'tag:' + startElement.get('tag');
			if (this.functions[this.currentIdentifier]) {

				this.functions[this.currentIdentifier](startElement);
			}

			if (id) {
				this.currentIdentifier = 'id:' + id;
				if (this.functions[this.currentIdentifier]) {

					this.functions[this.currentIdentifier](startElement);
				}
			}

			var children = startElement.getChildren();
			this.parentNodes.push(startElement);
			children.each(function(element) {
						this.walk(element);
					}.bind(this));

			this.parentNodes.pop();
		}

		this.currentDepth--;
	},

	renderParentNodes : function() {

		var out = '';
		this.parentNodes.each(function(parent) {

					out += parent.get('tag') + ' ';
				});
		return out;
	},

	parentHasProperty : function(attribute, value) {

		return this.parentNodes.some(function(element) {
					return (element.get(attribute) && element.get(attribute)
							.contains(value));
				});
	}

});

domwalker = new Domwalker();

/* Element Functions */

// shadow under box_header
/*
 * domwalker.functions['class:box_content'] = function (elem) {
 * if(!Browser.Engine.trident4){
 * 
 * if(!this.parentHasProperty('class', 'static')) generateItems(elem, 'span',
 * new Array('shadow'), 'bottom'); } }.bind(domwalker);
 */

// media_wrapper (general)
domwalker.functions['class:media_wrapper'] = function(elem) {

	/*
	 * if(!Browser.Engine.trident4){ var link = elem.getElement('a'); if(link) {
	 * generateItems(link, 'span', new Array('inner_shadow'), 'bottom');
	 * generateItems(elem, 'span', new Array('top', 'top_left', 'top_right',
	 * 'right', 'bottom_left', 'bottom_right', 'bottom', 'left'), 'bottom'); }
	 * else{ generateItems(elem, 'span', new Array('top', 'top_left',
	 * 'top_right', 'right', 'bottom_left', 'bottom_right', 'bottom', 'left',
	 * 'inner_shadow'), 'bottom'); } }
	 * 
	 * //set hover events if(this.parentHasProperty('class', 'list_entry') &&
	 * (this.parentHasProperty('class', 'vcard') ||
	 * this.parentHasProperty('class', 'mcard') ) ){
	 * if(elem.getElement('.selected') || elem.getElement('.play')){ var dir;
	 * if(elem.getElement('a')){dir = elem.getElement('a');} else{dir = elem;}
	 * var tmpOver = generateItems(dir, 'span', new Array('mw_overlay'),
	 * 'bottom'); tmpOver.setStyles({'display' : 'block', 'opacity' : '0.4'}); }
	 * if(!elem.getParent('.expanded_card') && !elem.getParent('.category_card') ){
	 * if(elem.getElement('.play')){var tmp = new Element('span', { 'class' :
	 * 'mw_overlay'}).inject(elem);} elem.addEvent('mouseover', mW_MouseOver);
	 * elem.addEvent('mouseout', mW_MouseOut);
	 * if(this.parentHasProperty('class', 'info_list')){elem.removeEvents();} } }
	 */

	// events for overlays
	// album
	if (this.parentHasProperty('class', 'album')
			&& this.parentHasProperty('class', 'mcard')) {
		var a = elem.getElement('a');
		if (a)
			ME_albumGalerie(a);
	}
	// video
	if (this.parentHasProperty('class', 'video')
			&& this.parentHasProperty('class', 'mcard')) {
		var a = elem.getElement('a');
		if (a)
			ME_openVideo(a);
	}
	// image
	if (this.parentHasProperty('class', 'image')
			&& this.parentHasProperty('class', 'mcard')) {
		var a = elem.getElement('a');
		if (a)
			ME_openImage(a);
	}

}.bind(domwalker);

// Schatten für overlay right
/*
 * domwalker.functions['class:media_info'] = function (elem) {
 * if(!Browser.Engine.trident4){ if(elem.get('tag').test('div'))
 * generateItems(elem, 'span', new Array('shadow'), 'bottom'); }
 * }.bind(domwalker);
 */

// span für vcard/mcard in card_list
var CardSpans = function(elem, setHeight, type) {
	if (!Browser.Engine.trident4) {
		generateItems(elem, 'span', new Array('right cardr', 'left cardl'),
				'bottom');
	}
	if (setHeight) {
		if (!elem.getParent('.card_list').hasClass('small_cards')) {
			var height = elem.getSize().y;
			elem.getElements('.cardr').extend(elem.getElements('.cardl')).each(
					function(elem) {

						elem.setStyle('height', height);
					});
		}
	}
}

/*
 * domwalker.functions['class:vcard'] = function (elem) {
 * if(Browser.Engine.trident && !Browser.Engine.trident4){
 * if(elem.getParent('.card_list')) CardSpans(elem, true, 'vcard') }else{
 * if(this.parentHasProperty('class', 'card_list')) CardSpans(elem, false,
 * 'vcard') } }.bind(domwalker);
 */

/*
 * domwalker.functions['class:mcard'] = function (elem) {
 * if(Browser.Engine.trident && !Browser.Engine.trident4){
 * if(elem.getParent('.card_list')) CardSpans(elem, true, 'mcard') }else{
 * if(this.parentHasProperty('class', 'card_list')) CardSpans(elem, false,
 * 'mcard') } }.bind(domwalker);
 */

// for the infoboxes on start
domwalker.functions['class:drag_selection'] = function(elem) {
	/*
	 * if(!Browser.Engine.trident4){ elem.getElements('li').each(function(elem){
	 * generateItems(elem,'span', new Array('top_left ds_tl', 'top_right ds_tr',
	 * 'bottom_left ds_bl', 'bottom_right ds_br'), 'bottom'); }); }
	 */

	var strong = elem.getElement('strong');
	if (strong) {
		var tmp = generateItems(strong, 'span', new Array('toggle_indicator'),
				'bottom')
		strong.addEvent('click', function(e) {
					e.stop();
					this.getParent('.drag_selection')
							.toggleClass('open_drag_selection');
				});
	}
}.bind(domwalker);

// spans in box
/*
 * domwalker.functions['class:box'] = function (elem) {
 * if(!Browser.Engine.trident4){ //generall generateItems(elem, 'span', new
 * Array('bottom_left box_bl', 'bottom_right box_br'), 'bottom');
 * 
 * //is static if(this.parentHasProperty('class', 'static')){ //falls box im
 * overlay (h�he f�r die seitlichen spans errechnen)
 * if(this.parentHasProperty('id', 'Overlay')){ generateItems(elem, 'span', new
 * Array('right box_r', 'left box_l', 'top box_t', 'bottom box_b'), 'bottom');
 * var tmpHeight = $('OverlayContent').getSize().y; //console.log(tmpHeight);
 * $$(elem.getElement('.box_r'),
 * elem.getElement('.box_l')).each(function(elem){elem.setStyle('height',tmpHeight -
 * 2)}); } else{ generateItems(elem, 'span', new Array('top_left box_tl',
 * 'top_right box_tr'), 'bottom'); } } } }.bind(domwalker);
 */

// spans f�r formelemente
var InputElements = function(elem) {
	if (!Browser.Engine.trident4) {
		// nur, wenn kein wrapper vorhanden
		if (!this.parentHasProperty('class', 'buttonWrapper')) {
			// zusatz class herausbekommen
			if (elem.hasClass('error')) {
				var tmpClassExtend = ' error';
			} else {
				var tmpClassExtend = ''
			}
			if (elem.hasClass('atrophied')) {
				tmpClassExtend += ' atrophied';
			}
			if (elem.hasClass('button')) {
				var tmpWrapperClass = 'buttonWrapper'
						+ elem.className.replace('button', '');
			} else {
				var tmpWrapperClass = 'textInputWrapper';
			}

			// wrapper + spans erzeugen
			var tmpWrapper = new Element('span', {
						'class' : tmpWrapperClass + tmpClassExtend + ' '
								+ elem.get('tag')
					});
			tmpWrapper.wraps(elem);
			generateItems(tmpWrapper, 'span', new Array('top', 'top_left',
							'top_right', 'right', 'bottom_left',
							'bottom_right', 'bottom', 'left'), 'bottom');
		}
	}
}.bind(domwalker);

/*
 * domwalker.functions['class:button'] = function (elem) { InputElements(elem);
 * }.bind(domwalker);
 */

/*
 * domwalker.functions['class:fText'] = function (elem) { InputElements(elem);
 * if(!Browser.Engine.trident4){ if (!elem.get('readonly')) {
 * elem.addEvent('focus', inputFocusBlur); elem.addEvent('blur',
 * inputFocusBlur); } if(elem.hasClass('error')){ elem.addEvent('change',
 * inputFocusBlur_error); } } }.bind(domwalker);
 */

domwalker.functions['class:fText'] = function(elem) {
	InputElements(elem);

	if (this.parentHasProperty('class', 'bdSearch')) {
		elem.addEvents({
					'focus' : textBdFocus,
					'blur' : textBdBlur
				});
	}
}.bind(domwalker);

domwalker.functions['class:fTextarea'] = function(elem) {
	InputElements(elem);
	if (!Browser.Engine.trident4) {
		if (!elem.get('readonly')) {
			elem.addEvent('focus', inputFocusBlur);
			elem.addEvent('blur', inputFocusBlur);
		}
		if (elem.hasClass('error')) {
			elem.addEvent('change', inputFocusBlur_error);
		}
	}

	if (this.parentHasProperty('class', 'board')) {
		elem.addEvents({
					'focus' : textareaFocus,
					'blur' : textareaBlur
				});
	}
}.bind(domwalker);

/*
 * domwalker.functions['class:fElement'] = function (elem) {
 * if(this.parentHasProperty('class', 'formContent')) InputElements(elem);
 * }.bind(domwalker);
 */

// ratings generieren
domwalker.functions['class:rating'] = function(elem) {
	var tmprating = new Rating(elem);
}.bind(domwalker);

// Dropdowns
domwalker.functions['class:dropdown'] = function(elem) {
	if (!elem.get('class').contains('IE6dd'))
		var tmpDd = new Dropdown(elem);
}.bind(domwalker);

// toggleindicators/closeindicators
domwalker.functions['class:options_inner'] = function(elem) {
	if ((this.parentHasProperty('class', 'box_header') && this
			.parentHasProperty('id', 'IM'))
			|| (this.parentHasProperty('class', 'box_can_toggle')))
		generateIndicators(elem, 'span', 'toggle_indicator', 'top');
}.bind(domwalker);

domwalker.functions['class:selected'] = function(elem) {
	if (elem.get('tag').test('span') && this.parentHasProperty('id', 'Filter'))
		generateIndicators(elem, 'span', 'toggle_indicator', 'top');
}.bind(domwalker);

// headline
domwalker.functions['class:headline'] = function(elem) {
	if (this.parentHasProperty('class', 'toggle_item'))
		generateIndicators(elem, 'em', 'toggle_indicator', 'bottom');
}.bind(domwalker);

// ajax pagination
domwalker.functions['class:pagination'] = function(elem) {

	elem.getElements('a[rel=ajax]').each(function(elem) {
				// if pagination is inside a box, update the .box_wrapper div
				elem.set('href', elem.get('title'));
				elem.removeProperty('title');
				elem.addEvent('click', ajaxPagination);
			});

}.bind(domwalker);

domwalker.functions['class:acceptInvitation'] = function(elem) {
	elem.getElements('a[rel=ajax]').each(function(element) {
				element.set('assocId', elem.get('assocId'));
				element.set('userId', elem.get('userId'));
				element.addEvent('click', function() {
							acceptInvitation(element);
							return false;
						});
			})
}.bind(domwalker);

// vorschlag event auf ajaxfTexte legen
domwalker.functions['class:ajaxfText'] = function(elem) {
	var fTextProposal = new Suggestion(elem);
}.bind(domwalker);

// hover events auf auswahllisten mit l�schfunktion, beispiel: interessen
// entfernen etc.
domwalker.functions['class:removalList'] = function(elem) {
	elem.getElements('li label').each(function(elem) {
				elem.addEvent('mouseover', function() {
							this.getParent().toggleClass('hover');
						});
				elem.addEvent('mouseout', function() {
							this.getParent().toggleClass('hover');
						});
				elem.addEvent('click', function() {
							if (this.getParent().getParent().getChildren().length > 1) {
								this.getParent().destroy();
							}
						});
			});
}.bind(domwalker);

// header scroller
domwalker.functions['id:ForeignProfiles'] = function(elem) {
	var elem = elem.getElement('.content');
	if (elem.getElements('li').length > 3) {
		var foreignSlider = new hSlider(elem, 90, 3, 5);
	}
}.bind(domwalker);

// alle Countdowns starten
domwalker.functions['class:countdown'] = function(elem) {
	var countdown = new Countdown(elem);
}.bind(domwalker);

// colorthemeradio
domwalker.functions['id:colorThemeRadioSelection'] = function(elem) {
	elem.getElements('li').each(function(item, index) {

		if (item.getElement('input').checked)
			item.getElement('img').setProperty(
					'src',
					'/img/colorThemeRadio/'
							+ item.getElement('img').getProperty('alt')
							+ '_selected.gif');

		item.addEvents({
			'mouseover' : function() {
				if (!item.getElement('input').checked)
					item.getElement('img').setProperty(
							'src',
							'/img/colorThemeRadio/'
									+ item.getElement('img').getProperty('alt')
									+ '_over.gif');
			},
			'mouseout' : function() {
				if (!item.getElement('input').checked)
					item.getElement('img').setProperty(
							'src',
							'/img/colorThemeRadio/'
									+ item.getElement('img').getProperty('alt')
									+ '_out.gif');
			},
			'click' : function() {
				item.getElement('input').setProperty('checked', 'checked');
				item
						.getParent('ul')
						.getElements('img[src$=_selected.gif]')
						.setProperty(
								'src',
								'/img/colorThemeRadio/'
										+ item
												.getParent('ul')
												.getElements('img[src$=_selected.gif]')
												.getProperty('alt')
										+ '_out.gif');
				item.getElement('img').setProperty(
						'src',
						'/img/colorThemeRadio/'
								+ item.getElement('img').getProperty('alt')
								+ '_selected.gif');
			}
		});
	});
}.bind(domwalker);

// pinboard events
domwalker.functions['class:pinboard'] = function(elem) {
	var fCancel = elem.getElement('input.fCancel')
	if (fCancel) {
		fCancel.addEvent('click', function() {
					var fieldset = this.getParent('fieldset');
					if (fieldset)
						fieldset.addClass('closed');
				}.bind(fCancel));
	}

	elem.getElements('.delete_entry a').each(function(link) {
				link.addEvent('click', function(e) {
							e.stop();
							new MessageBox('/overlay/question_box/100', {
										onYes : function() {
											window.location.href = link.href;
										}
									})
							return false;
						});
			});
}.bind(domwalker);

domwalker.functions['class:delete_entry'] = function(elem) {

	elem.getElement('a').addEvent('click', function(e) {
				e.stop();
				new MessageBox('/overlay/question_box/100', {
							onYes : function() {
								window.location.href = link.href;
							}
						});
				return false;
			});

}.bind(domwalker);

// autoclear
domwalker.functions['class:autoclear'] = function(elem) {
	elem.autoclearText = elem.get('title');
	elem.removeProperty('title');
	elem.addEvent('focus', autoclearFocus);
	elem.addEvent('blur', autoclearBlur);
}.bind(domwalker);

// Portrait upload
domwalker.functions['id:userPortraitUpload'] = function(portraitUpload) {

	var submitUrl = '';
	var cancelUrl = '';

	if (portraitUpload.hasClass('assoc_logo')) {
		var assocId = portraitUpload.getElement('.mcard').get('title');
		portraitUpload.getElement('.mcard').removeProperty('title');
		submitUrl = '/associations/set_logo/' + assocId + '/';
		cancelUrl = '/associations/restore_logo/' + assocId + '/';
	} else if (portraitUpload.hasClass('assoc_photo')) {
		var assocId = portraitUpload.getElement('.mcard').get('title');
		portraitUpload.getElement('.mcard').removeProperty('title');
		submitUrl = '/association_settings/set_photo/' + assocId + '/';
		cancelUrl = '/association_settings/restore_photo/' + assocId + '/';
	} else {
		submitUrl = '/profile/set_profile_image/';
		cancelUrl = '/profile/restore_profile_image/';
	}

	var portraitUploader = new ProfileImageUpload({
		'submitUrl' : submitUrl,
		'cancelUrl' : cancelUrl,
		url : $('userPortraitUpload').action,
		fieldName : 'Media/upload',
		path : '/flash/Swiff.Uploader.swf',
		limitSize : 60 * 1024 * 1024, // 60Mb @TODO:[SU] What maximum filesize
		// to use?
		limitFiles : 1,
		typeFilter : {
			'Images (*.jpg, *.jpeg, *.gif, *.png)' : '*.jpg; *.jpeg; *.gif; *.png;'
		},
		// The changed parts!
		debug : true, // enable logs, uses console.log
		target : 'userPortraitSelectImage' // the element for the overlay
			// (Flash 10 only)
	});

	var cancelButton = $('userPortraitUploadCancel');
	if (cancelButton) {
		cancelButton.addEvent('click', function(e) {
					e.stop();
					portraitUploader.cancel();
					return false;
				});
	}

	var submitButton = $('userPortraitUploadSubmit');
	if (submitButton) {
		submitButton.addEvent('click', function(e) {
					e.stop();
					portraitUploader.submit();
					return false;
				});
	}

	$('userPortraitSelectImage').addEvent('click', function(e) {
				e.stop();
				// portraitUploader.browse();
				return false;
			});

	$('userPortraitUploadImage').addEvent('click', function(e) {
				e.stop();
				portraitUploader.upload();
				return false;
			});
}.bind(domwalker);

// forum -> autodelete startup text im form
domwalker.functions['id:postTitle'] = function(elem) {
	if (this.parentHasProperty('class', 'board')) {
		elem.addEvent('blur', function() {
					if (this.value == "")
						this.value = 'Dein Titel';
				});
		elem.addEvent('focus', function() {
					if (this.value == "Dein Titel")
						this.value = '';
				});
	}
}.bind(domwalker);

domwalker.functions['id:postText'] = function(elem) {
	if (this.parentHasProperty('class', 'board')) {
		elem.removeEvents('blur');
		elem.addEvent('blur', function() {
					this.getParent().toggleClass('focus');
					if (this.get('value') == "")
						this.set('value', 'Dein Text');
				});
		elem.addEvent('focus', function() {
					if (this.get('value') == "Dein Text")
						this.set('value', '');
				});
	}
}.bind(domwalker);

domwalker.functions['id:threadTitle'] = function(elem) {
	if (this.parentHasProperty('class', 'forum')) {
		elem.addEvent('blur', function() {
					if (this.value == "")
						this.value = 'Dein Titel';
				});
		elem.addEvent('focus', function() {
					if (this.value == "Dein Titel")
						this.value = '';
				});
	}
}.bind(domwalker);

domwalker.functions['id:threadText'] = function(elem) {
	if (this.parentHasProperty('class', 'forum')) {
		elem.removeEvents('blur');
		elem.addEvent('blur', function() {
					this.getParent().toggleClass('focus');
					if (this.get('value') == "")
						this.set('value', 'Dein Text');
				});
		elem.addEvent('focus', function() {
					if (this.get('value') == "Dein Text")
						this.set('value', '');
				});
	}
}.bind(domwalker);

// media events

// ONCLICK events im element erzeugen: nachfolgendes DEPRECATED

function ME_albumGalerie(elem) {
	var mcard = elem.getParent('.mcard');
	if (!mcard.albumId) {
		mcard.albumId = mcard.get('title');
		if (!Browser.Engine.trident4)
			mcard.removeProperty('title');
	}
	elem.albumId = mcard.albumId;
	elem.removeEvents('click');
	elem.addEvent('click', openAlbum);

}

function ME_openImage(elem) {
	var mcard = elem.getParent('.mcard');
	if (!mcard.mediaId) {
		mcard.mediaId = mcard.get('title');
		if (!Browser.Engine.trident4)
			mcard.removeProperty('title');
	}
	elem.mediaId = mcard.mediaId;
	elem.removeEvents('click');
	elem.addEvent('click', openMedia);
}

function ME_openVideo(elem) {
	var mcard = elem.getParent('.mcard .video');
	if (!mcard.mediaId) {
		mcard.mediaId = mcard.get('title');
		if (!Browser.Engine.trident4)
			mcard.removeProperty('title');
	}
	elem.mediaId = mcard.mediaId;
	elem.removeEvents('click');
	elem.addEvent('click', openVideo);
}

function ME_deleteMedia(elem) {
	var mcard = elem.getParent('.mcard');
	if (!mcard.mediaId) {
		mcard.mediaId = mcard.get('title');
		if (!Browser.Engine.trident4)
			mcard.removeProperty('title');
	}
	elem.mediaId = mcard.mediaId;
	elem.removeEvents('click');
	elem.addEvent('click', deleteMedia);
}

function ME_offerFriendship(elem) {
	var vcard = elem.getParent('.vcard');
	if (!vcard.userId) {
		vcard.userId = vcard.get('title');
		if (!Browser.Engine.trident4)
			vcard.removeProperty('title');
	}
	elem.userId = vcard.userId;
	elem.removeEvents('click');
	elem.addEvent('click', offerFriendship);
}

domwalker.functions['class:view'] = function(elem) {
	// album galerie
	if (this.parentHasProperty('class', 'album')
			&& this.parentHasProperty('class', 'mcard')) {
		if (elem.get('tag') == 'a') {
			elem.removeEvents('click');
			ME_albumGalerie(elem);
		} else {
			var a = elem.getElement('a');
			if (a)
				ME_albumGalerie(a);
		}
	}

	// video view
	if (this.parentHasProperty('class', 'video')
			&& this.parentHasProperty('class', 'mcard')) {
		if (elem.get('tag') == 'a') {
			elem.removeEvents('click');
			ME_openVideo(elem);
		} else {
			var a = elem.getElement('a');
			if (a)
				ME_openVideo(a);
		}
	}

	// image view
	if (this.parentHasProperty('class', 'image')
			&& this.parentHasProperty('class', 'mcard')) {
		if (elem.get('tag') == 'a') {
			elem.removeEvents('click');
			ME_openImage(elem);
		} else {
			var a = elem.getElement('a');
			if (a)
				ME_openImage(a);
		}
	}

}.bind(domwalker);

domwalker.functions['class:offer_friendship'] = function(elem) {
	if (this.parentHasProperty('class', 'vcard')) {
		var a = elem.getElement('a');
		if (a)
			ME_offerFriendship(a);
	}
}.bind(domwalker);

// Forum tr hover in IE6_7
/*
 * domwalker.functions['class:topicList'] = function (elem) { if (
 * Browser.Engine.trident){ elem.getElements('tr').each(function(elem){
 * elem.addEvents({ 'mouseover' : function(){ if(!this.hasClass('hover'))
 * this.addClass('hover'); }, 'mouseout' : function(){
 * if(this.hasClass('hover')) this.removeClass('hover'); } });
 * 
 * }); } }.bind(domwalker);
 */

/**
 * *************************** Diese Funktionen waren bereits auskommentiert
 * ****************************
 */

/*
 * domwalker.functions['class:delete'] = function (elem) { if ((
 * this.parentHasProperty('class', 'video') || this.parentHasProperty('class',
 * 'image') || this.parentHasProperty('class', 'document') ) &&
 * this.parentHasProperty('class', 'mcard')){ var a = elem.getElement('a');
 * if(a) ME_deleteMedia(a); }
 * 
 * if (this.parentHasProperty('class', 'album') &&
 * this.parentHasProperty('class', 'mcard')){ var a = elem.getElement('a');
 * if(a) ME_deleteAlbum(a); } }.bind(domwalker);
 */

/*
 * function ME_deleteAlbum(elem){ var mcard = elem.getParent('.mcard'); if
 * (!mcard.mediaId){ mcard.mediaId = mcard.get('title');
 * if(!Browser.Engine.trident4) mcard.removeProperty('title'); } elem.mediaId =
 * mcard.mediaId; elem.removeEvents('click'); elem.addEvent('click',
 * deleteAlbum); }
 */


///////////////////////////////////////////////////////
// dropdown.js


// IE6 dropdown positioning

var Dropdown = new Class({

	open : false,
	hideDelay : false,

	initialize: function(element){

		this.element = element;
		this.dt = this.element.getElement('dt');
		this.dd = this.element.getElement('dd');

		this.dt.set('html', this.dt.innerHTML + '<span class="overlay"></span>');

		//für IE6_7 anders
		if(Browser.Engine.trident){
			var cardType = 'mcard'; 
			if(this.element.getParent('vcard'))
				cardType = 'vcard';
			
			var mediaType = '';
			var parent = this.element.getParent('.'+cardType);
			if(parent){
				if(parent.className.contains('video'))
					mediaType = ' video';
				if(parent.className.contains('album'))
					mediaType = ' album';
				if(parent.className.contains('image'))
					mediaType = ' image';
				if(parent.className.contains('document'))
					mediaType = ' document';
			}
			//Wrapper für dd
			this.Wrapper = new Element('dl', {'class': 'IE6dd dropdown ' + cardType + mediaType});
			this.Wrapper.adopt(this.dd);
			this.Wrapper.inject($('Body'));
	
			domwalker.hurry(this.Wrapper);

			//styles ändern
			this.Wrapper.setStyles({
				'position' : 'absolute',
				'display' : 'none',
				'z-index' : '10000',
				'padding': '20px'
				});
			this.dd.setStyles({
				'display' : 'block',
				'position': 'relative',
				'width' : this.dt.getStyle('width').toInt() + 3
				});
			//click event auf dt
			this.dt.addEvent('click', this.IE6_dtEvent.bind(this));

			//event auf dl
			this.Wrapper.addEvent('mouseleave', this.wrapperEvent.bind(this));
		}
		else{
			this.dt.addEvent('click', this.dtEvent.bind(this));
			this.element.addEvents({
				'mouseleave' : this.ddEventLeave.bind(this),
				'mouseenter' : this.ddEventEnter.bind(this)
			});
		}



	},

	dtEvent : function(){
		this.ddEventEnter();
		if(this.open){
			this.dd.setStyle('display', 'none');
			this.element.toggleClass('open_dd');
			this.open = false;
		} else {
			this.dd.setStyle('display', 'block');
			this.open = true;
			if(!this.element.hasClass('open_dd'))
				this.element.toggleClass('open_dd');
		}

	},

	ddEventLeave : function(){
		if(this.open)
			this.hideDelay = this.dtEvent.delay(500, this);
	},

	ddEventEnter : function(){
		if(this.hideDelay){
			$clear(this.hideDelay);
			this.hideDelay = false;
		}
	},

	IE6_dtEvent : function(){
		var tmp = 'block';
			if(this.open){tmp = 'none'; this.open = false;}
			else {this.open = 'true';}
			this.Wrapper.setStyles({
				'display': tmp,
				'left' : this.element.getPosition().x - 20,
				'top' : this.element.getPosition().y - 20
			});
			this.dt.getParent().toggleClass('open_dd');
	return false;
	},

	wrapperEvent : function(){
		if(this.open){
			this.open = false;
			this.Wrapper.setStyles({
				'display': 'none',
				'left' : this.element.getPosition().x - 20,
				'top' : this.element.getPosition().y - 20
			});
			this.dt.getParent().toggleClass('open_dd');
		}
		return false;
	}
});



///////////////////////////////////////////////////////
// dropdownlist.js


var DropDownList = new Class({

	Implements: Options,

	options: {
		type: 'dropDown',
		Suggestion: null,
		typeInputName: 'interests/id',
		typeInput: null,
		typeAdd: null,
		typeList: null
	},

	form: null,
	submitButton: null,
	inputIndex: 0,
	boxcontainer: null,
	linkedProfileContainer: null,
	linkedProfileBox: null,
	activeStatus: false,
	boxStatus: true,

	initialize: function(options)
	{
		this.setOptions(options);

		this.initForm();
		this.initInput();
		this.initList();
		this.initBoxes();

	},
	initForm: function()
	{
		if($(this.options.type + 'Form'))
		{
			this.form = $(this.options.type + 'Form');
			this.submitButton = $(this.options.type + 'Submit');

			this.submitButton.addEvent('click', function(e)
			{
				e.stop();
				//eval('Links.saveLinks()');
				this.saveLinks();
			}.bind(this));
		}
	},
	initBoxes: function()
	{
		this.boxContainer = $('ShowMe').getElement('div.show_room');
		this.linkedProfileContainer = new Element('dl',
		{
			'class': 'linkedProfiles',
			'html': '<dt>Verlinkte Person/en</dt><dd><ul class="linkedProfileBox"></ul></dd>'
		});

		this.linkedProfileContainer.inject(this.boxContainer);
		this.linkedProfileBox = this.boxContainer.getElement('.linkedProfileBox');
	},
	initList: function()
	{
		if(this.options.typeList)
			this.inputIndex = this.options.typeList.getElements('input').length;
	},
	initInput: function()
	{
		if (this.options.typeList == null)
			this.options.typeList = $(this.options.type + 'List');

			if ($(this.options.type))
			{
					if (this.options.typeInput == null)
							this.options.typeInput = $(this.options.type);

					if (this.options.typeAdd == null)
							this.options.typeAdd = $(this.options.type + 'Add');

					if (this.options.typeInput && this.options.typeAdd && this.options.typeList)
					{
							this.options.typeAdd.addEvent('click', function()
							{
									var title = this.options.typeInput.get('value');
									if (title.length < 3)
											return false;

									this.addItem($(this.options.type + 'Alt').value, this.options.typeInput.value.capitalize());

									return false;
							}.bind(this));
					}
			}
	},
	addItem: function(data, text)
	{
			var identifier = JSON.decode(data).identifier;
			//is item already inserted?

			var alreadyInserted = this.options.typeList.getElements('input').some(function(el)
			{
					return JSON.decode(el.get('value')).identifier == JSON.decode(data).identifier;
			});

			if (alreadyInserted)
					return;

			var label = new Element('label',
			{
					'html': '<input type="checkbox" class="fCheck" name="' + this.options.type + '/' + this.inputIndex + '" value="' + data + '" checked="checked" />'
			});

			var listItem = new Element('li',
			{
					'html': text
			}).adopt(label);

			this.createEventsForListItem(label);

			listItem.inject(this.options.typeList);
			this.inputIndex++;

			//Highlight Box
			this.renderBox(identifier, true);
	},
	renderBox: function(identifier, neu)
	{
			if (identifier != null)
			{
					var data = this.findBoxData(identifier);
					var boxObj = this.createHtml(data, neu);

					boxObj.inject(this.linkedProfileBox);
					this.createEventForBox(data);
			}
	},
	findBoxData: function(identifier)
	{
			if (identifier != null)
			{
					var found = $(this.options.type + 'List').getElements('input').filter(function(item, index)
					{
							if (item.value.test('\'identifier\':\'' + identifier + '\''))
									return item;
					});

					if (found[0] != undefined)
							return JSON.decode(found[0].value);
					else
							return false;
			}
	},
	findBoxInput: function(identifier)
	{
			if (identifier != null)
			{
					var found = $(this.options.type + 'List').getElements('input').filter(function(item, index)
					{
							if (item.value.test('\'identifier\':\'' + identifier + '\''))
									return item;
					});

					if (found[0] != undefined)
							return found[0];
					else
							return false;
			}
	},
	createHtml: function(data, neu) {

		var box = new Element('li',
		{
				'id': 'box' + data.identifier,
				'styles': {
					'top': data.coordY,
					'left': data.coordX
				},
				// set links to profile in profile name description (not on link image):
				'html': '<a href="#" onclick="return false;"><div style="width: 20px; height: 20px;"></div></a><a href="/profile/home/'+data.user_id+'"><span>' + data.text + '</span></a>'
				// deprecated:
				//'html': '<a href="#" onclick="return false;"><div style="width: 20px; height: 20px;"></div></a><a href="#" onclick="return false;"><span>' + data.text + '</span></a>'
				//'html': '<a href="/profile/home/'+data.user_id+'"><div style="width: 20px; height: 20px;"></div></a><a href="/profile/home/'+data.user_id+'"><span>' + data.text + '</span></a>'
		});

		if(neu){
			box.addClass('new');
		//box.setStyle('opacity', 0.9);
	}
			return box;
	},
	createEventForBox: function(data)
	{
			if (data.identifier != null)
			{
					var box = $('box' + data.identifier);
					var input = this.findBoxInput(data.identifier);

					box.addEvents(
					{
							'mouseenter': function(e)
							{
									e.stop();
									box.toggleClass('hover');
				//box.setStyle('opacity', 1);
							},
							'mouseleave': function(e)
							{
									e.stop();
									box.toggleClass('hover');
				/*var op = 0.8;
				if(box.hasClass('new')) op = 0.9;
				box.setStyle('opacity', op );*/
							}
					});

					box.myDrag = new Drag(box,
					{
							snap: 0,
							limit:
							{
									x: [5, 604],
									y: [5, 445]
							},
							onSnap: function(el)
							{
									el.addClass('dragging');
							},
							onComplete: function(el)
							{
									var newCoords = el.getStyles('left', 'top');
									data.coordY = newCoords.top;
									data.coordX = newCoords.left;

									input.setProperty('value', JSON.encode(data));

									el.removeClass('dragging');
							}
					});
			}
	},
	saveLinks: function()
	{
		var actLinks = this.options.typeList.getElements('input');
		var inputData = new Object();
		actLinks.each(function(item, index)
		{
			var tmpData = JSON.decode(item.getProperty('value'));
			tmpData.media_id = $('actMediaId').getProperty('value');
			inputData[item.getProperty('name')] = JSON.encode(tmpData);
		});

		var myRequest = new Request(
		{
			method: 'post',
			url: this.form.action + '/' + $('actMediaId').getProperty('value'),
			data: inputData,
			onSuccess: function(responseText, responseXML)
			{
				if(JSON.decode(responseText).result == 'save')
				{
					this.setActive();
				}
			}.bind(this)
		}).send();
	},
	createLoadedBoxes: function()
	{
		//this.removeBoxes();
		if (this.options.typeList)
		{
			this.options.typeList.getElements('input').each(function(item, index)
			{
				var label = item.getParent();

				this.createEventsForListItem(label);

				this.inputIndex++;

				var data = JSON.decode(item.getProperty('value'));

			this.addLinkListEvent(label.getParent('li'), data.identifier);
			this.renderBox(data.identifier, false);
			}.bind(this));

			if(!this.activeStatus)
				this.setActive(false);

			if (this.activeStatus == false)
			{
				if (this.options.typeList.getElements('input').length == 0)
				{
					$('NoLinks').setStyle('display', 'block');
				}
				else
				{
					$('NoLinks').setStyle('display', 'none');
				}
			}
			else
			{
				$('NoLinks').setStyle('display', 'none');
			}
		}
	},
	addLinkListEvent: function(li, identifier)
	{
		li.addEvents(
		{
			'mouseenter': function(e)
			{
				e.stop();
				var box = $('box'+identifier);
				box.toggleClass('hover');
			},
			'mouseleave': function(e)
			{
				e.stop();
				var box = $('box'+identifier);
				box.toggleClass('hover');
			}
		});
	},
	removeBoxes: function()
	{
			if ($('ShowMe').getElement('.linkedProfileBox'))
			{
					$('ShowMe').getElement('.linkedProfileBox').set('html', '');
			}
	},
	createEventsForListItem: function(label)
	{
			label.addEvent('mouseover', function()
			{
					this.getParent().toggleClass('hover');
			});

			label.addEvent('mouseout', function()
			{
					this.getParent().toggleClass('hover');
			});

			label.addEvent('click', function()
			{
					var identifier = JSON.decode(this.getElement('input').value).identifier;
					$('box' + identifier).destroy();
					this.getParent().destroy();
			});
	},
	setActive: function(status)
	{
		if($defined(status))
			this.activeStatus =! status;

		var boxContainer = $('ShowMe').getElement('.linkedProfileBox');
		var listForm = $(this.options.type + 'Form');
		var editButton = $('linkEdit');
		var linkList = $('linkList');
		var linkSubmit = $('linkSubmit');

		if (this.activeStatus == false)
		{
			if (boxContainer)
			{
				boxContainer.getElements('li').each(function(item, index)
				{
					item.myDrag.attach();
					item.setStyle('cursor', 'move');
				});

				this.activeStatus = true;
			}

			if($('NoLinks'))
				$('NoLinks').setStyle('display', 'none');

			if (listForm)
				listForm.setStyle('display', 'block');

			if (editButton)
				editButton.set('text', 'Abbrechen');

			if (linkList && linkList.hasClass('list_view'))
				linkList.toggleClass('list_view');

			if (linkSubmit && linkSubmit.getParent('li').hasClass('accessibility'))
				linkSubmit.getParent('li').removeClass('accessibility');
		}
		else if (this.activeStatus == true)
		{
			if (boxContainer)
			{
				boxContainer.getElements('li').each(function(item, index)
				{
					item.myDrag.detach();
					item.setStyle('cursor', 'auto');
				});

				this.activeStatus = false;
			}

			console.log(boxContainer.getElements('li').length);

			if(this.options.typeList.getElements('input').length == 0 && $('NoLinks'))
				$('NoLinks').setStyle('display', 'block');

			if (listForm)
				listForm.setStyle('display', 'none');

			if (editButton)
				editButton.set('text', 'Bearbeiten');

			if (linkList && !linkList.hasClass('list_view'))
				linkList.toggleClass('list_view');

			if (linkSubmit && !linkSubmit.getParent('li').hasClass('accessibility'))
				linkSubmit.getParent('li').addClass('accessibility');
		}

		/*if (this.options.typeList.getElements('input').length == 0)
		{
			console.log('BLOCK');
			$('NoLinks').setStyle('display', 'block');
		}
		else
		{
			console.log('NONE');
			$('NoLinks').setStyle('display', 'none');
		}*/
	},
	toggleBoxes: function()
	{
			if (this.boxStatus == true)
			{
					if (this.linkedProfileBox)
					{
							this.linkedProfileBox.setStyle('display', 'none');
			$('linkToggleBoxes').set('text', 'Profillinks einblenden');

			$('linkEdit').getParent('li').setStyle('display', 'none');
							this.boxStatus = false;

			if(this.activeStatus == true)
				this.setActive();
					}
			}
			else
					if (this.boxStatus == false)
					{
							if (this.linkedProfileBox)
							{
									this.linkedProfileBox.setStyle('display', 'block');
				$('linkToggleBoxes').set('text', 'Profillinks ausblenden')
				$('linkEdit').getParent('li').setStyle('display', 'block');
				this.boxStatus = true;
							}
					}
	}
}).implement(Options);

/*
var Links = new Class(
{
	saveLinks: function()
	{
		var actLinks = this.options.typeList.getElements('input');
		var inputData = new Object();
		actLinks.each(function(item, index)
		{
			var tmpData = JSON.decode(item.getProperty('value'));
			tmpData.media_id = $('actMediaId').getProperty('value');
			inputData[item.getProperty('name')] = JSON.encode(tmpData);
		});

		var myRequest = new Request(
		{
			method: 'post',
			url: this.form.action + '/' + $('actMediaId').getProperty('value'),
			data: inputData
		}).send();
	}
});
*/


///////////////////////////////////////////////////////
// form.js

window.addEvent('load', function() {
	//tinyMCE
	if ($('tmce_message')) {
		// document.writeln('<script type="text/javascript" src=""></script>');
		//var tmce = Asset.javascript('/js/tiny_mce/tiny_mce.js');

		tinyMCE.init({
			// General options
			mode : "exact",
			elements : "tmce_message",
			theme : "advanced",
			plugins : "",

			// Theme options
			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifyright,justifyfull,|,bullist,outdent,indent",
			theme_advanced_buttons2 : "",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left"
		});
	}
	});

//form domready
window.addEvent('domready', function(){



	//MV_Selection
	$$('.ajaxSelection').each(function(elem){
		var tmpSel = new MV_Selection(elem);
		});

	//MV_Selection
	$$('.countChars').each(function(elem){
		var tmpCount = new countDigitsLeft(elem);
	});

	//checkchecks
	$$('.headline .fCheck').each(function(elem){
		elem.addEvent('click', checkChecks);
	});


	//user input for assoctiationPosition
	initializeUserPositionInputs();

});

/*
Class  MV_Selection  for innerToggle at sublevel 3 with ajax reload

element = link, on which the select process should start after clicking

*/
var MV_Selection = new Class(
{
	initialize: function(element)
	{
		this.element = element;

		/*selection vars*/
		this.Category = this.element.id;
		this.Selection = new Array();
		this.tmpSelection = new Array();
		this.SelectionType = '';

		/*container vars*/
		this.MainWrapper = this.element.getParent('.selectionContainer');
		this.tmpWrapper;
		this.currentSelectionWrapper;
		this.currentSelection = new Element('ul', {'class' : 'card_list small_cards'});
		this.FinalContent = false;
		this.tmpFinalContent = false;

		this.MainWrapperStartHtml = this.MainWrapper.get('html');
		this.MainWrapperInfoHtml = false;
		this.MainWrapperStartHeight = this.MainWrapper.getSize().y;

		this.Loader = new Element('div', {'class' : 'ajax-loading'});

		/*Request vars*/
		this.Error = false;
		this.tmpContent;
		this.RequestLayout = new Request(
		{
			url: '/ajax/selection_layout/',
			method: 'post',
			onSuccess: function(result){this.tmpContent = result; this.dumpRequested(this.Destination);}.bind(this),
			onFailure: function(){this.Error = true; this.tmpContent = 'Fehler bei der Übertragung'; this.dumpError(this.Destination); }.bind(this)
		});

		this.Request = new Request(
		{
			url: '/ajax/selection/',
			method: 'post',
			onSuccess: function(result){this.tmpContent = result; this.dumpRequested(this.Destination);}.bind(this),
			onFailure: function(){this.Error = true; this.tmpContent = 'Fehler bei der Übertragung'; this.dumpError(this.Destination);}.bind(this)
		});

		/*else*/
		this.SubmitBtn;

		/*Status Variabeln*/
		this.hasSelection = false;
		this.Exists = false;
		this.isShown = false;
		this.EffektBool = true;

		/*For preselection*/
		this.hasPreSelection = false;
		this.PreSelectedArray = new Array();

		/*effekt var*/
		this.Fx_morph;
		this.Fx_close = false;

		this.createStartupEvent();
	},

	createStartupEvent : function()
	{
		this.element.href = 'javascript:void(0)';
		this.SelectionType = this.element.id;

		this.element.removeEvents('click');
		this.element.addEvent('click', function()
		{
			if(this.hasSelection)
			{
				//inhalt austauschen
				this.MainWrapper.setStyles(
				{
					opacity: 0,
					height: this.MainWrapper.getSize().y
				});

				this.MainWrapper.set('html', '');
				if(this.FinalContent)
				{
					this.tmpFinalContent = this.FinalContent.clone(true, true);
					this.FinalContent.inject(this.MainWrapper);
				}

				this.createCardEvents(this.MainWrapper);
				updateScreenLayout(this.MainWrapper.getElement('ul'));

				//variabeln neu setzten
				this.tmpSelection = $A(this.Selection);
				this.currentSelectionWrapper = this.MainWrapper.getElement('.currentSelection');
				this.currentSelection =  this.MainWrapper.getElement('.currentSelection ul');
				this.Exists = true;

				this.MainWrapper.getElement('.sel_cancel').addEvent('click', function()
				{
					this.abbort();
				}.bind(this));

				this.SubmitBTn = this.MainWrapper.getElement('input.sel_submit');

				//submit button funktion ändern
				this.changeSubmit('keine Änderung', false, true);

				//effekt
				 var tmpFx_morph = new Fx.Morph(this.MainWrapper, {onComplete : function(){this.MainWrapper.setStyle('height', 'auto')}.bind(this)});
				tmpFx_morph.start({
						height	: this.MainWrapper.getElement('.ajax_result').getSize().y,
						opacity : 1
				});
			}
			else
			{
				var PreSelected = '';

				if(this.MainWrapper.getElement('.fSelection'))
				{
					this.hasPreSelection = true;
					PreSelected = this.getPreSelected(this.MainWrapper.getElement('.fSelection'));
				}

				this.getRequested(this.MainWrapper, this.createPost(this.element.id, true) + PreSelected, true);
			}

			return false;
		}.bind(this));
	},
	getRequested : function(whereToPut, query, layout)
	{
		this.Destination = whereToPut;

			 /*loading anzeige + effect*/
			/*whereToPut.setStyles({
				opacity: 0,
				height: whereToPut.getSize().y
			});
			*/

			 whereToPut.set('html', '');

			 this.Loader.inject(whereToPut);
			 whereToPut.setStyle('height', '50px');
			/*this.Fx_morph = new Fx.Morph(whereToPut , {onComplete : function(){whereToPut.setStyle('height', 'auto')} });
			this.Fx_morph.start({
						height: '50px',
						opacity : 1
					});
			*/
			 /*Requesten*/
			 if(layout){
				 this.RequestLayout.cancel();
				this.RequestLayout.send(query);
			 }else{
				 this.Request.cancel();
				this.Request.send(query);
			}
		 },

		 dumpRequested : function(whereToPut){
			 //this.Fx_morph.cancel();
			 /*if($type(this.Fx_close).test('object')){
					 this.Fx_close.cancel();
					 if(this.EffektBool){
						 this.Fx_close.onComplete();
						 this.EffektBool = true;
					 }else{this.EffektBool = true;}
			 }*/
			/*inhalt reinschmeißen
			 whereToPut.setStyles({
				opacity: 0,
				height: whereToPut.getSize().y
			});*/

			 whereToPut.set('html', this.tmpContent);
			 whereToPut.setStyle('height', 'auto');
			 //layout
			 updateScreenLayout(whereToPut);
			 if(this.Exists){generateIndicators(whereToPut.getElement('.headline'), 'em', 'toggle_indicator', 'bottom');}
			 this.createCardEvents(whereToPut);

			/*Falls Startelemente vorhanden sind*/
			if(this.hasPreSelection){
				//bei der ersten ausführung
				if(!this.Exists){
					this.hasSelection = true;
					this.currentSelectionWrapper = this.MainWrapper.getElement('.currentSelection');
					this.currentSelection = this.currentSelectionWrapper.getElement('ul');
				}
			}
			this.SearchForExisting(whereToPut);


			 /*bei der ersten ausführung*/
			if(!this.Exists){
				 this.Exists = true;
				 whereToPut.getElement('.sel_cancel').addEvent('click', function(){
						 this.abbort();
					 }.bind(this));
				 this.currentSelectionWrapper = whereToPut.getElement('.currentSelection');
				 this.SubmitBTn = whereToPut.getElement('input.sel_submit');
			 }

			/*auf-faden*/
			/*var tmpFx_morph = new Fx.Morph(whereToPut, {onComplete : function(){whereToPut.setStyle('height', 'auto')}});
			tmpFx_morph.start({
						height	: whereToPut.getElement('.ajax_result').getSize().y,
						opacity : 1
				});
			*/
		 },

		 dumpError : function(whereToPut){
			 /*this.Fx_morph.cancel();
			 if($type(this.Fx_close).test('object')){
					 this.Fx_close.cancel();
					 if(this.EffektBool){
						 this.Fx_close.onComplete();
						 this.EffektBool = true;
					 }else{this.EffektBool = true;}
			 }*/
			/*inhalt reinschmeißen*/
			 /*whereToPut.setStyles({
				height: 'auto'
			});*/
			 whereToPut.set('html', this.tmpContent);

		 },

		 createCardEvents : function(wrapper){

					 /*nächste ebene öffnen*/
					 wrapper.getElements('a.open').each(function(elem){
						 if(!elem.hasClass('inactive')){
							 elem.removeEvents('click');
							 elem.addEvent('click', function(e){
								 e.stop();
								 this.getNextSublevel(elem);
								 return false;
							 }.bind(this));
						 }
					 }.bind(this));

					 /*hinzufügen des elements*/
					 wrapper.getElements('a.add').each(function(elem){
						 elem.removeEvents('click');
						 elem.addEvent('click', function(e){
							 e.stop();
							 this.add(elem);
							 return false;
						 }.bind(this));
					 }.bind(this));

					 /*entfernen*/
					 wrapper.getElements('a.remove').each(function(elem){
						 elem.removeEvents('click');
						 elem.addEvent('click', function(e){
							 e.stop();
							 this.remove(elem);
							 return false;
						 }.bind(this));
					 }.bind(this));

					 /*bild �ffnen*/
					 wrapper.getElements('a.link').each(function(elem){
						 elem.addEvent('click', function(e){
								 e.stop();
								 MV_Overlay.show('/ajax/overlay/', true);
								 return false;
							 }.bind(this));
					 }.bind(this));
		 },

		 getNextSublevel : function(elem){
			 var tmpParent = elem.getParent('.toggle_item');
			 //layout akteuelles li
			 if(tmpParent.hasClass('last')){tmpParent.toggleClass('last');}
			 if(!tmpParent.hasClass('closed')){tmpParent.toggleClass('closed');}

				 /*effekt schließen*/
				 //var tmpEffekt = tmpParent.getElement('.segment-content');
				 //tmpEffekt.setStyle('height', 0);
				 /*this.Fx_close = new Fx.Morph(tmpEffekt, {onComplete : function(){tmpEffekt.setStyle('height', 'auto'); tmpParent.toggleClass('closed'); this.EffektBool = false;}.bind(this)});
				this.Fx_close.start({
							height	: 0
					});*/


			 //alle untern li löschen
			 tmpParent.getAllNext('.toggle_item').each(function(elem){elem.destroy();});

			 //neues li erzeugen
			 this.tmpWrapper = new Element('li', {'class' : 'toggle_item active last'});
			 this.tmpWrapper.inject(tmpParent.getParent('ul'));

			 //request
			 this.getRequested(this.tmpWrapper, this.createPost(elem.getParent('.mcard').id, false), false);
		 },

		 add : function(elem){
			 var tmpCard = elem.getParent('.mcard');

			 //tmpCard ->add buttons ändern
			 var tmpbtn = tmpCard.getElements('a.add');
			 tmpbtn.each(function(btn){
				btn.removeClass('add');
				btn.addClass('remove');
				btn.removeEvents('click');
				btn.set('title', 'Aus der Auswahl löschen');
				btn.addEvent('click', function(e){
	 				e.stop();
	 				this.remove(elem);
	 				return false;
	 			}.bind(this));
			 }.bind(this));

			 //element klonen und oben einfügen
			 var tmpCloneWrapper = new Element('li', {'class' : 'list_entry'});
			 var tmpClone = tmpCard.clone(true, true);
			 tmpCloneWrapper.adopt(tmpClone);

			 //ausgewählt hinzufügen
			// var tmpSelected = new Element('span');

				 /*effekt*/
				/* tmpCloneWrapper.setStyle('opacity', '0');
				 var tmpFx_show = new Fx.Morph(tmpCloneWrapper);
				tmpFx_show.start({opacity : 1});
*/
			 //prüfung , button ändern
			 if(this.Selection.length < 1){
				 //liste generieren
				 this.currentSelectionWrapper.set('html', '');
				 this.currentSelection.inject(this.currentSelectionWrapper);

				 //submit button ändern
				 if(this.hasSelection){this.changeSubmit('Auswahl aktualisieren', true, false);}
				 else{ this.changeSubmit('Auswahl hinzufügen', true, true);}

			 }else{
					 if(this.hasSelection){this.changeSubmit('Auswahl aktualisieren', true, false);}
			 }

			 tmpCloneWrapper.inject(this.currentSelection);

			 //events setzten
			 this.createCardEvents(tmpCloneWrapper);

			 //element dem array hinzufuegen
			 this.Selection.push(tmpCard.id);

			 //falls geklontes element eine sub_ebene öffnen kann -> deaktivieren
			 var tmpOpen = tmpClone.getElement('a.open')
			 if(tmpOpen){
				 tmpOpen.removeEvents('click');
				 tmpOpen.addEvent('click', function(e){e.stop; return false;});
				 tmpOpen.toggleClass('inactive');
				 tmpOpen.set('title', 'nicht möglich')
			 }

			 //falls element eine sub_ebene öffnen kann -> deaktivieren
			 tmpOpen = tmpCard.getElement('a.open')
			 if(tmpOpen){
				 tmpOpen.removeEvents('click');
				 tmpOpen.addEvent('click', function(e){e.stop; return false;});
				 tmpOpen.toggleClass('inactive');
				 tmpOpen.set('title', 'nicht möglich')
			 }
		 },

		 remove : function(elem){

			 var tmpElem = elem.getParent('.mcard');
			 var tmpCardID = tmpElem.id;

			//aus der auswahl entfernen
			 this.Selection.erase(tmpCardID);

			/*effekt falls alle wieder leer*/
				 if(this.Selection.length < 1){
					 //this.currentSelectionWrapper.setStyle('opacity' , '0');
					 this.currentSelection.getElement('#' + tmpCardID).getParent().destroy();
					 this.currentSelectionWrapper.set('html', 'Keine ausgewählt');
					 //this.currentSelectionWrapper.fade(1);

					//submit button ändern
					if(this.hasSelection){
						this.changeSubmit('Auswahl aktualisieren', true, false);
					 }else{
						 this.changeSubmit('keine Auswahl', false, true);
					 }

				 }else{
					 this.currentSelection.getElement('#' + tmpCardID).getParent().destroy();
					 if(this.hasSelection){ this.changeSubmit('Auswahl aktualisieren', true, false);}
				}

			 //ursprüngliche card wieder add btn, falls existiert
				 if($(tmpCardID)){
					var tmpbtn = $(tmpCardID).getElements('a.remove');
					tmpbtn.each(function(btn){
						btn.addClass('add');
						btn.removeClass('remove');
						btn.removeEvents('click');
						btn.set('title', 'Zur Auswahl hinzufügen');
						btn.addEvent('click', function(e){
							e.stop();
							this.add(btn);
							return false;
						}.bind(this));
					}.bind(this));

					//falls element eine sub_ebene öffnen kann -> aktivieren
					 var tmpOpen = $(tmpCardID).getElement('a.open')
					 if(tmpOpen){
						 tmpOpen.removeEvents('click');
						 tmpOpen.set('title', '�ffnen');
						 tmpOpen.addEvent('click', function(e){
							e.stop();
							this.getNextSublevel(tmpOpen);
							return false;
						}.bind(this));

						 tmpOpen.toggleClass('inactive');
					 }
				}
		},

		 changeSubmit : function(str_value, bool_event, bool_check){
			 if(this.SubmitBTn.hasClass('inactive') || bool_check){ this.SubmitBTn.toggleClass('inactive'); this.SubmitBTn.getParent().toggleClass('inactive');}
		 	if(!this.SubmitBTn.hasClass('fSubmit') || bool_check){this.SubmitBTn.toggleClass('fSubmit'); this.SubmitBTn.getParent().toggleClass('fSubmit');}
			this.SubmitBTn.set('value', str_value);
				 if(bool_event){
					 this.SubmitBTn.removeEvents('click');
					 this.SubmitBTn.addEvent('click', function(e){
						 e.stop();
						 this.finalize();
						 return false;
					 }.bind(this));
				 }else{
					 this.SubmitBTn.removeEvents('click');
				 }
		 },

		 SearchForExisting : function(container){
			 container.getElements('.mcard').each(function(elem){
				 //alle außer in currentSelection
				 if(!elem.getParent('.currentSelection')){
					//falls elem in der vorauswahl
					if(this.Selection.contains(elem.get('id'))){
						//elem ->add button ändern
						var tmpbtn = elem.getElements('a.add');
						tmpbtn.each(function(btn){
							btn.removeClass('add');
							btn.addClass('remove');
							btn.removeEvents('click');
							btn.set('title', 'Aus der Auswahl löschen');
							btn.addEvent('click', function(e){
								e.stop();
								this.remove(btn);
								return false;
							}.bind(this));
						}.bind(this));
					}
				 }
			}.bind(this));
		 },

		 createPost : function(string, bool){
			 var query;
			 if(bool){
				 query = 'selectionLayout/type='+ string.replace('sel_', '') + '&selectionLayout/user_id='+ globalNumber;
				 }
			 else{
				 var tmpArray = string.split('_');
				 query = 'selection/type='+ tmpArray[0] +'&selection/id='+ tmpArray[1] +'&selection/user_id='+ globalNumber;
			 }
			 return query;
		 },

		 getPreSelected : function(container){
			 var tmpArray = container.getElements('input');
			 var query = '';
			 for( i=0; i < tmpArray.length; i++){
				query += '&' + tmpArray[i].name + '=' + tmpArray[i].value

				tmpArray[i].name = tmpArray[i].name.replace('type/', '');
				var tmpType = tmpArray[i].name.split("[");
				this.PreSelectedArray[i] = tmpType[0] + '_' +tmpArray[i].value;

			 }
			 this.Selection = $A(this.PreSelectedArray);
			 this.tmpSelection = $A(this.PreSelectedArray);
			 return query;
		 },

		 finalize : function(){

			 if(this.Selection.length < 1){this.hasSelection = false; this.abbort(); return false;}

			 //input type hidden generieren
			 var hiddenWrapper = new Element('div', {'style' : 'display: none;', 'class' : 'fSelection'});
			 var tmpContent = '';
			 this.Selection.each(function(elem, index){
			 	var tmpBalBla = elem.split("_");
			 	tmpContent += '<input type="hidden" name="type/'+ tmpBalBla[0] +'['+ index +']" value="'+ tmpBalBla[1] +'" />';

			 	});
			 hiddenWrapper.set('html', tmpContent);

			 //inhalt speichern- info inhalt erzeugen
			 this.FinalContent = this.MainWrapper.getChildren('.ajax_result').clone(true, true);
			 this.hasSelection = true;
				 //ausfaden
				 /*this.MainWrapper.setStyles({
					opacity: 0,
					height: this.MainWrapper.getSize().y
				});*/

				//info Inhalt

				//this.MainWrapperInfoHtml = new Element('div', {'html':'Du hast '+ this.Selection.length +' Elemente ausgewählt. <a class="ajaxSelection" href="javascript:void(0)">Auswahl ändern</a>'});
				this.MainWrapperInfoHtml = new Element('div', {'html':'Bereits '+ this.Selection.length +' ausgewählt. <a class="ajaxSelection" href="javascript:void(0)">Auswahl ändern</a>'});
				//hidden felder reinschmeißen
				 hiddenWrapper.inject(this.MainWrapperInfoHtml);
				 this.MainWrapper.set('html', this.MainWrapperInfoHtml.get('html'));
				 /*var tmpFx_morph = new Fx.Morph(this.MainWrapper, {onComplete : function(){this.MainWrapper.setStyle('height', 'auto')}.bind(this)});
				tmpFx_morph.start({
							height	: this.MainWrapperStartHeight,
							opacity : 1
					});*/
				 this.MainWrapper.setStyles('height', this.MainWrapperStartHeight);

			 this.element = this.MainWrapper.getElement('a');
			 this.createStartupEvent();
			 this.isShown = false;

		 },

		 abbort : function(){
			 //ausfaden
			/* this.MainWrapper.setStyles({
				opacity: 0,
				height: this.MainWrapper.getSize().y
			});*/

			//welchen inhalt angeben?
			if(this.hasSelection){
				if(this.hasPreSelection){this.MainWrapper.set('html', this.MainWrapperStartHtml);}
				else{this.MainWrapper.set('html', this.MainWrapperInfoHtml.get('html'));}

				if(this.tmpFinalContent){this.FinalContent = this.tmpFinalContent;}
				this.Selection = $A(this.tmpSelection);
			}
			else{
				this.Exists = false;
				if(this.hasPreSelection){
					this.MainWrapper.set('html', 'Keine Auswahl. <a href="javascript:void(0)" id="'+ this.SelectionType +'" class="ajaxSelection">Jetzt ändern!</a>');
					this.hasPreSelection = false;
					this.PreSelectionArray = new Array();
				}
				else{
					this.MainWrapper.set('html', this.MainWrapperStartHtml);
				}
				this.Selection = new Array();
				this.tmpWrapper = false;
				this.currentSelectionWrapper = false;
				this.currentSelection = new Element('ul', {'class' : 'card_list small_cards'});
				}

			 var tmpFx_morph = new Fx.Morph(this.MainWrapper, {onComplete : function(){this.MainWrapper.setStyle('height', 'auto')}.bind(this)});
			/*tmpFx_morph.start({
						height	: this.MainWrapperStartHeight,
						opacity : 1
				});*/

			 this.element = this.MainWrapper.getElement('a');
			 this.createStartupEvent();
			this.isShown = false;
		 }

});

//Class für countDigitsLeft
var countDigitsLeft = new Class({
		initialize: function(element){
			this.element = element;
			//console.log(this.element);
			this.InfoContainer = this.element.getParent('dd').getNext('dd.charsLeft');
			//console.log(this.element.getParent('dd'));
			this.Info = this.InfoContainer.getElement('.maxChars');
			this.MaxChars = this.Info.get('html');

			if(this.MaxChars > this.element.value.length){
				this.Info.set('html', this.MaxChars - this.element.value.length);
			}
			else{
				this.element.value = this.element.value.substring(0, this.MaxChars);
				this.Info.set('html', '0');
			}

			this.creatEvent();
		},

		creatEvent :  function () {
			this.element.addEvent('keyup', function(e){
				e.stop();
				if(this.MaxChars > this.element.value.length){
					this.Info.set('html', this.MaxChars - this.element.value.length);
				}
				else{
					this.element.value = this.element.value.substring(0, this.MaxChars);
					this.Info.set('html', '0');
				}
				return false;
			}.bind(this));
		}
});

//function for checking all Elements -> used for addEvents
var checkChecks =function(){
	var checker = !this.checked;
	this.getParent('fieldset').getElements('.formContent input[type=checkbox]').each(function(elem){
		if(checker){elem.removeProperty('checked');}
		else{elem.set('checked', 'checked');}
	});
	return true;
}


var initializeUserPositionInputs = function() {

	$$('.positionUserText').each( function(elem) {
		elem.setStyle('display', 'none');
	});
	$$('.positionUserSelect').each( function(elem) {
		elem.addEvent('change', function(elem) {

			var text = this.getSelected().get('text');

			if (text == 'Eigene Eingabe') {

				$$('.positionUserText').setStyle('display', 'block');

			} else {

				$$('.positionUserText').set('value', '');
				$$('.positionUserText').setStyle('display', 'none');
			}
		});
	});
};




///////////////////////////////////////////////////////
// hslider.js


//Class für horizontalen bild slider
/*
element =  die Liste
width = breite des viewports
amountInView = maximale anzahl an elementen im viewport
amountFade = breite des fade-bereiches links-recht inpx
*/
var hSlider = new Class({

	initialize: function(element, width, amountInView, amountFade){
		this.Wrapper = element;
		this.element = this.Wrapper.getElement('ul');
		this.allLi = this.element.getElements('li');
		this.amountLi = this.allLi.length;
		this.width = this.allLi.length * width;
		this.ElementWidth = width;

		this.link1;
		this.link2;

		//stauts vars
		this.counter = 0;
		this.maxcount = this.amountLi - amountInView;
		this.AmountInView = amountInView;

		//Breite von ul setzten
		this.element.setStyles({width: this.width, left: 0});

		//Effekt
		this.fx_Slide = new Fx.Tween(this.element, {duration: 1000, transition: Fx.Transitions.Cubic.easeOut});

		//setzten
		this.generateArrows();
		this.amountFade = amountFade;
		this.generateFader();

	},

	generateArrows :  function(){
		//links generieren
		var classRight = 'arrow_right_active';
		if(this.amountLi <= this.AmountInView){classRight = 'arrow_right';}

		this.link1 = new Element	('a', {'href': 'javascript:void(0)','class': 'arrow_left'}); this.link1.inject(this.Wrapper);
		this.link2 = new Element	('a', {'href': 'javascript:void(0)','class': classRight}); this.link2.inject(this.Wrapper);

		if(this.amountLi > this.AmountInView){
			//Effekt generieren
			this.link1.addEvent('click', function(){
				if( this.counter > 0){
					this.fx_Slide.cancel();
					this.counter--;
					this.fx_Slide.start('left', this.element.getStyle('left').toInt(), -(this.counter*this.ElementWidth));

					this.link2.className = 'arrow_right_active';
					if(this.counter == 0){this.link1.className = 'arrow_left';}
					else{this.link1.className = 'arrow_left_active';}
				}
			}.bind(this));
			this.link2.addEvent('click', function(){
			if( this.counter < this.maxcount){
				this.fx_Slide.cancel();
				this.counter++;
				this.fx_Slide.start('left', this.element.getStyle('left').toInt(), -(this.counter*this.ElementWidth));

				this.link1.className = 'arrow_left_active';
				if(this.counter == this.maxcount){this.link2.className = 'arrow_right';}
				else{this.link2.className = 'arrow_right_active';}
			}
		}.bind(this));
		}
	},

	generateFader : function(){
		//spans für opacity generieren
		var transLeft = new Element('span', {'class': 'cross_fade_right'}).inject(this.Wrapper.getElement('.inner_content'));
		var transRight = new Element('span', {'class': 'cross_fade_left'}).inject(this.Wrapper.getElement('.inner_content'));
		var tmpContent = '';
		for(i=0; i < this.amountFade; i++){tmpContent += '<span></span>';}
		transLeft.set('html', tmpContent);
		transRight.set('html',transLeft.innerHTML);
			//opacity setzten
			var allSpans = transRight.getElements('span').extend(transLeft.getElements('span'));
			var half = allSpans.length/2;
			for(i=0; i < allSpans.length; i++){
				if(i < half){var tmpOP = (half-i)/(half + 1);}
				else{var tmpOP = (i-(half - 1))/(half + 1);}
				allSpans[i].setStyle('opacity', tmpOP);
			}
	}
});



///////////////////////////////////////////////////////
// login.js


// overlay login

var loginForm = function(target) {

	MV_Overlay.show('/overlay/login_form', true, function() {

		$('target').set('value', target);
		$('login').focus();
		$('Overlay').setStyle('left', '140px');
		$('Overlay').setStyle('top', '260px');

	});

};



///////////////////////////////////////////////////////
// meinverein.js


// Funktionen , Classen
Sortables.implement({
			getClone : function(event, element) {
				if (!this.options.clone)
					return new Element('div').inject(document.body);
				if ($type(this.options.clone) == 'function')
					return this.options.clone.call(this, event, element,
							this.list);
				return element.clone(true).setStyles({
							'margin' : '0px',
							'position' : 'absolute',
							'visibility' : 'hidden',
							'z-index' : '1234567',
							'width' : element.getStyle('width')
						}).inject(this.list).position(element
						.getPosition(element.getOffsetParent()));
			}
		});

// leer elemente für stylende sachen oder funktionelle sachen reingeneriern
/*
 * where = da solls rein (obj) typ = html-ElementenTyp (string) array =
 * classenNamen array (string) pos = wo in elem es injected werden soll (string)
 */
function generateItems(where, typ, array, pos) {
	if (!where)
		return;
	if (array.length > 1) {
		var html = '';
		for (i = 0; i < array.length; i++) {
			html += '<' + typ + ' class="' + array[i] + '"></' + typ + '>';
		}
		var tmpNewWrapper = new Element('span', {
					'class' : 'jsSW',
					'html' : html
				}).inject(where, pos);
	} else {
		if (array.length == 1) {
			var tmpSpan = new Element(typ, {
						'class' : array[0]
					}).inject(where, pos);
			return tmpSpan;
		}
	}
}

// Togglefunktion oder closeFunktion auf ein element generieren
/*
 * elem = da solls rein (obj) typ = html-ElementenTyp (string) cName =
 * classenName (string) pos = wo in elem es injected werden soll (string)
 */
function generateIndicators(where, typ, cName, pos) {
	// falls in dragarea
	var testdrag = true;
	var dragParent = where.getParent('.drag_area');
	var mvParent = where.getParent('#MeinVerein');
	var toggleList = where.getParent('.toggle_list');

	if (dragParent || (!mvParent && !toggleList)) {
		cName = 'close_indicator';
		testdrag = false;
	}

	var tmpIndi = generateItems(where, typ, new Array(cName), pos);

	// normal box toggle
	if (where.getParent().getParent().hasClass('box_header') && testdrag) {
		tmpIndi.addEvent('click', clickToggleBox);
	}
	// for innerToggle
	else {
		if (testdrag) {
			tmpIndi.addEvent('click', clickInnerToggle);
		}
	}
};

// generate onclick events for ajax paginations
/* Function is DEPRECATED */
/*
 * function generateAjaxPaginations(where) {
 * 
 * //use document root when no element supplied if (!where) where = document;
 * 
 * //turn string into element where = $(where);
 * 
 * //generate onclick events for paginations where.getElements('.pagination
 * a[rel=ajax]').each(function(elem){ //if pagination is inside a box, update
 * the .box_wrapper div elem.set('href', elem.get('title'));
 * elem.removeProperty('title'); elem.addEvent('click', ajaxPagination); }); }
 */

// funktion zum updaten des screenlayout + screen functions
// where = main wrapper zum suchen der objekte (obj oder string->selector)
function updateScreenLayout(where) {
	var tmpElem;
	// where testen
	if ($type(where).test('string')) {
		tmpElem = $$(where)[0];
	} else {
		tmpElem = where;
	}

	domwalker.hurry(tmpElem);

	// generateMediaEvents(tmpElem);
}

/*
 * Functions to pass whene overlay is started
 */

// Albumgalleries dazugehörige ausführfunktion-> wird beim starten des Overlays
// mit übergeben
var active_AlbumGalerie;
var startAlbumGalerie = function() {
	active_AlbumGalerie = new AlbumGalerie($('AlbumGalerie'));
	$$('.ajaxfText').each(function(elem) {
				var fTextProposal = new Suggestion(elem);
			});
};

// Function to pass when overlay is started for interests
var startInterestSelection = function() {

	$$('#selectInterests .toggle_indicator').each(function(elem) {
		elem.removeEvents('click');
		elem.addEvent('click', function(e) {
			e.stop();
			var thisToggler = this.getParent('.toggle_item');
			if (!thisToggler.hasClass('closed')) {
				thisToggler.toggleClass('closed');
			} else {
				var tmpLength = thisToggler.getParent().getElements('.closed').length;
				if (tmpLength == 3) {
					thisToggler.getParent().getElements('.toggle_item').each(
							function(elem) {
								if (!elem.hasClass('closed')) {
									elem.toggleClass('closed');
								}
							});
					thisToggler.toggleClass('closed');
				} else {
					thisToggler.toggleClass('closed');
				}
			}
			return false;
		});
	});
};

// Comercial checker, for Layout
function commercialChecker() {
	var MV = $('MeinVerein');
	if (MV) {
		// If topBanner is present
		if ($('topBanner')) {
			MV.addClass('has_topBanner');
			$('MeinVerein').setStyle('padding-top',
					10 + $('topBanner').getStyle('height').toInt());
		}

		// If Skyscraper is present
		if ($('Skyscraper')) {
			MV.addClass('has_Skyscraper');
			$('MeinVerein').setStyle('width',
					1000 + $('Skyscraper').getStyle('width').toInt());
		}
	}
}

// Function to pass when overlay is started for appointment
var startAppointment = function(cName) {
	$('cal-appointmentDetail').getElement('.box').addClass(cName);
	$$('#Overlay .countdown').each(function(elem) {
				var countdown = new Countdown(elem);
			});
	$('Overlay').setStyle('left', '140px');
	$('Overlay').setStyle('top', '80px');
};

/* ADDEVENT FUNCTIONS */
// fTextarea event for 'Schreibe einen Eintrag...'
var textareaFocus = function() {
	if (this.get('value') == 'Schreibe einen Eintrag...')
		this.set('value', '');
}
var textareaBlur = function() {
	if (this.get('value') == '')
		this.set('value', 'Schreibe einen Eintrag...');
}

var textBdFocus = function() {
	if (this.get('value') == 'Straße, Hausnr., PLZ, Ort')
		this.set('value', '');
}
var textBdBlur = function() {
	if (this.get('value') == '')
		this.set('value', 'Straße, Hausnr., PLZ, Ort');
}

// filter event
var filterToggler = function() {
	// filterSlide.cancel();
	var tmp = 1;
	var tmpElem = $('Filter').getElement('.content');
	if (filterIndi) {
		tmp = 0;
		filterIndi = false;
		tmpElem.setStyle('display', 'none');
	} else {
		filterIndi = true;
		// filterSlide.element.setStyle('display' , 'block');
		tmpElem.setStyle('display', 'block');
	}
	// filterSlide.start({opacity : tmp});
	$('Filter').toggleClass('open');
};

// mouseover on media_wrapper
var mW_MouseOver = function() {
	this.getParent().getParent().toggleClass('hover');
	// if(this.getElement('.mw_overlay')){this.getElement('.mw_overlay').setStyles({'display'
	// : 'block', 'opacity' : '0.2'});}
};
// mouseover on media_wrapper
var mW_MouseOut = function() {
	this.getParent().getParent().toggleClass('hover');
	// if(this.getElement('.mw_overlay')){this.getElement('.mw_overlay').setStyles({'display'
	// : 'none', 'opacity' : '0'});}
};
// focus/blur fText/fTextarea
var inputFocusBlur = function() {
	this.getParent().toggleClass('focus');
};
var inputFocusBlur_error = function() {
	this.getParent().toggleClass('error');
	this.toggleClass('error');
	this.removeEvent('change');
};

// toggle functions
var clickToggleBox = function() {
	if (this.getParent('.report')) {
		this.getParent('.report').toggleClass('report_closed');
	}
	this.getParent('.box_wrapper').toggleClass('closed');
};
var clickInnerToggle = function() {
	var tmpElem = this.getParent('fieldset');
	var tmpToggleItem = this.getParent('.toggle_item');
	if (tmpElem && tmpToggleItem.hasClass('legend')) {
		if (tmpElem.hasClass('legendFirst')) {
			this.getParent('.toggle_item').toggleClass('closedFirst');
		}
	}
	this.getParent('.toggle_item').toggleClass('closed');
};

// ajax pagination event
var ajaxPagination = function(element, href) {

	// if one of both parameters is not set
	// assume event was called from an anchor
	if (!element || !href) {
		element = this;
		href = this.get('href');
	}

	// add form fields contained in paginationTarget
	// as post parameters
	var paginationTarget = element.getParent('.paginationTarget');
	var form = element.getParent('form');
	var ajaxData = form ? form.toQueryString() : '';

	var myRequest = new Request({
				data : ajaxData,
				url : href,
				onRequest : function() {
					var el = null;
					if (element.getParent('.infoboxes')) { // update a box in
						// an infobox
						var el = element.getParent('.box_wrapper')
								.getElement('.box_content');
					} else {
						var el = paginationTarget;
					}
					el.setStyles({
								'height' : el.getSize().y,
								'width' : el.getSize().x
							});
					el.set('html', '');
					el.toggleClass('paginationLoading');
				},
				onSuccess : function(htmlResponse, xmlResponse) {
					if (element.getParent('.infoboxes')) { // update a box in
						// an infobox
						var el = element.getParent('.box_wrapper');
						if (el) {
							var temp = new Element('div', {
										'html' : htmlResponse
									});
							var box = temp.getFirst('.box_wrapper');

							if (!box) {
								el.getElements('.ajax-indicator').each(
										function(el) {
											el.destroy()
										});
								return;
							}

							var infoboxArea = el.getParent('.infoboxes');

							if (infoboxArea) {
								infoboxArea.infoboxesInstance.removeItems(el);
							}

							box.replaces(el);
							updateScreenLayout(box);

							if (infoboxArea) {
								infoboxArea.infoboxesInstance.applyEvents(box);
								infoboxArea.infoboxesInstance.addItems(box);
							}
						}
					} else if (paginationTarget) { // update a general ajax
						// area
						var temp = new Element('div', {
									'html' : htmlResponse
								});
						var box = temp.getFirst('.paginationTarget');
						if (box) { // ok
							// call pagination handler if any
							var before = paginationTarget.ajaxPaginationBeforeExchange;
							var after = paginationTarget.ajaxPaginationAfterExchange;

							if (before)
								before.run(box);

							box.replaces(paginationTarget);
							updateScreenLayout(box);

							if (after)
								after.run(box);

							// re-apply callbacks to new box
							box.ajaxPaginationBeforeExchange = before;
							box.ajaxPaginationAfterExchange = after;
						}
					}
				}
			});
	myRequest.send();
	return false;
}

/**
 * VON MICHA B
 * 
 * @param {Object}
 *            event
 */

/** ** Open abuse form overlay */
var openAbuse = function(userId, target_type, target_id) {
	MV_Overlay.show('/abuse/add/' + userId + '/' + target_type + '/'
					+ target_id, true, null);
};
var saveAbuse = function(userId, target_type, target_id, close) {
	// alert(userId+':'+target_type+':'+target_id);
	var myRequest = new Request({
				method : 'post',
				url : '/abuse/save',
				onSuccess : function(htmlResponse, xmlResponse) {
					if (JSON.decode(htmlResponse).result == 'isinvalid') {
						if ($('abuse').getElement('dt[class^=message]') != null)
							$('abuse').getElement('dt[class^=message]')
									.addClass('error');
						else
							$('messageLabel').addClass('error');

						$('message').addClass('error');
					} else if (JSON.decode(htmlResponse).result == 'save') {
						if (close == true)
							MV_Overlay.close();
						else {
							$('message')
									.getParent()
									.getParent()
									.set('html',
											'Ihre Nachricht wurde erfolgreich versendet.');
							$('abuseSubmit').destroy();
						}
					}
				}
			});
	myRequest.send('abuses/user_id=' + userId + '&abuses/target_type='
			+ target_type + '&abuses/target_id=' + target_id
			+ '&abuses/message=' + $('message').value);
};

/** ** Open contact form form overlay */
var openContactForm = function(fromId, toId) {
	MV_Overlay.show('/profile_communication/ajax_compose/' + fromId + '/'
					+ toId, true, null);
};
var sendContactForm = function(fromId, toId) {
	// alert(userId+':'+target_type+':'+target_id);
	var myRequest = new Request({
				method : 'post',
				url : '/profile_communication/ajax_compose/' + fromId + '/'
						+ toId,
				onSuccess : function(htmlResponse, xmlResponse) {
					var results = JSON.decode(htmlResponse);

					if (JSON.decode(htmlResponse).result == 'isinvalid') {
						if (JSON.decode(htmlResponse).subject == 'isinvalid') {
							$('contact_form')
									.getElement('dt[class^=subject_label]')
									.addClass('error');
							$('contact_form').getElement('dt[class^=subject]')
									.addClass('error');
							$('subject').addClass('error');
						}

						if (JSON.decode(htmlResponse).message == 'isinvalid') {
							$('contact_form')
									.getElement('dt[class^=message_label]')
									.addClass('error');
							$('contact_form').getElement('dt[class^=message]')
									.addClass('error');
							$('message').addClass('error');
						}
					} else if (JSON.decode(htmlResponse).result == 'save') {
						MV_Overlay.close();
					}
				}
			});
	myRequest.send('msg/fromId=' + fromId + '&msg/toId=' + toId
			+ '&msg/subject=' + $('subject').value + '&msg/message='
			+ $('message').value);

};

/**
 * ** DEPRECATED Color Theme Radio Selection var colorThemeRadioSelection =
 * function() { if ($('colorThemeRadioSelection')) {
 * $('colorThemeRadioSelection').getElements('li').each(function(item, index) {
 * if (item.getElement('input').checked) {
 * item.getElement('img').setProperty('src', '/img/colorThemeRadio/' +
 * item.getElement('img').getProperty('alt') + '_selected.gif'); }
 * 
 * item.addEvents({ 'mouseover': function(){ if
 * (!item.getElement('input').checked) { //console.log(item);
 * item.getElement('img').setProperty('src', '/img/colorThemeRadio/' +
 * item.getElement('img').getProperty('alt') + '_over.gif'); } }, 'mouseout':
 * function(){ if (!item.getElement('input').checked) {
 * item.getElement('img').setProperty('src', '/img/colorThemeRadio/' +
 * item.getElement('img').getProperty('alt') + '_out.gif'); } }, 'click':
 * function(){ item.getElement('input').setProperty('checked', 'checked');
 * $('colorThemeRadioSelection').getElements('img[src$=_selected.gif]').setProperty('src',
 * '/img/colorThemeRadio/' +
 * $('colorThemeRadioSelection').getElements('img[src$=_selected.gif]').getProperty('alt') +
 * '_out.gif'); item.getElement('img').setProperty('src',
 * '/img/colorThemeRadio/' + item.getElement('img').getProperty('alt') +
 * '_selected.gif'); } }); }); } };
 */
/** ** Rating im Album */
var albumRating = function() {
	if ($('albumRating')) {
		var form = $('albumRating').getElement('form');
		form.set('send', {
					url : form.getProperty('action'),
					method : 'post',
					onSuccess : function(responseText, responseXML) {
						if (JSON.decode(responseText).result == 'save') {
							form.getParent().getParent().getPrevious()
									.destroy();
							form.getParent().getParent().destroy();
							$('overallRating')
									.set(
											'html',
											'Durchschnittliche Bewertung: '
													+ JSON.decode(responseText).overallRating);
							$('overallRating').setStyle('display', 'block');
							var ratingCountHtml = $('ratingCount').get('html');
							var tmpSplit = ratingCountHtml.split(": ");
							$('ratingCount').set(
									'html',
									'Anzahl der Bewertungen: '
											+ (parseInt(tmpSplit[1]) + 1));
						}
					}

				});
		form.send();
	}
	return false;
};

/** ** Rating im Bericht */
var reportsRating = function(id) {
	if ($('reportRating' + id)) {
		var form = $('reportRating' + id);
		form.set('send', {
					url : form.getProperty('action'),
					method : 'post',
					onSuccess : function(responseText, responseXML) {
						if (JSON.decode(responseText).result == 'save') {
							form.getParent().setStyle('display', 'none');
							$('overallRating' + id).set('html',
									JSON.decode(responseText).overallRating);
							var ratingCountHtml = $('ratingCount' + id)
									.get('html');
							$('ratingCount' + id).set('html',
									(parseInt(ratingCountHtml) + 1));
						}
					}

				});
		form.send();
	}
	return false;
};

/** ** Position im Verein bearbeiten */

var editUserPosition = function(associationId) {

	var afterLoad = function() {
		initializeUserPositionInputs();
		$('Overlay').setStyle('top', '120px');
		$('Overlay').setStyle('left', '100px');
	};
	MV_Overlay.show('/overlay/edit_user_position/' + associationId, true,
			afterLoad, new Array());
};

/** ** Freunde einladen */

var inviteFriend = function(options) {
	$('invite_email').blur();
	var email = $('invite_email').get('value');
	var type = $('invite_type').get('value');
	var id = $('invite_id').get('value');
	var assocId = $('invite_assocId').get('value');

	var myRequest = new Request({
				method : 'post',
				url : options.url,
				data : {
					'invite/email' : email,
					'invite/type' : type,
					'invite/id' : id,
					'invite/assocId' : assocId
				},
				onSuccess : function(htmlResponse, xmlResponse) {
					var afterLoad = function() {
					};

					var afterLoad = function() {
						$('Overlay').setStyle('left', '180px');
						$('Overlay').setStyle('top', '200px');
					};

					var result = JSON.decode(htmlResponse);
					if (result.result == 'success') {
						MV_Overlay.show('/overlay/invite_friend/success/'
										+ options.type, true, afterLoad);
						$('invite_email').set('value', '');
					} else {
						MV_Overlay.show('/overlay/invite_friend/failure/'
										+ options.type + '/' + result.error,
								true, afterLoad);
					}
				}
			});

	myRequest.send();

};

/* MICHA: Notizen Übersicht */
var openNotices = function(userId) {
	if ($defined(userId)) {
		MV_Overlay.show('/friends/get_notices/' + userId, true, function() {
					$('Overlay').setStyle('left', '140px');
					$('Overlay').setStyle('top', '120px');
				});
	}
};

/* MICHA: Vereinsfreundschaften schließen */
var openAssocFriendship = function(assocId) {
	if ($defined(assocId)) {

		var pushArround = new function() {
			$('Overlay').setStyle('top', '140px');
			$('Overlay').setStyle('left', '140px');
		}
		MV_Overlay.show('/ajax/assoc_friendship/' + assocId, true, pushArround);
	}
};

var sendAssocFriendship = function() {
	if ($('twin_association')) {
		var form = $('twin_association');
		form.set('send', {
			url : '/ajax/save_assoc_friendship',
			method : 'post',
			onSuccess : function(responseText, responseXML) {
				if (JSON.decode(responseText).result == 'save') {
					var form = $('twin_association');
					form.getElement('.box_wrapper').setStyle('height',
							form.getElement('.box_wrapper').getSize().y)
					form
							.getElement('.formContent')
							.set(
									'html',
									'<p class="formDescription_full">Deine Vereinsfreundschaftsanfrage wurde erfoglreich übermittelt.</p>');
					$('twin_submit').getParent().setStyle('display', 'none');
					$('twin_cancel').set('html', 'Schließen');
				}
			}

		});
		form.send();
	}
};

/**
 * sets a flag field to affirm and submits the form
 * 
 * @author Stefan Michalsky
 * @param String
 *            formId id of the form tag
 * @param String
 *            affirmId id of the hidden input that stores the flag
 */
var affirmMedia = function(formId, affirmId) {
	affirmField = $(affirmId);
	form = $(formId);

	if (affirmField && form) {
		affirmField.value = 'affirm';
		form.submit();
	}
}

/**
 * sets a flag field to decline and submits the form
 * 
 * @author Stefan Michalsky
 * @param String
 *            formId id of the form tag
 * @param String
 *            affirmId id of the hidden input that stores the flag
 */
var declineMedia = function(formId, affirmId) {
	affirmField = $(affirmId);
	form = $(formId);

	if (affirmField && form) {
		affirmField.value = 'decline';
		form.submit();
	}
}

/**
 * sets a flag field to lock and submits the form
 * 
 * @author Stefan Michalsky
 * @param String
 *            formId id of the form tag
 * @param String
 *            affirmId id of the hidden input that stores the flag
 */
var lockMedia = function(formId, affirmId) {
	affirmField = $(affirmId);
	form = $(formId);

	if (affirmField && form) {
		affirmField.value = 'lock';
		form.submit();
	}
}

/**
 * set all checkboxes checked
 * 
 * @author Stefan Michalsky
 */
var selectAllCheckboxes = function() {
	$$('.fCheck').each(function(item) {
				item.checked = true;
			});
}

/**
 * set all checkboxes unchecked
 * 
 * @author Stefan Michalsky
 */
var unselectAllCheckboxes = function() {
	$$('.fCheck').each(function(item) {
				item.checked = false;
			});
}

var openOverlayForAlternativeInterest = function() {
	MV_Overlay.show('/ajax/get_interests/', true);
}

var insertAlternativeInterest = function() {
	id = $('alternative/selectField').options[$('alternative/selectField').selectedIndex].value;
	$('alternative/id').value = id;

	var newSubmit = new Element('input', {
				type : 'hidden',
				name : 'submit/decline',
				value : 'decline'
			});
	newSubmit.inject($('interestsForm'));

	$('interestsForm').submit();
}

var jumpToPinboard = function() {
	var pinboardAnker = $('anker_associationPinboard');

	if (pinboardAnker) {
		var posOA = pinboardAnker.getPosition();
		console.log(posOA);
		var body = document.getElementsByTagName('body')[0];
		console.log(body);
		body.scrollTo(0, posOA.y);
	}
}

var acceptInvitation = function(elem) {
	if (elem.get('html') == 'Annehmen') {
		MV_Overlay.show('/overlay/accept_invite/' + elem.get('userId') + '/'
						+ elem.get('assocId'), true, function() {

					$('Overlay').setStyle('left', '140px');
					$('Overlay').setStyle('top', '260px');

				});
	} else {
		var userId = elem.get('userId');
		var assocId = elem.get('assocId');
		MV_Overlay.show(false, true, function() {
			$('Overlay').setStyle('left', '140px');
			$('Overlay').setStyle('top', '260px');
			return ('<div class="box_wrapper static small " ><div class="box"><div class="box_content">Einladung wirklich ablehnen ?<br><b><a href="#" onClick="declineInvitation('+assocId+','+userId+'); return false;">Ja</a></b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b><a href="#" onClick="MV_Overlay.close(); return false;">Nein</a></b></div></div>');
		});

	}
};

var declineInvitation = function(assocId, userId) {
	MV_Overlay.show('/overlay/decline_invite/' + userId + '/'
					+ assocId, true, function() {
				$('Overlay').setStyle('left', '140px');
				$('Overlay').setStyle('top', '260px');
			});
}

var clearInvitation = function(assocId, userId) {
	$(assocId + '' + userId).set('html', '');
}


///////////////////////////////////////////////////////
// meinverein_stephan.js

//DEPRECATED
//THis function is used now in domwalker
function generateMediaEvents(elem)
{
	// Open album buttons (gallery overlay)
	elem.getElements('.album .media_wrapper a, .album .view a').each(function(el)
	{
		var mcard = el.getParent('.mcard');
		if (mcard)
		{
			if (!mcard.albumId)
			{
				mcard.albumId = mcard.get('title');
				mcard.removeProperty('title');
			}
			el.albumId = mcard.albumId;
			el.removeEvents('click');
			el.addEvent('click', openAlbum);
		}
	});

	//Open media buttons (gallery overlay)
	elem.getElements('.video .media_wrapper a, .video .view a, .image .media_wrapper a, .image .view a').each(function(el) {
		var mcard = el.getParent('.mcard');
		if (mcard) {
			if (!mcard.mediaId) {
				mcard.mediaId = mcard.get('title');
				mcard.removeProperty('title');
			}

			el.mediaId = mcard.mediaId;
			el.removeEvents('click');
			el.addEvent('click', openMedia);
		}

			var vcard = el.getParent('.mcard .video');

			if (vcard)
			{
				if (!vcard.mediaId)
				{
					vcard.mediaId = vcard.get('title');
					vcard.removeProperty('title');
				}

				el.vediaId = vcard.mediaId;
				el.removeEvents('click');
				el.addEvent('click', openVideo);
			}
		}
	);



	//Offer friendship buttons
		elem.getElements('.vcard .offer_friendship a').each(function(el)
		{
		var vcard = el.getParent('.vcard');
				if (vcard)
				{
						if (!vcard.userId)
						{
				vcard.userId = vcard.get('title');
				vcard.removeProperty('title');
			}
			el.userId = vcard.userId;
			el.removeEvents('click');
			el.addEvent('click', offerFriendship);
		}
	});
}

function generateInfoboxes()
{
	//load profile visitors
	var profileVisitors = $('ib-profile-visitors');
	if (profileVisitors) {
		profileVisitors.set('load', {
			'onSuccess'	:	function(result) {

				// copy class and html content to outer box wrapper (fix for ie6)
				this.set('class', this.getFirst().get('class'));
				this.set('html', this.getFirst().get('html'));

				updateScreenLayout(this);

			}.bind(profileVisitors)
		});
		profileVisitors.load('/infobox/profile_visitors/'+globalNumber);
	}

	//load networknews
	var networkNews = $('ib-network-news');
		if (networkNews)
		{
				networkNews.set('load',
				{
						'onSuccess': function()
						{

						// copy class and html content to outer box wrapper (fix for ie6)
						this.set('class', this.getFirst().get('class'));
						this.set('html', this.getFirst().get('html'));

						updateScreenLayout(this);
						}.bind(networkNews)
		});
		networkNews.load('/infobox/network_news/'+globalNumber);
	}

	//load assoc networknews
	var assocNetworkNews = $('ib-assoc-network-news');
	if (assocNetworkNews) {
		var assocId = assocNetworkNews.getFirst().get('html');
		assocNetworkNews.set('load', {
			'onSuccess'	:	function() {

				// copy class and html content to outer box wrapper (fix for ie6)
				this.set('class', this.getFirst().get('class'));
				this.set('html', this.getFirst().get('html'));

				updateScreenLayout(this);
			}.bind(assocNetworkNews)
		});
		assocNetworkNews.load('/infobox/association_network_news/'+globalNumber+'/'+assocId);
	}

	//load assoc info
	var assocInfo = $('ib-assoc-info');
	if (assocInfo) {
		var assocId = assocInfo.getFirst().get('html');
		assocInfo.set('load', {
			'onSuccess'	:	function() {

				// copy class and html content to outer box wrapper (fix for ie6)
				this.set('class', this.getFirst().get('class'));
				this.set('html', this.getFirst().get('html'));

				updateScreenLayout(this);
			}.bind(assocInfo)
		});
		assocInfo.load('/infobox/association_info/'+globalNumber+'/'+assocId);
	}


	//load newest assoc forum entries
	var assocForumEntries = $('ib-assoc-new-forum-entries');
	if (assocForumEntries) {
		var assocId = assocForumEntries.getFirst().get('html');
		assocForumEntries.set('load', {
			'onSuccess'	:	function() {

				// copy class and html content to outer box wrapper (fix for ie6)
				if (this.getFirst())
				{
					this.set('class', this.getFirst().get('class'));
					this.set('html', this.getFirst().get('html'));
				}
				updateScreenLayout(this);
			}.bind(assocForumEntries)
		});
		assocForumEntries.load('/infobox/association_new_forum_entries/'+globalNumber+'/'+assocId);
	}

	//load latest assoc profile visitors
	var assocProfileVisitors = $('ib-assoc-profile-visitors');
	if (assocProfileVisitors) {
		var assocId = assocProfileVisitors.getFirst().get('html');
		assocProfileVisitors.set('load', {
			'onSuccess'	:	function() {

				// copy class and html content to outer box wrapper (fix for ie6)
				this.set('class', this.getFirst().get('class'));
				this.set('html', this.getFirst().get('html'));

				updateScreenLayout(this);
			}.bind(assocProfileVisitors)
		});
		assocProfileVisitors.load('/infobox/association_profile_visitors/'+globalNumber+'/'+assocId);
	}


	//load latest assoc medias
	var assocMedia = $('ib-assoc-media');
	if (assocMedia) {
		var assocId = assocMedia.getFirst().get('html');
		assocMedia.set('load', {
			'onSuccess'	:	function() {

				// copy class and html content to outer box wrapper (fix for ie6)
				this.set('class', this.getFirst().get('class'));
				this.set('html', this.getFirst().get('html'));

				updateScreenLayout(this);
			}.bind(assocMedia)
		});
		assocMedia.load('/infobox/association_media/'+globalNumber+'/'+assocId);
	}

	//load latest assoc events
	var assocEvents = $('ib-assoc-events');
	if (assocEvents) {
		var assocId = assocEvents.getFirst().get('html');
		assocEvents.set('load', {
			'onSuccess'	:	function() {

				// copy class and html content to outer box wrapper (fix for ie6)
				this.set('class', this.getFirst().get('class'));
				this.set('html', this.getFirst().get('html'));

				updateScreenLayout(this);
			}.bind(assocEvents)
		});
		assocEvents.load('/infobox/association_events/'+globalNumber+'/'+assocId);
	}

	//load latest assoc birthdays
	var assocBirthdays = $('ib-assoc-birthdays');
	if (assocBirthdays) {
		var assocId = assocBirthdays.getFirst().get('html');
		assocBirthdays.set('load', {
			'onSuccess'	:	function() {

				// copy class and html content to outer box wrapper (fix for ie6)
				this.set('class', this.getFirst().get('class'));
				this.set('html', this.getFirst().get('html'));

				updateScreenLayout(this);
			}.bind(assocBirthdays)
		});
		assocBirthdays.load('/infobox/association_birthdays/'+globalNumber+'/'+assocId);
	}

	//load assoc online users
	var assocOnlineUsers = $('ib-assoc-who-is-online');
	if (assocOnlineUsers) {
		var assocId = assocOnlineUsers.getFirst().get('html');
		assocOnlineUsers.set('load', {
			'onSuccess'	:	function() {

				// copy class and html content to outer box wrapper (fix for ie6)
				this.set('class', this.getFirst().get('class'));
				this.set('html', this.getFirst().get('html'));

				updateScreenLayout(this);
			}.bind(assocOnlineUsers)
		});
		assocOnlineUsers.load('/infobox/association_whos_online/'+globalNumber+'/'+assocId);
	}

	//load assoc reports
	var assocReports = $('ib-assoc-reports');
	if (assocReports) {
		var assocId = assocReports.getFirst().get('html');
		assocReports.set('load', {
			'onSuccess'	:	function() {

				// copy class and html content to outer box wrapper (fix for ie6)
				this.set('class', this.getFirst().get('class'));
				this.set('html', this.getFirst().get('html'));

				updateScreenLayout(this);
			}.bind(assocReports)
		});
		assocReports.load('/infobox/association_reports/'+globalNumber+'/'+assocId);
	}

	//load business directory within a map
	var assocMap = $('ib-assoc-map');
	if (assocMap) {
		var assocId = assocMap.getFirst().get('html');
		assocMap.set('load', {
			'onSuccess'	:	function() {

				// copy class and html content to outer box wrapper (fix for ie6)
				this.set('class', this.getFirst().get('class'));
				this.set('html', this.getFirst().get('html'));

				updateScreenLayout(this);
			}.bind(assocMap)
		});
		assocMap.load('/infobox/association_business_directory/'+assocId);
	}

	var els = $$('.infoboxes').each(function(elem) {

				var myInfoboxes = new InfoboxSortables(elem, globalNumber,
				{
			clone: true,
			handle : '.box_header',
			opacity: 0.5
		});

		//save instance to div
		elem.infoboxesInstance = myInfoboxes;

		//infobox add buttons
		$$('.drag_area .drag_selection a.addInfobox').each(function(el)
		{
			el.addEvent('click', function(event)
			{
				var li = this.getParent('li');
				var id = li.get('id').replace('add_', '');
				myInfoboxes.addInfobox(id);
				event.stop();
				return false;
			});
		});

		//infobox remove buttons
		$$('.drag_area .drag_selection a.removeInfobox').each(function(el)
		{
			el.addEvent('click', function(event)
			{
				var li = this.getParent('li');
				var id = li.get('id').replace('add_', '');
				myInfoboxes.removeInfobox(id);
				event.stop();
				return false;
			});
		});
	});
}

/**
 * @class: InfoboxSortables
 * @author: Stephan Unverwerth, Farbwahl
 *
 * Class for infobox area, sends ajax request to save new box arrangement
 * whenever an infobox is moved, added or closed
 */
var InfoboxSortables = new Class(
{
	Extends: Sortables,

		initialize: function(element, userId, options)
		{
		this.userId = userId;

		this.list = $(element);
		$(element).getChildren('.box_wrapper').each(this.applyEvents.bind(this));
		options.onComplete = this.saveArrangement;
		this.parent(element, options);
		this.addFiller();
		this.loadInitialBoxes();
	},

		loadInitialBoxes: function()
		{
				this.list.getChildren().each(function(el)
				{
			if (el.hasClass('loadme'))
				this.addInfobox(el.get('title'), el);
				}.bind(this));
	},

	//overridden function to prevent dropping on filler elements
		insert: function(dragging, element)
		{
		if (element.hasClass('filler') || element.hasClass('waitbox'))
			return;
		else
			this.parent(dragging, element);
	},

	//adds functionality to passed box
		applyEvents: function(box)
		{

		var closeIndicator = box.getElement('.close_indicator');
			if (closeIndicator)
			{
				closeIndicator.addEvent('click', function(e)
				{
					e.stop();
					this.removeInfobox(closeIndicator.getParent('.box_wrapper').getProperty('id'));
				}.bind(this));
			}
		},

	//adds an infobox to this sortable list
		addInfobox: function(boxId, target)
		{

		if ($(boxId))
			return false;

				var myRequest = new Request(
				{
	url		: '/ajax/get_infobox/'+this.userId+'/'+boxId,

						onRequest: function()
						{

								if (!target)
										this.removeFiller();

	 myRequest.waitBox = target || this.createWaitBox(boxId);
								if (!target)
								{
					myRequest.waitBox.inject(this.list, 'bottom');
					this.addFiller();
				}

						}
.bind(this)            ,

						onSuccess: function(htmlResponse, xmlResponse)
						{

								var temp = new Element('div',
								{
					'html'	: htmlResponse
				});

				var box = temp.getFirst();

								if (box)
								{
					updateScreenLayout(box);
					this.applyEvents(box);
					box.replaces(myRequest.waitBox);
					myRequest.waitBox.destroy();
					this.addItems(box);
										if (!target)
												this.saveArrangement();

					var toggleBox = $('add_'+boxId);
										if (toggleBox)
										{
						toggleBox.removeClass('selectable_box');
						toggleBox.addClass('static_box');
												toggleBox.getElements('.addInfobox').each(function(el)
												{
														el.addClass('inactive')
												});
												toggleBox.getElements('.removeInfobox').each(function(el)
												{
														el.removeClass('inactive')
												});
					}
				}
								else
								{
										if (!target)
										{
		 	this.removeFiller();
						myRequest.waitBox.destroy();
		 	this.addFiller();
		 }
				}

						}
.bind(this)            ,

						onFailure: function(xhr)
						{

								if (!target)
								{
					this.removeFiller();
					myRequest.waitBox.destroy();
					this.addFiller();
				}
						}
.bind(this)
	});

	myRequest.send();
	return true;
	},

	//removes an infobox from this sortable list
		removeInfobox: function(id)
		{

		var element = $(id);
				if (element)
				{
			var toggleBox = $('add_'+id);
						if (toggleBox)
						{
				toggleBox.addClass('selectable_box');
				toggleBox.removeClass('static_box');
								toggleBox.getElements('.addInfobox').each(function(el)
								{
										el.removeClass('inactive')
								});
								toggleBox.getElements('.removeInfobox').each(function(el)
								{
										el.addClass('inactive')
								});
			}
			this.removeFiller();
			this.removeItems(element);
			element.destroy();
			this.saveArrangement();
			this.addFiller();
			return true;
		}
		return false;
	},

	//removes the filler from the list
		removeFiller: function()
		{

		//remove all fillers
				this.list.getElements('.filler').each(function(el)
				{
			el.destroy();
		});
	},

	//adds a filler to the sortables list if the last row is not filled
		addFiller: function()
		{
		//number of elements in last row
		var lastRow = (this.list.getChildren().length)%3;
		var url = '';
		var fillerClass = '';
				if (lastRow == 1)
				{ //add a big filler
			url = '/infobox/big_filler';
		}
				else
						if (lastRow == 2)
						{ //add a small filler
			url = '/infobox/small_filler';
			fillerClass = ' small';
		}
						else
						{
			return;
		}

				var myRequest = new Request(
				{
	url		: url,

						onRequest: function()
						{

								myRequest.tempBox = new Element('div',
								{
					'class'	: 'box_wrapper filler'+fillerClass
				});

				myRequest.tempBox.inject(this.list, 'bottom');
						}
.bind(this)            ,

						onSuccess: function(htmlResponse, xmlResponse)
						{

								var temp = new Element('div',
								{
					'html'	: htmlResponse
				});

				var box = temp.getElement('.box_wrapper');
								if (box)
								{
					box.replaces(myRequest.tempBox);
				}
						}
.bind(this)
	});

	myRequest.send();
	},

	//saves the arrangement via ajax
		saveArrangement: function()
		{
				var myRequest = new Request(
				{
	url		: '/ajax/save_infoboxes/'+this.userId
	});

				var data = this.serialize(null, function(el, index)
				{
						if (el.hasClass('waitbox'))
								return null;
	var id = el.get('id');
	if (id)
	return 'Infobox/'+index+'='+el.get('id');
	else
	 return null;
	}).join('&');

	if (data.length == 0)
	data = 'Empty/value=1';

				if (data != this.lastDataSent)
				{
		myRequest.send(data);
		this.lastDataSent = data;
		}
	},

	//returns a temporary box to show the user that an
	//ajax request is in progress
		createWaitBox: function(boxId)
		{
		return new Element('div', {
			'class'	: 'box_wrapper small waitbox',
			'id'	: boxId
		}).adopt(new Element('div', {
			'class'	: 'box',
			'html'	: '<img src="/img/tmpImages/ajax-loader.gif" alt="wird geladen..."/>'
		}));
	}
});

/**
 *
 */
/*--- Fancy Upload stuff ---*/

/**
 * Fx.ProgressBar
 *
 * @version		1.0
 *
 * @license		MIT License
 *
 * @author		Harald Kirschner <mail [at] digitarald [dot] de>
 * @copyright	Authors
 */
Fx.ProgressBar = new Class(
{

	Extends: Fx,

		options:
		{
		text: null,
		transition: Fx.Transitions.Circ.easeOut,
		link: 'cancel'
	},

		initialize: function(element, options)
		{
		this.element = $(element);
		this.parent(options);
		this.text = $(this.options.text);
		this.set(0);
	},

		start: function(to, total)
		{
		return this.parent(this.now, (arguments.length == 1) ? to.limit(0, 100) : to / total * 100);
	},

		set: function(to)
		{
		this.now = to;
		this.element.setStyle('width', (to) + '%');
				if (this.text)
						this.text.set('text', Math.round(to) + '%');
		return this;
	}

});

/**
 * Swiff.Uploader - Flash FileReference Control
 *
 * @version		1.2
 *
 * @license		MIT License
 *
 * @author		Harald Kirschner <mail [at] digitarald [dot] de>
 * @copyright	Authors
 */
Swiff.Uploader = new Class(
{

	Extends: Swiff,

	Implements: Events,

		options:
		{
		path: 'Swiff.Uploader.swf',
		multiple: true,
		queued: true,
		typeFilter: null,
		url: null,
		method: 'post',
		data: null,
		fieldName: 'Filedata',
		target: null,
		height: '100%',
		width: '100%',
		callBacks: null
	},

	initialize: function(options)
	{
		//read session id
		this.sessionID = Cookie.read('PHPSESSID');

		if (Browser.Plugins.Flash.version < 9)
			return false;

		this.setOptions(options);

		var callBacks = this.options.callBacks || this;
		if (callBacks.onLoad)
			this.addEvent('onLoad', callBacks.onLoad);
		if (!callBacks.onBrowse)
		{
			callBacks.onBrowse = function()
			{
				return this.options.typeFilter;
			}
		}

		var prepare = {}, self = this;
		['onBrowse', 'onSelect', 'onAllSelect', 'onCancel', 'onBeforeOpen', 'onOpen', 'onProgress', 'onComplete', 'onError', 'onAllComplete'].each(function(index)
		{
			var fn = callBacks[index] || $empty;
			prepare[index] = function()
			{
				self.fireEvent(index, arguments, 10);
				return fn.apply(self, arguments);
			};
		});

		prepare.onLoad = this.load.create(
		{
			delay: 10,
			bind: this
		});

		this.options.callBacks = prepare;

		var path = this.options.path;
		if (!path.contains('?'))
		path += '?noCache=' + $time(); // quick fix
		this.parent(path);

		var scroll = window.getScroll();
		this.box = new Element('div',
		{
			styles:
			{
				position: 'absolute',
				visibility: 'visible',
				zIndex: 9999,
				overflow: 'hidden',
				height: 15,
				width: 15,
				top: scroll.y,
				left: scroll.x
			}
		});
		this.inject(this.box);
		this.box.inject(document.body);

		this.mouseover = function()
		{
			this.reposition();
		}.bind(this);

		this.mouseout = function()
		{
			this.box.setStyles(
			{
				width: 0,
				height: 0
			});
		}.bind(this);

		this.box.addEvent('mouseout', this.mouseout);
		this.changeTarget($(this.options.target));
		return this;
	},

		load: function()
		{
		this.remote('register', this.instance, this.options.multiple, this.options.queued);
		this.fireEvent('onLoad');
	},

		changeTarget: function(target)
		{

				if (target && this.target != target)
				{

						if (this.target)
						{
				this.target.removeEvent('mouseover', this.mouseover);
			}

			this.target = target;

						if (this.target)
						{
				this.target.addEvent('mouseover', this.mouseover);
			}

			this.reposition();
		}
	},

		reposition: function(target)
		{
		var pos = this.target.getCoordinates(this.box.getOffsetParent());
		this.box.setStyles(pos);
	},

	/*
	Method: browse
		Open the file browser.
	*/
		browse: function(typeFilter)
		{
		this.options.typeFilter = $pick(typeFilter, this.options.typeFilter);
		return this.remote('browse');
	},

	/*
	Method: upload
		Starts the upload of all selected files.
	*/
		upload: function(options)
		{

		var current = this.options;
				options = $extend(
				{
						"data": current.data,
						"url": current.url,
						"method": current.method,
						"fieldName": current.fieldName
				}, options);
				if ($type(options.data) == 'element')
						options.data = $(options.data).toQueryString();

		//append session id to post data
		if (!options.data || options.data.length == 0)
			options.data = 'SESSID='+this.sessionID;
		else
			options.data += '&SESSID='+this.sessionID;

		return this.remote('upload', options);
	},

	/*
	Method: removeFile
		For multiple uploads cancels and removes the given file from queue.
	Arguments:
		name - (string) Filename
		name - (string) Filesize in byte
	*/
		removeFile: function(file)
		{
				if (file)
						file =
						{
								name: file.name,
								size: file.size
						};
		return this.remote('removeFile', file);
	},

	/*
	Method: getFileList
		Returns one Array with with arrays containing name and size of the file.
	Returns:
		(array) An array with files
	*/
		getFileList: function()
		{
		return this.remote('getFileList');
	},

		sizeToKB: function(size)
		{
		var unit = 'B';
				if ((size / 1048576) > 1)
				{
			unit = 'MB';
			size /= 1048576;
				}
				else
						if ((size / 1024) > 1)
						{
			unit = 'kB';
			size /= 1024;
		}
		return size.round(1) + ' ' + unit;
	}
});



/**
 * MultipleImageUpload - Upload for image upload page, based on digitaralds FancyUpload2
 *
 */
var MultipleImageUpload = new Class(
{

	Extends: Swiff.Uploader,

		options:
		{
		limitSize: false,
		limitFiles: null,
		instantStart: false,
		allowDuplicates: false,

		validateFile: function(file) // provide a function that returns true for valid and false for invalid files.
		{
			var parts = file.name.split('.');
			if (parts.length > 2)
				return false;

			var type = parts.pop().toLowerCase();
			var types = ['jpg', 'jpeg', 'gif', 'png'];

			return types.contains(type);
		},

		debug: false,

		fileInvalid: function(file, errors) { // called for invalid files with error stack as 2nd argument
			if (!this.errorShown) {
				if (errors.contains('size')) {
					new MessageBox('/overlay/message_box/400/'+file.name);
					this.errorShown = true;
				}
				else if (errors.contains('custom')) {
					new MessageBox('/overlay/message_box/401/'+file.name);
					this.errorShown = true;
				}
			}
		},

		fileCreate: null, // creates file element after select
		fileUpload: null, // called when file is opened for upload, allows to modify the upload options (2nd argument) for every upload
		fileComplete: null, // updates the file element to completed state and gets the response (2nd argument)
		fileRemove: null // removes the element
		/**
		 * Events:
		 * onBrowse, onSelect, onAllSelect, onCancel, onBeforeOpen, onOpen, onProgress, onComplete, onError, onAllComplete
		 */
	},

		errors: 0,

		initialize: function(list, options)
		{
		this.list = $(list);

		this.files = [];

				if (options.callBacks)
				{
			this.addEvents(options.callBacks);
			options.callBacks = null;
		}

		this.totalProgress = $$('.totalUpload .middle')[0];
		this.totalText = $$('.totalUpload .byteCount')[0];

		this.partialProgress = $$('.partialUpload .middle')[0];
		this.partialText = $$('.partialUpload .byteCount')[0];

		this.currentFileName = $$('dt.partialUpload')[0];

		this.totalProgressFx = new Fx.ProgressBar(this.totalProgress);
		this.partialProgressFx = new Fx.ProgressBar(this.partialProgress);

		if ($('uploadImagesAlbumId'))
			this.albumId = $('uploadImagesAlbumId').get('value');

		var editButton = $('afterUploadEditAlbum');
				editButton.addEvent('click', function(event)
				{
			event.stop();
			return false;
		});

		this.parent(options);
		this.render();
	},

		render: function()
		{
	},

		onLoad: function()
		{
		this.log('Uploader ready!');
	},

		onBeforeOpen: function(file, options)
		{
			this.log('Initialize upload for "{name}".', file);
			var fn = this.options.fileUpload;
			var obj = (fn) ? fn.call(this, this.getFile(file), options) : options;
			var data = obj.data;
			file = this.getFile(file);

			var title = file.element.getElement('.mcard_title input').get('value');
			var tags  = file.element.getElement('.mcard_catchwords input').get('value');
			var desc  = file.element.getElement('.mcard_description input').get('value');

			var description = '';
			if (title.length > 0)
					description += '&media/title=' + escape(title);
			if (tags.length > 0)
					description += '&media/tags=' + escape(tags);
			if (desc.length > 0)
					description += '&media/description=' + escape(desc);

			if (!obj.data)
				obj.data = "";

			obj.data += description;
			if (this.albumId)
				obj.data += ('&albums/id=' + escape(this.albumId));

			return obj;
		},

		onOpen: function(file, overall)
		{
		this.log('Starting upload "{name}".', file);
		file = this.getFile(file);
		file.element.addClass('file-uploading');

		this.currentFileName.set('html', file.name);
		this.partialProgressFx.cancel().set(0);
				this.partialText.set('html', '<strong>0% | {sent}</strong> / {total}'.substitute(
				{
			'sent'		: this.sizeToKB(current.bytesLoaded),
			'total'		: this.sizeToKB(current.bytesTotal)
		}));
	},

		onProgress: function(file, current, overall)
		{

		this.currentFileName.set('html', file.name);

		var percent = Math.round(100*overall.bytesLoaded/overall.bytesTotal);
		this.totalProgressFx.start(overall.bytesLoaded, overall.bytesTotal);
				this.totalText.set('html', '<strong>{percent}% | {sent}</strong> / {total}'.substitute(
				{
			'percent'	: percent,
			'sent'		: this.sizeToKB(overall.bytesLoaded),
			'total'		: this.sizeToKB(overall.bytesTotal)
		}));

		percent = Math.round(100*current.bytesLoaded/current.bytesTotal);
		this.log(file.name+': '+percent);
		this.partialProgressFx.start(current.bytesLoaded, current.bytesTotal);
				this.partialText.set('html', '<strong>{percent}% | {sent}</strong> / {total}'.substitute(
				{
			'percent'	: percent,
			'sent'		: this.sizeToKB(current.bytesLoaded),
			'total'		: this.sizeToKB(current.bytesTotal)
		}));
	},

		onSelect: function(file, index, length)
		{
		var errors = [];
				if (this.options.limitSize && (file.size > this.options.limitSize))
						errors.push('size');
				if (this.options.limitFiles && (this.countFiles() >= this.options.limitFiles))
						errors.push('length');
				if (!this.options.allowDuplicates && this.getFile(file))
						errors.push('duplicate');
				if (!this.options.validateFile.call(this, file, errors))
						errors.push('custom');
				if (errors.length)
				{
			var fn = this.options.fileInvalid;
						if (fn)
								fn.call(this, file, errors);
			return false;
		}
		(this.options.fileCreate || this.fileCreate).call(this, file);
		this.files.push(file);
		return true;
	},

		onAllSelect: function(files, current, overall) {
			this.errorShown = false;
			this.log('Added ' + files.length + ' files, now we have (' + current.bytesTotal + ' bytes).', arguments);
			this.updateOverall(current.bytesTotal);
			if (this.files.length && this.options.instantStart)
				this.upload.delay(10, this);
			if (current.filesTotal > 0)	{
				$('imageUploadSelectedStatus').set('html', 'Du hast <strong>{count} Bilder</strong> ausgewählt. Möchtest Du weitere Bilder hinzufügen oder Deine gewählten Dateien für diese Album hochladen?'.substitute(
				{
						'count': current.filesTotal
				}));
				if (!this.firstStep)
						{
				this.firstStep=true;

				var addImages = $('addImages');
				this.changeTarget(addImages);
				addImages.removeClass('inactive');
				addImages.getParent().removeClass('inactive');
				addImages.addEvent('click', function()
						{
							this.browse();
							return false;
						}.bind(this));

				var selectImages = $('selectImages');
				selectImages.removeEvents();
				selectImages.addEvent('click', function()
				{
						return false;
				});
				selectImages.addClass('inactive');
				selectImages.getParent().addClass('inactive');

				var uploadImages = $('uploadImages');
				uploadImages.removeClass('inactive');
				uploadImages.getParent().removeClass('inactive');
								uploadImages.addEvent('click', function()
								{
					var step1 = $('imageUpload').getElement('.uploadImagesStep1');
					var step2 = $('imageUpload').getElement('.uploadImagesStep2');
					step1.addClass('closed closedFirst');
					step2.removeClass('inactive');
					step2.removeClass('closed');

					var startUpload = $('startUpload');
					startUpload.addEvent('click', function()
					{
						var albumTitle = $('albumTitle');

						if (albumTitle)
								albumTitle = albumTitle.get('value');
						else
								albumTitle = 'Album';

						var albumVisibility = 0;
						$('imageUpload').getElements('input.fRadio').each(function(el)
						{
							if(el.get('checked'))
								albumVisibility = el.get('value');
						});

						var zipcode = $('albumZipcode');
						var city = $('albumCity');
						var tags = $('tags');
						var legalCheck = $('albumsCheck').get('checked');
						var noClickHistory = $('noHistoryForUploadID');
						var error = false;

						//validate tags
						if (tags && tags.get('value').length == 0)
						{
							tags.addClass('error');
							tags.getParent().addClass('error');
							error = true;
						}
						else if (tags)
						{
							tags.removeClass('error');
							tags.getParent().removeClass('error');
						}

						if (!legalCheck)
						{
							$$('label[for="albumsCheck"]')[0].addClass('error');
							error = true;
						}
						else
							$$('label[for="albumsCheck"]')[0].removeClass('error')

						if (albumTitle.length == 0)
						{
							$('albumTitle').addClass('error');
							error = true;
						}
						else
						{
							if ($('albumTitle'))
								$('albumTitle').removeClass('error');
						}

						if (noClickHistory)
							var noClickHistoryValue = noClickHistory.get('value');
						else
							var noClickHistoryValue = 0;

						if (!error)
						{
							this.albumTitle = albumTitle;
							var data = 'albums/title='+albumTitle;
							data += '&albums/visibility='+albumVisibility;
							if (zipcode)
									data += '&albums/zipcode=' + zipcode.get('value');
							if (city)
									data += '&albums/city=' + city.get('value');
							if ($('description'))
									data += '&albums/description=' + $('description').get('value');
							if (tags)
									data += '&albums/tags=' + tags.get('value');

							data += '&global/no_history_for_upload=' + noClickHistoryValue;

							this.upload(
							{
									'data': data
							});
						}

						return false;
					}.bind(this));

					return false;
				}.bind(this));
			}
		}
	},

		onComplete: function(file, response)
		{
		this.log('Completed upload "' + file.name + '".', arguments);
		(this.options.fileComplete || this.fileComplete).call(this, this.finishFile(file), response);

		var jresponse = JSON.decode(response);
		this.albumId = jresponse.albumId;


		var myFile = this.getFile(file);
		myFile.element.getElement('input.identifier').set('value', jresponse.mediaId);

		this.partialProgressFx.start(100);
				this.partialText.set('html', '<strong>100% | {sent}</strong> / {total}'.substitute(
				{
			'sent'		: this.sizeToKB(file.size),
			'total'		: this.sizeToKB(file.size)
		}));
	},

		onError: function(file, error, info)
		{
		this.log('Upload "' + file.name + '" failed. "{1}": "{2}".', arguments);
		(this.options.fileError || this.fileError).call(this, this.finishFile(file), error, info);
	},

		onCancel: function()
		{
		this.log('Filebrowser cancelled.', arguments);
	},

		onAllComplete: function(current)
		{
		this.log('Completed all files, ' + current.bytesTotal + ' bytes.', arguments);
		this.updateOverall(current.bytesTotal);

		this.totalProgressFx.start(100);
				this.totalText.set('html', '<strong>100% | {sent}</strong> / {total}'.substitute(
				{
			'sent'		: this.sizeToKB(current.bytesLoaded),
			'total'		: this.sizeToKB(current.bytesTotal)
		}));

			if (this.errors == 0)
			{
				$('afterUploadText').set('html', '<strong>Hochladen erfolgreich:</strong> Deine {count} Bilder wurden erfolgreich in das Album "{albumTitle}" geladen und angelegt. Dein Album kannst Du jetzt bei Bedarf weiter bearbeiten. Dies kannst Du aber auch zu einem späteren Zeitpunkt vornehmen.'.substitute(
				{
					'count':this.files.length,
					'albumTitle':this.albumTitle
				}));
			}
			else if (this.errors == this.files.length)
			{
				$('afterUploadText').set('html', '<strong>Fehler beim Hochladen:</strong> Deine Bilder konnten nicht in das Album "{albumTitle}" geladen werden.'.substitute(
				{
					'albumTitle':this.albumTitle
				}));
			}
			else
			{
				$('afterUploadText').set('html', '<strong>Fehler beim Hochladen:</strong> {errors} von Deinen {count} Bildern konnten nicht in das Album "{albumTitle}" geladen werden.'.substitute(
				{
					'count':this.files.length,
					'errors':this.errors,
					'albumTitle':this.albumTitle
				}));
			}

		if (this.errors < this.files.length)
		{
			$('imageUpload').set('action', '/profile_media/edit_album/'+globalNumber+'/'+this.albumId);
			var editButton = $('afterUploadEditAlbum');
			editButton.removeEvents('click');
			editButton.removeClass('inactive');
			editButton.getParent().removeClass('inactive');
		}

		if (this.errors > 0)
		{
			MV_Overlay.show('/overlay/upload_errors', true);
		}
	},

		browse: function(fileList)
		{
		var ret = this.parent(fileList);
				if (ret !== true)
				{
						if (ret)
								this.log('An error occured: ' + ret);
						else
								this.log('Browse in progress.');
				}
				else
				{
			this.log('Browse started.');
		}
	},

		upload: function(options)
		{
			var ret = this.parent(options);

			if (ret !== true)
			{
				this.log('Upload in progress or nothing to upload.');

				if (ret)
					alert(ret);
			}
			else
			{
				this.log('Upload started.');
			}
	},

		removeFile: function(file)
		{
		var remove = this.options.fileRemove || this.fileRemove;
				if (!file)
				{
			this.files.each(remove, this);
			this.files.empty();
			this.updateOverall(0);
				}
				else
				{
						if (!file.element)
								file = this.getFile(file);
			this.files.erase(file);
			remove.call(this, file);
			this.updateOverall(this.bytesTotal - file.size);
		}
		this.parent(file);
	},

		getFile: function(file)
		{
		var ret = null;
				this.files.some(function(value)
				{
						if ((value.name != file.name) || (value.size != file.size))
								return false;
			ret = value;
			return true;
		});
		return ret;
	},

		countFiles: function()
		{
		var ret = 0;
				for (var i = 0, j = this.files.length; i < j; i++)
				{
						if (!this.files[i].finished)
								ret++;
		}
		return ret;
	},

		updateOverall: function(bytesTotal)
		{
		this.bytesTotal = bytesTotal;
	},

		finishFile: function(file)
		{
		file = this.getFile(file);
		file.element.removeClass('file-uploading');
		file.finished = true;
		return file;
	},

		fileCreate: function(file)
		{

		if (!this.fileUid)
			this.fileUid = 0;

		this.fileUid++;

		var titleId			= 'title_'+this.fileUid;
		var titleName		= 'media/title['+this.fileUid+']';

		var catchwordsId	= 'catchwords_'+this.fileUid;
		var catchwordsName	= 'media/catchwords['+this.fileUid+']';

		var descriptionId	= 'description_'+this.fileUid;
		var descriptionName	= 'media/description['+this.fileUid+']';

		var hiddenName = 'media/id['+this.fileUid+']';

				file.element = new Element('li',
				{
						'class': 'list_entry'
				}).adopt(new Element('div',
				{
						'class': 'mcard expanded_card formElementsOnWhite'
				}).adopt(new Element('div',
				{
						'class': 'media_wrapper mw_big'
				}).adopt(new Element('a',
				{
						'href': '#'
				})), new Element('dl',
				{
						'class': 'mcard_content'
				}).adopt(new Element('dt',
				{
						'class': 'mcard_title'
				}).adopt(new Element('label',
				{
						'for': titleId,
						'text': 'Bildtitel'
				})), new Element('dd',
				{
						'class': 'mcard_title'
				}).adopt(new Element('input',
				{
						'type': 'text',
						'id': titleId,
						'name': titleName,
						'class': 'fText',
						'value': file.name
				})), new Element('dt',
				{
						'class': 'mcard_catchwords'
				}).adopt(new Element('label',
				{
						'for': catchwordsId,
						'text': 'Suchbegriffe/tags'
				})), new Element('dd',
				{
						'class': 'mcard_catchwords'
				}).adopt(new Element('input',
				{
						'type': 'text',
						'id': catchwordsId,
						'name': catchwordsName,
						'class': 'fText'
				})), new Element('dt',
				{
						'class': 'mcard_description'
				}).adopt(new Element('label',
				{
						'for': descriptionId,
						'text': 'Kurzbeschreibung des Bildes'
				})), new Element('dd',
				{
						'class': 'mcard_description last'
				}).adopt(new Element('input',
				{
						'type': 'text',
						'id': descriptionId,
						'name': descriptionName,
						'class': 'fText'
				}), new Element('input',
				{
						'type': 'hidden',
						'name': hiddenName,
						'class': 'identifier'
				}))), new Element('div',
				{
						'class': 'options'
				}).adopt(new Element('div',
				{
						'class': 'options_inner'
				}))));

		updateScreenLayout(file.element);
		file.element.inject(this.list, 'bottom');
	},

		fileComplete: function(file, response)
		{
			var json = $H(JSON.decode(response, true));

			if (json.get('result') == 'success')
			{
				file.element.addClass('file-success');
				file.mediaId = json.get('mediaId');
				file.element.getElement('.media_wrapper a').adopt(new Element('img',
				{
						'src': json.get('src_130x130'),
						'alt': 'Bildvorschau'
				}));
			}
			else
			{
				this.errors++;
				file.element.addClass('file-failed');
				if (json.get('albumId'))
				{
					this.albumId = json.get('albumId');
				}
				this.log('failure: '+json.get('message'));
			}
		},

		fileError: function(file, error, info)
		{
		file.element.addClass('file-failed');
	},

		fileRemove: function(file)
		{
		file.element.fade('out').retrieve('tween').chain(Element.destroy.bind(Element, file.element));
	},

		log: function(text, args)
		{
				if (this.options.debug && window.console)
						console.log(text.substitute(args ||
						{}));
	}

});

/**
 * ProfileImageUpload - Upload for profile edit page, based on digitaralds FancyUpload2
 *
 */
var ProfileImageUpload = new Class(
{

	Extends: Swiff.Uploader,

		options:
		{
		limitSize: false,
		limitFiles: 1,
		instantStart: false,
		allowDuplicates: false,

		validateFile: function(file) // provide a function that returns true for valid and false for invalid files.
		{
			var parts = file.name.split('.');
			if (parts.length > 2)
				return false;

			var type = parts.pop().toLowerCase();
			var types = ['jpg', 'jpeg', 'gif', 'png'];

			return types.contains(type);
		},

		debug: false,

		fileInvalid: function(file, errors) { // called for invalid files with error stack as 2nd argument
			if (!this.errorShown) {
				if (errors.contains('size')) {
					new MessageBox('/overlay/message_box/400/'+file.name);
					this.errorShown = true;
				}
				else if (errors.contains('custom')) {
					new MessageBox('/overlay/message_box/401/'+file.name);
					this.errorShown = true;
				}
			}
		},

		fileCreate: null, // creates file element after select
		fileUpload: null, // called when file is opened for upload, allows to modify the upload options (2nd argument) for every upload
		fileComplete: null, // updates the file element to completed state and gets the response (2nd argument)
		fileRemove: null // removes the element
		/**
		 * Events:
		 * onBrowse, onSelect, onAllSelect, onCancel, onBeforeOpen, onOpen, onProgress, onComplete, onError, onAllComplete
		 */
	},

		initialize: function(options)
		{
		this.files = [];

				if (options.callBacks)
				{
			this.addEvents(options.callBacks);
			options.callBacks = null;
		}

		this.parent(options);
		this.render();

		this.currentFileName = $('userPortraitUploadFileName');
		this.totalProgressFx = new Fx.ProgressBar($('userPortraitUploadProgressBar'));
		this.totalText = $('userPortraitUploadProgressText');
		this.previewImg = $('userPortraitUploadPreview');

		this.submitButton = $('userPortraitUploadSubmit');
		this.cancelButton = $('userPortraitUploadCancel');
	},

		render: function()
		{
	},

		onLoad: function()
		{
		this.log('Uploader ready!');
	},

		onBeforeOpen: function(file, options)
		{
			this.log('Initialize upload for "{name}".', file);
			var fn = this.options.fileUpload;
			var obj = (fn) ? fn.call(this, this.getFile(file), options) : options;
			return obj;
		},

		onOpen: function(file, overall)
		{
		this.log('Starting upload "{name}".', file);
		this.totalProgressFx.cancel().set(0);
				this.totalText.set('html', '<strong>0% | {sent}</strong> / {total}'.substitute(
				{
			'percent'	: percent,
			'sent'		: this.sizeToKB(overall.bytesLoaded),
			'total'		: this.sizeToKB(overall.bytesTotal)
		}));
	},

		onProgress: function(file, current, overall)
		{
		var percent = Math.round(100*overall.bytesLoaded/overall.bytesTotal);
		this.totalProgressFx.start(overall.bytesLoaded, overall.bytesTotal);
				this.totalText.set('html', '<strong>{percent}% | {sent}</strong> / {total}'.substitute(
				{
			'percent'	: percent,
			'sent'		: this.sizeToKB(overall.bytesLoaded),
			'total'		: this.sizeToKB(overall.bytesTotal)
		}));
	},

		onSelect: function(file, index, length)
		{
			if (this.allAdded) {
				//remove all previously added files
				this.removeFile();
				this.allAdded = false;
			}

			var errors = [];
			if (this.options.limitSize && (file.size > this.options.limitSize))
					errors.push('size');
			if (this.options.limitFiles && (this.countFiles() >= this.options.limitFiles))
					errors.push('length');
			if (!this.options.allowDuplicates && this.getFile(file))
					errors.push('duplicate');
			if (!this.options.validateFile.call(this, file, errors))
					errors.push('custom');

			this.errorShown = false;
			if (errors.length)
			{
				var fn = this.options.fileInvalid;
				if (fn)
					fn.call(this, file, errors);
				return false;
			}
			(this.options.fileCreate || this.fileCreate).call(this, file);
			this.files.push(file);
			this.currentFileName.set('text', file.name);
			this.totalText.set('html', '<strong>0% | {sent}</strong> / {total}'.substitute(
			{
				'sent'		: this.sizeToKB(0),
				'total'		: this.sizeToKB(file.size)
			}));
			return true;
		},

		onAllSelect: function(files, current, overall)
		{
			this.allAdded = true;
		this.log('Added ' + files.length + ' files, now we have (' + current.bytesTotal + ' bytes).', arguments);
		this.updateOverall(current.bytesTotal);
				if (this.files.length && this.options.instantStart)
						this.upload.delay(10, this);
	},

		onComplete: function(file, response)
		{
			this.log('Completed upload "' + file.name + '".', arguments);
			(this.options.fileComplete || this.fileComplete).call(this, this.finishFile(file), response);

			response = JSON.decode(response);
			if (response.result == 'success')
			{
				var cropperLink = $$('.userPortraitEdit a');
				if (cropperLink)
				{
					if (response.type == 'assocphoto')
						cropperLink[0].set('href', "javascript:editAssocPhoto("+response.mediaId+");");
					else
						cropperLink[0].set('href', "javascript:editProfileImage("+response.mediaId+");");
				}
			}
			else
			{
				MV_Overlay.show('/overlay/upload_error/'+response.reason, true);
			}
		},

		onError: function(file, error, info)
		{
			this.log('Upload "' + file.name + '" failed. "{1}": "{2}".', arguments);
			(this.options.fileError || this.fileError).call(this, this.finishFile(file), error, info);
			MV_Overlay.show('/overlay/upload_errors/1', true);
		},

		onCancel: function()
		{
		this.log('Filebrowser cancelled.', arguments);
	},

		onAllComplete: function(current)
		{
		this.log('Completed all files, ' + current.bytesTotal + ' bytes.', arguments);
		this.updateOverall(current.bytesTotal);

		this.totalProgressFx.start(100);
				this.totalText.set('html', '100% | {sent} / {total}'.substitute(
				{
			'sent'		: this.sizeToKB(current.bytesLoaded),
			'total'		: this.sizeToKB(current.bytesTotal)
		}));
	},

		browse: function(fileList)
		{
		var ret = this.parent(fileList);
				if (ret !== true)
				{
						if (ret)
								this.log('An error occured: ' + ret);
						else
								this.log('Browse in progress.');
				}
				else
				{
			this.log('Browse started.');
		}
	},

		upload: function(options)
		{
		var ret = this.parent(options);
				if (ret !== true)
				{
			this.log('Upload in progress or nothing to upload.');
						if (ret)
								alert(ret);
				}
				else
				{
			this.log('Upload started.');
		}
	},

		removeFile: function(file)
		{
		var remove = this.options.fileRemove || this.fileRemove;
				if (!file)
				{
			this.files.each(remove, this);
			this.files.empty();
			this.updateOverall(0);
				}
				else
				{
						if (!file.element)
								file = this.getFile(file);
			this.files.erase(file);
			remove.call(this, file);
			this.updateOverall(this.bytesTotal - file.size);
		}
		this.parent(file);
	},

		getFile: function(file)
		{
		var ret = null;
				this.files.some(function(value)
				{
						if ((value.name != file.name) || (value.size != file.size))
								return false;
			ret = value;
			return true;
		});
		return ret;
	},

		countFiles: function()
		{
		var ret = 0;
				for (var i = 0, j = this.files.length; i < j; i++)
				{
						if (!this.files[i].finished)
								ret++;
		}
		return ret;
	},

		updateOverall: function(bytesTotal)
		{
		this.bytesTotal = bytesTotal;
	},

		finishFile: function(file)
		{
		return file;
	},

		fileCreate: function(file)
		{

		//update text
	},

		fileComplete: function(file, response)
		{
			var json = $H(JSON.decode(response, true));
			if (json.get('result') == 'success')
			{
				this.lastUploadedId = json.get('mediaId');
				this.previewImg.set('src', json.get('src_130x130'));
				this.submitButton.removeClass('inactive');
				this.submitButton.getParent().removeClass('inactive');
				if (this.cancelButton)
				{
					this.cancelButton.removeClass('inactive');
					this.cancelButton.getParent().removeClass('inactive');
				}
			}
			else
			{
			}
		},

		fileError: function(file, error, info)
		{
	},

		fileRemove: function(file)
		{
	},

		sizeToKB: function(size)
		{
		var unit = 'B';
				if ((size / 1048576) > 1)
				{
			unit = 'MB';
			size /= 1048576;
				}
				else
						if ((size / 1024) > 1)
						{
			unit = 'kB';
			size /= 1024;
		}
		return size.round(1) + ' ' + unit;
	},

		log: function(text, args)
		{
				if (this.options.debug && window.console)
						console.log(text.substitute(args ||
						{}));
	},

	//set uploaded pic as new profile pic
	submit: function() {

		//no image uploaded yet
		if (!this.lastUploadedId)
			return;

		var ajax = new Request.JSON({
			url		: this.options.submitUrl,
			onSuccess: function(jsonResponse, textResponse) {
				if (jsonResponse.result = 'success') {
					this.submitButton.addClass('inactive');
					if (this.cancelButton)
						this.cancelButton.addClass('inactive');
					window.location.reload();
 	} else {
 	//TODO: Fehler ausgeben
 	}
			}.bind(this)
		});
		ajax.send();
	},

	//delete uploaded pic
	cancel: function()
	{
		//no image uploaded yet
		if (!this.lastUploadedId)
			return;

		var ajax = new Request.JSON({

			url		: this.options.cancelUrl,

			onSuccess: function(jsonResponse, textResponse)
			{
				if (jsonResponse.result = 'success')
				{
 		this.previewImg.set('src', jsonResponse.src_130x130);
					var cropperLink = $$('.userPortraitEdit a');
					if (cropperLink)
					{
						if (jsonResponse.type == 'assocphoto')
							cropperLink[0].set('href', "javascript:editAssocPhoto("+jsonResponse.mediaId+");");
						else
							cropperLink[0].set('href', "javascript:editProfileImage("+jsonResponse.mediaId+");");
					}
					this.submitButton.addClass('inactive');
					if (this.cancelButton)
						this.cancelButton.addClass('inactive');
				}
				else
				{
					//TODO: Fehler ausgeben
				}
			}.bind(this)
		});

		ajax.send();
	}

});

/**
 * @todo Clean-up, into Date.js
 */
Date.parseDuration = function(sec)
{
	var units = {}, conv = Date.durations;
		for (var unit in conv)
		{
		var value = Math.floor(sec / conv[unit]);
				if (value)
				{
			units[unit] = value;
						if (!(sec -= value * conv[unit]))
								break;
		}
	}
	return units;
};

Date.fancyDuration = function(sec)
{
	var ret = [], units = Date.parseDuration(sec);
		for (var unit in units)
				ret.push(units[unit] + Date.durationsAbbr[unit]);
	return ret.join(', ');
};

Date.durations =
{
		years: 31556926,
		months: 2629743.83,
		days: 86400,
		hours: 3600,
		minutes: 60,
		seconds: 1,
		milliseconds: 0.001
};
Date.durationsAbbr =
{
	years: 'j',
	months: 'm',
	days: 'd',
	hours: 'h',
	minutes: 'min',
	seconds: 'sec',
	milliseconds: 'ms'
};

/**
 * Class Messagebox
 * displays a message box with buttons to close it,
 * calls user defined callback function when buttons clicked
 */
var MessageBox = new Class({
	options: {
		shallClose	: false,
		onOk		: false,
		onYes		: false,
		onNo		: false,
		onCancel	: false,
		onLoad		: false,
		modal		: true
	},

	initialize: function(url, options) {
		$extend(this.options, options);
		MV_Overlay.show(url, !this.options.modal, this.afterLoad.bind(this));
	},

	onOk: function() {
		var closeMe = true;
		if (this.options.onOk)
				closeMe = this.options.onOk.run(null, this);
		if (closeMe)
				MV_Overlay.close();
		return false;
	},

	onCancel: function() {
		var closeMe = true;
		if (this.options.onCancel)
				closeMe = this.options.onCancel.run(null, this);
		if (closeMe)
				MV_Overlay.close();
		return false;
	},

	onYes: function() {
		var closeMe = true;
		if (this.options.onYes)
				closeMe = this.options.onYes.run(null, this);
		if (closeMe)
				MV_Overlay.close();
		return false;
	},

	onNo: function() {
		var closeMe = true;
		if (this.options.onNo)
				closeMe = this.options.onNo.run(null, this);
		if (closeMe)
				MV_Overlay.close();
		return false;
	},

	afterLoad: function() {
		//add 'ok' onclick event
		var mbox = this;
		var content = MV_Overlay.OverlayContent;
		content.getElements('.buttonOk').each(function(el) {
			el.addEvent('click', mbox.onOk.bind(mbox));
		});

		//add 'cancel' onclick event
		content.getElements('.buttonCancel').each(function(el) {
			el.addEvent('click', mbox.onCancel.bind(mbox));
		});

		//add 'yes' onclick event
		content.getElements('.buttonYes').each(function(el) {
			el.addEvent('click', mbox.onYes.bind(mbox));
		});

		//add 'no' onclick event
		content.getElements('.buttonNo').each(function(el) {
			el.addEvent('click', mbox.onNo.bind(mbox));
		});

		$('Overlay').setStyle('top', '260px');
		$('Overlay').setStyle('left', '140px');

		if (this.options.onLoad)
			this.options.onLoad.run(content, this);
	},

	swicthLayout: function(type, options) {
		if(type == 'message') {
			$('OverlayContent').getElement('.box_content').set('html', options.text);
			var no = $('OverlayContent').getElement('.box_options_list').getFirst();
			var yes = no.getNext();
			no.getElement('a').set('html', options.butText);
			yes.setStyle('display', 'none');
		}
	}
});

/**
 * Class RemovalList
 *
 */
var RemovalList = new Class(
{

		inputIndex: 0,

		options: {},

		initialize: function(list, fieldName, options)
		{
			this.list = list;
			this.fieldName = fieldName;
			$extend(this.options, options);

			this.inputIndex = this.list.getElements('input').length;
		},

		addItem: function(fieldValue, content)
		{

			//is item already inserted?
				var alreadyInserted = this.list.getElements('input').some(function(el)
				{
				return el.get('value') == fieldValue;
			});

				if (alreadyInserted)
						return;

				var label = new Element('label',
				{
						'html': '<input type="checkbox" class="fCheck" name="' + this.fieldName + '[' + this.inputIndex + ']" value="' + fieldValue + '" checked />'
				});
				var listItem = new Element('li',
				{
						'html': content
				}).adopt(label);

				label.addEvent('mouseover', function()
				{
				this.getParent().toggleClass('hover');
			});
				label.addEvent('mouseout', function()
				{
				this.getParent().toggleClass('hover');
			});
				label.addEvent('click', function()
				{
						if (this.getParent('.removalList').getChildren().length > 1)
						{
					this.getParent().destroy();
				}
			});

			listItem.inject(this.list);
			this.inputIndex++;
		}
});


var deleteReport = function(reportId)
{
	new MessageBox('/overlay/question_box/400',{
		onYes: function(){
			new Request({
					url: '/profile_reports/delete_report/'+reportId,
					onSuccess: function(){
						//this.getParent('.mcard').getParent().destroy();
						window.location.reload();
					}.bind(this)
			}).send();
		return true;
	}.bind(this)
	})
	return false;
};


var deleteReportFromAssoc = function(reportId, assocId) {
	new MessageBox('/overlay/question_box/400',	{
		onYes: function() {
			new Request({
				url: '/association_reports/delete/'+assocId+'/'+reportId,
				onSuccess: function() {
					window.location.reload();
				}.bind(this)
			}).send();
			return true;
		}.bind(this)
	})
	return false;
};

var publishReportFromAssoc = function(reportId, assocId, client) {
	new MessageBox('/overlay/question_box/401/' + client, {
		onYes: function() {
			new Request({
				url: '/association_reports/publish/'+assocId+'/'+reportId,
				onSuccess: function() {
					window.location.reload();
				}.bind(this)
			}).send();
			return true;
		}.bind(this)
	})
	return false;
};

var removePublishReportFromAssoc = function(reportId, assocId, client) {
	new MessageBox('/overlay/question_box/402/' + client, {
		onYes: function() {
			new Request({
				url: '/association_reports/removePublishing/'+assocId+'/'+reportId,
				onSuccess: function() {
					window.location.reload();
				}.bind(this)
			}).send();
			return true;
		}.bind(this)
	})
	return false;
};



var deleteMember = function(userId, assocId) {
	new MessageBox('/overlay/question_box/500', {
		onYes: function() {
			new Request({
				url: '/association_members/delete_member/'+userId+'/'+assocId,
				onSuccess: function(responseJSON, responseText) {

					if (JSON.decode(responseJSON).result == 'success'){
						window.location.reload();
					} else {
						this.switchLayout('message', {
							'text': JSON.decode(responseJSON).message,
							'butText': 'Schließen'
						});
					}
				}.bind(this)
			}).send();
			return false;
		}.bind(this)
	})
	return false;
};


var deleteFriend = function(userId, friendId)
{
		new MessageBox('/overlay/question_box/600',
		{
				onYes: function()
				{
						new Request(
						{
				url: '/friends/reject_friend/'+userId+'/'+friendId,
								onSuccess: function()
								{
					//this.getParent('.mcard').getParent().destroy();
					window.location.reload();
								}
.bind(this)
			}).send();
			return true;
				}
.bind(this)
	})
	return false;
};

var deleteAssocFriend = function(assocId, twinAssocId, messageId)
{
	new MessageBox('/overlay/question_box/'+messageId,
	{
		onYes: function()
		{
			new Request(
			{
				url: '/association_friends/reject_friendship/'+assocId+'/'+twinAssocId,

				onSuccess: function(responseJSON, responseText)
				{
					if (JSON.decode(responseJSON).result == 'success')
					{
						window.location.reload();
					}
					else
					{
						this.switchLayout('message', {'text': JSON.decode(responseJSON).message, 'butText': 'Schließen'});
					}
				}.bind(this)
			}).send();

			return false;
		}.bind(this)
	})
	return false;
};



/* func for patrick */


function deleteDivision(divId, assocId)
{
	new MessageBox('/overlay/delete_division/'+divId+'/'+globalNumber,
	{
		onYes: function()
		{
			new Request(
			{
				url: '/association_divisions/delete/'+divId,
				onSuccess: function()
				{
					window.location = '/association_divisions/divisions/'+assocId;
				}.bind(this)
			}).send();
			return true;
		}.bind(this)
	})
}

function deleteTeam(teamId, assocId)
{
	new MessageBox('/overlay/delete_team/'+teamId+'/'+globalNumber,
	{
		onYes: function()
		{
			new Request(
			{
				url: '/association_teams/delete/'+teamId,
				onSuccess: function()
				{
					window.location = '/association_teams/teams/'+assocId;
				}.bind(this)
			}).send();
			return true;
		}.bind(this)
	})
}

function deleteGroup(groupId)
{
	new MessageBox('/overlay/delete_group/'+groupId+'/'+globalNumber,
	{
		onYes: function()
		{
			new Request(
			{
				url: '/groups/delete/'+globalNumber+'/'+groupId,
				onSuccess: function()
				{
					window.location = '/groups/accepted/'+globalNumber;
				}.bind(this)
			}).send();
			return true;
		}.bind(this)
	})
}

/* func for patrick */


function leaveGroup(groupId)
{
	new MessageBox('/overlay/leave_group/'+groupId+'/'+globalNumber,
	{
		onYes: function()
		{
			new Request(
			{
				url: '/groups/leave/'+globalNumber+'/'+groupId, //'/ajax/delete_media/'+groupId+'/'+globalNumber,
				onSuccess: function()
				{
					window.location = '/groups/accepted/'+globalNumber;
								}
.bind(this)
			}).send();
			return true;
				}
.bind(this)
	})
}
/** funcs by patrick **/
function leaveAssoc(assocId) {

	new MessageBox('/overlay/leave_assoc/'+assocId+'/'+globalNumber, {
		onYes: function() {
			new Request({
				url: '/groups/leave/'+globalNumber+'/'+assocId, //'/ajax/delete_media/'+groupId+'/'+globalNumber,
				onSuccess: function(){
					//window.location = '/profile/memberships/'+globalNumber;
					window.location.reload();
				}.bind(this)
			}).send();

			return true;
		}.bind(this)
	})
}









/**
 * class for the farbwahl simple (image) cropper
 * This is the javascript representation of the simple cropper. It contains functions
 * to set values from flash to a html formular.
 */
var SimpleCropper = new Class(
{
	Implements : Options,

		options:
		{
		xName : 'cropped_x', /** id of the field that will contain the x coordinate */
		yName : 'cropped_y', /** id of the field that will contain the y coordinate */
		widthName : 'cropped_width', /** id of the field that will contain the width of the croparea */
		heightName : 'cropped_height', /** id of the field that will contain the height of the croparea */
		rotationName : 'cropped_rotation' /** id of the field that will contain the rotation of the image */
	}, /** the options object contains the fieldnames */
	x : null, /** will contain the field named by xName */
	y : null, /** will contain the field named by yName */
	width : null, /** will contain the field named by widthName */
	height : null, /** will contain the field named by heightName */
	rotation : null, /** will contain the field named by rotationName */
	fieldsExist : false, /** indicates whether all fields do exist or not */
	gotCropdata : false, /** if true, the form can be submitted */
	/**
	 * constructor
	 * set new values for object properties and check whether all neccessary fields do exist
	 *
	 * @param Object options : object with optional attributes for formName, xName, yName, widthName, heightName
	 */
	initialize : function(options)
	{
		this.setOptions(options);

		if ($(this.options.xName))
			this.x = $(this.options.xName);

		if ($(this.options.yName))
			this.y = $(this.options.yName);

		if ($(this.options.widthName))
			this.width = $(this.options.widthName);

		if ($(this.options.heightName))
			this.height = $(this.options.heightName);

		if ($(this.options.rotationName))
			this.rotation = $(this.options.rotationName);

		if (this.x != null && this.y != null && this.width != null && this.height != null && this.rotation != null)
			this.fieldsExist = true;
		else
			alert('The image cropper will not work properly. Please check for missing fields.');
	},

	/**
	 * set the given values to the input fields
	 *
	 * @param Number x : the top left corners x position of the cropper area
	 * @param Number y : the top left corners y position of the cropper area
	 * @param Number width : the width of the cropper area
	 * @param Number height : the height of the cropper area
	 * @param Number rotation : the rotation of the image
	 */
	setValues : function(x, y, width, height, rotation)
	{
		if (this.fieldsExist)
		{
			this.x.value = Math.round(x);
			this.y.value = Math.round(y);
			this.width.value = Math.round(width);
			this.height.value = Math.round(height);
			this.rotation.value = rotation;

			this.gotCropdata = true;
		}
	}
});

var reloadPage = false;

function deleteForumTopic(anchor)
{
	new MessageBox('/overlay/question_box/800', {
		onYes: function() {
			window.location.href = $(anchor).get('href');
			return true;
		}.bind(this)
	})
	return false;
}

function editImage(id)
{
	MV_Overlay.show('/overlay/image_cropper/'+id, true, startImageCropper);
}

function editProfileImage(id) {
	if (id > 0)
		MV_Overlay.show('/overlay/image_cropper/'+id+'/false', true, startImageCropper);
}

function editAssocPhoto(id) {
	if (id > 0)
		MV_Overlay.show('/overlay/image_cropper/'+id+'/false', true, startImageCropperAssocPhoto);
}

function checkCropped(formular, mediaId, reopenGallery) {

	formular = $(formular);

	var myRequest = new Request.JSON({
		'url':formular.action,
		'data':formular.toQueryString(),

		onSuccess: function(responseJSON, responseText)
		{
			if (responseJSON.result == 'success')
			{
				responseJSON.changes.each(function(pair) {
					replaceImages(pair[0], pair[1]);
				});

				MV_Overlay.close();
				if(reopenGallery)
					MV_Overlay.show('/overlay/media_album_galerie/'+mediaId, true, startAlbumGalerie);
				//else
				//	window.location.reload();
			}
		}
	}).send();

	return false;
}

var simpleCropper; // in this variable the simple cropper object is stored
function startImageCropperAssocPhoto() {
	startImageCropper(420, 120, true);
}

function startImageCropper(width, height, limit)
{
	if (limit === null) limit = true;

/*
 * The real image crop size is calculated as followed:
 *  width = cropperWidth - 2 * overlayWidth
 *  height = cropperHeight - 2 * overlayHeight
 *
 * This are optional flashVars:
 *  cropperWidth  Integer : flash objects width
 *  cropperHeight Integer : flash objects height - 45px
 *    overlayWidth      Integer : the width of the overlays left and right bar
 *    overlayHeight     Integer : the height of the overlays top and bottom bar
 *    overlayColor      hexadecimal (0xffffff) : the color that is used for the overlay
 *    overlayOpacity    float (from 0.0 to 1.0) : the opacity the overlayColor is painted
 *    overlayBorderWidth      Integer : the width of the border around the clipping area
 *    overlayBorderColor      hexadecimal (0xffffff) : the color of the clipping areas border
 *    overlayBorderOpacity    float (from 0.0 to 1.0) : the opacity the overlayBorderColor is painted
 *    underlayColor     hexadecimal (0xffffff) : this is the color in the back of the image and the overlay
 *  limitMinimumSize     Boolean : if set to true, it will not be possible to scale the images to a bordered size
 */
if (!width) width = 230;
if (!height) height = 230;

	var flashVars = {file: $('cropperDiv').get('title'),
						jsObject: 'simpleCropper',
						cropperWidth: 630,
						cropperHeight: 432,
						overlayWidth: (630-width)/2,
						overlayHeight: (432-height)/2,
						//limitMinimumSize: limit ? 'true' : 'false',
						limitMinimumSize: 'true',
			overlayColor: 0x000000,
			underlayColor: 0xffffff
	};

		var parameter =
		{
		quality: 'best',
		loop: 'false',
		scale: 'noscale',
		wmode: 'window',
		devicefont: 'false',
		bgcolor: '#ffffff',
		menu: 'false',
		allowFullScreen: 'false',
		allowScriptAccess:'sameDomain',
		salign: 'lt'
	};

		var attributes =
		{
		id: 'simplecropper',
		name: 'simplecropper',
		align: 'middle'
	};

	swfobject.embedSWF("/flash/simplecropper.swf", "cropperDiv", "630", "472", "9.0.0", "", flashVars, parameter);
	simpleCropper = new SimpleCropper();
}

//----------- button, dropdown and card events -----------//

var openAlbum = function()
{
	//event.stop();
	MV_Overlay.show('/overlay/album_galerie/'+this.albumId, true, startAlbumGalerie);
	return false;
};

var openAnyAlbum = function(albumId) {

	MV_Overlay.show('/overlay/album_galerie/'+albumId, true, startAlbumGalerie);
	return false;
}

var openMedia = function(event)
{
	event.stop();
	MV_Overlay.show('/overlay/media_album_galerie/'+this.mediaId, true, startAlbumGalerie);
	return false;
};
var openVideo = function(event)
{
	event.stop();
	showVideo(this.mediaId);
	return false;
};

var showVideo = function(identifier) {

	var startVideoOnly = function() {

		$('Overlay').setStyle('left', '160px');

		var videoFile		= $('file').get('title');
		var videoWidth		= $('width').get('title');
		var videoHeight		= $('height').get('title');
		var videoDuration	= $('duration').get('title');

		var showRoom = $('show_room');
		showRoom.set('html', '<div id="MV_Player"></div>');

		startVideoPlayer(videoFile, videoWidth, videoHeight, videoDuration);
	};
	MV_Overlay.show('/overlay/show_video/'+identifier, true, startVideoOnly);
}

var deleteMedia = function(mediaId) {
	//event.stop();
	new MessageBox('/overlay/question_box/300', {
		onYes: function() {
		//alert(mediaId);
			new Request({
				url: '/ajax/delete_media/'+mediaId,
				onSuccess: function() {
					//this.getParent('.mcard').getParent().destroy();
					window.location.reload();
				}.bind(this)
			}).send();
		return true;
		}.bind(this)
	})
	return false;
};


var deleteImageLink = function(mediaId, userId) {
	new MessageBox('/overlay/question_box/303', {
		onYes: function() {
			new Request({
				url: '/ajax/delete_image_link/'+mediaId+'/'+userId,
				onSuccess: function(htmlResponse, xmlResponse) {
					var response = JSON.decode(htmlResponse)
					if (JSON.decode(htmlResponse).result = 'success')
						window.location.reload();
				}.bind(this)
			}).send();
		return true;
		}.bind(this)
	})
	return false;
};


var deleteMediaFromAssoc = function(assocId, mediaId) {
	//event.stop();
	new MessageBox('/overlay/question_box/300', {
		onYes: function() {
			new Request({
				url: '/ajax/delete_media_from_assoc/' + assocId + '/' + mediaId,
				onSuccess: function() {
					//this.getParent('.mcard').getParent().destroy();
					window.location.reload();
				}.bind(this)
			}).send();
		return true;
		}.bind(this)
	})
	return false;
};


var deleteSurvey = function(surveyId)
{
	new MessageBox('/overlay/question_box/300',
	{
		onYes: function()
		{
			new Request(
			{
				url: '/ajax/delete_survey/'+surveyId,
				onSuccess: function()
				{
					window.location.reload();
				}
			}).send();
			return true;
		}
	});
	return false;
};



var deleteAlbum = function(albumId)
{
	//event.stop();
	new MessageBox('/overlay/question_box/301',
	{
		onYes: function()
		{
			new Request(
			{
				url: '/ajax/delete_album/'+albumId,
								onSuccess: function()
								{
					//this.getParent('.mcard').getParent().destroy();
					window.location.reload();
								}
.bind(this)
			}).send();
			return true;
				}
.bind(this)
	})
	return false;
};


var deleteAlbumFromAssoc = function(assocId, albumId, assocTitle)
{
	//event.stop();
		new MessageBox('/overlay/question_box/302/' + assocTitle,
		{
				onYes: function()
				{
						new Request(
						{
				url: '/ajax/delete_album_from_assoc/' + assocId + '/' + albumId,
								onSuccess: function()
								{
					//this.getParent('.mcard').getParent().destroy();
					window.location.reload();
								}
.bind(this)
			}).send();
			return true;
				}
.bind(this)
	})
	return false;
};

var offerFriendship = function(event)
{
	event.stop();
		new Request(
		{
		url: '/friends/friend_request/'+globalNumber+'/'+this.userId,
				onSuccess: function()
				{
			new MessageBox('/overlay/message_box_for_friend_request/'+this.userId);
				}
.bind(this)
	}).send();
	return false;
};

var checkForInterest = function()
{
		if ($('interests'))
		{
				var textInput = $('interests');
				var addButton = $('addInterest');
				var overviewLink = $('showAllInterests');
				var interestList = $('interestList');

				if (textInput && addButton && overviewLink && interestList)
				{
						var rl = new RemovalList(interestList, 'interests/id');

						var addNewInterest = function(title)
						{
								new MessageBox('/overlay/add_interest/' + title,
								{
										modal: true,

										onOk: function()
										{

												//validate input
												var errors = false;
												if (this.interestDescription.get('value') == '')
												{
														this.interestDescription.addClass('error');
														errors = true;
												}
												else
														this.interestDescription.removeClass('error');

												if (this.justifyCategory.get('value') == '')
												{
														this.justifyCategory.addClass('error');
														errors = true;
												}
												else
														this.justifyCategory.removeClass('error');

												if (!errors)
												{
														//add new category
														var request = new Request.JSON(
														{
																url: '/ajax/add_interest/' + title,
																data: this.form.toQueryString(),

																onSuccess: function(json, text)
																{
																		if (json && json.result == 'success')
																		{
																				textInput.set('value', '');
																				rl.addItem(json.interestId, title);
																		}
																}
														});
														request.send();
														return true;
												}
										},

										onLoad: function(content)
										{
												var categoryText = content.getElement('#newInterestSelectedCategory');
												this.categoryText = categoryText;
												this.form = content.getElement('#addInterest');
												this.categorySelection = content.getElement('#newInterestCategory');
												this.categorySelection.addEvent('change', function()
												{
														var index = this.selectedIndex;
														var text = this.getElements('option')[index].get('text');
														categoryText.set('text', text);
												});

												this.interestDescription = content.getElement('#newInterestDescription');
												this.justifyCategory = content.getElement('#justifyCategory');
										}
								});
						};

						addButton.addEvent('click', function()
						{

								var title = textInput.get('value');
								if (title.length < 3)
										return false;

								//try to find interest in database
								var myRequest = new Request.JSON(
								{
										'url': '/ajax/get_interest_by_title/',

										onSuccess: function(json, text)
										{
												//found something
												if (json.id)
												{
														//found an exact match
														if (!json.similar)
														{
																textInput.set('value', '');
																rl.addItem(json.id, json.title);
														}
														//found sth similar
														else
														{
																//open message box "did you mean ...?"
																new MessageBox('/overlay/question_box/200/' + escape(json.title),
																{
																		modal: false,

																		onYes: function()
																		{
																				textInput.set('value', '');
																				rl.addItem(json.id, json.title);
																		},

																		onNo: function()
																		{
																				addNewInterest(title);
																		}
																});
														}
												}
												//found nothing
												else
												{
														//open message box "do you want to add that interest ...?"
														new MessageBox('/overlay/question_box/201/' + escape(title),
														{
																modal: false,

																//open next overlay
																onYes: function()
																{
																		addNewInterest(title);
																}
														});
												}
										}
								});

								myRequest.send('title/title='+encodeURIComponent(title));
								return false;
						});

						overviewLink.addEvent('click', function()
						{
								new MessageBox('/overlay/all_interests',
								{
										modal: false
								});
								MV_Overlay.removalList = rl;
								return false;
						});
				}

		}
}


var CardFormSelector = new Class(
{
	Implements: Options,

	options:
	{
		formId: 'imageSelection',
		ajaxId: 'ajax'
	},

	formObj: null,
	fieldsetIn: null,
	fieldsetOut: null,
	ulIn: null,
	ulOut: null,
	paginationTarget: null,
	textLiIn: new Element('li', {'class': 'hints textLi', 'html': 'Keine Bilder ausgewählt!'}),
	textLiOut: new Element('li', {'class': 'hints textLi', 'html': 'Keine Bilder vorhanden!'}),
	status: true,

	initialize: function(options)
	{
		this.setOptions(options);

		this.initForm();
		this.initButtons(this.ulIn);
		this.initButtons(this.ulOut);
		this.initHiddenInputs();
		//this.checkStatus();
	},

	initForm: function()
	{
		this.formObj = $(this.options.formId);

		if (this.formObj == null)
		{
			this.status = false;
		}
		else
		{
			this.fieldsetIn = this.formObj.getElement('.'+this.options.formId+'_In');
			this.fieldsetOut = this.formObj.getElement('.'+this.options.formId+'_Out');

			if(this.fieldsetIn == null || this.fieldsetOut == null)
				this.status = false;
			else
			{
				this.ulIn = this.fieldsetIn.getElement('.card_list');
				this.ulOut = this.fieldsetOut.getElement('.card_list');

				this.paginationTarget = this.ulOut.getParent('.paginationTarget');
				this.paginationTarget.ajaxPaginationAfterExchange = this.afterPaginationCallback.bind(this);

				if(this.ulIn == null || this.ulOut == null)
					this.status = false;
			}
		}
	},

	initButtons: function(rootNode)
	{
		if(this.status)
		{
			var idPrefix = rootNode == this.ulIn ? 'incard_' : 'outcard_';
			var removeButtons = rootNode.getElements('.mcard.image a.remove');
			var addButtons = rootNode.getElements('.mcard.image a.add');

			removeButtons.each(function(item, index) {
				this.addEvent('remove', item);
				this.getLiElement(item).set('id', idPrefix+this.getIdFromCard(item));
			}.bind(this));

			addButtons.each(function(item, index) {
				this.addEvent('add', item);
				this.getLiElement(item).set('id', idPrefix+this.getIdFromCard(item));
			}.bind(this));
		}
	},

	initHiddenInputs: function()
	{
		if(this.status)
		{
			var removeButtons = this.ulIn.getElements('.mcard.image a.remove');
			removeButtons.each(function(item, index) {
				this.createHiddenInput(this.getIdFromCard(item));
			}.bind(this));
		}
	},

	afterPaginationCallback: function(box) {

		this.paginationTarget = box;
		this.initButtons(box);
	},

	addEvent: function(type, item)
	{
		if (this.status)
		{
			if (type == 'remove')
			{
				item.removeEvents();

				item.addEvent('click', function()
				{
					this.removeItem(item);
				}.bind(this));

				item.removeClass('add');
				item.addClass('remove');
			}
			else
			{
				item.removeEvents();

				item.addEvent('click', function()
				{
					this.addItem(item);
				}.bind(this));

				item.removeClass('remove');
				item.addClass('add');
			}
		}
	},

	getIdFromCard: function(item)
	{
		var id = item.getProperty('href').substr(1);
		return id;
	},

	createHiddenInput: function(id)
	{
		if(this.status)
		{
			var input = new Element('input', {
				'name': this.options.formId+'/ids[]',
				'id': this.options.formId+'_ids_'+id,
				'value': id,
				'type': 'hidden'
			});
			input.inject(this.formObj, 'top');
		}
	},

	removeItem: function(item)
	{
		if (this.status)
		{
			if (this.checkEmptyElements('out'))
			{
				if(this.ulOut.getElement('.textLi'))
					this.ulOut.getElement('.textLi').destroy();
			}

			var id = this.getIdFromCard(item);
			$(this.options.formId+'_ids_'+id).destroy();

			$('incard_'+id).destroy();

			var outCard = $('outcard_'+id);
			if (outCard) {
				var button = outCard.getElement('a.remove');
				this.addEvent('add', button);
			}

			if(!this.checkEmptyElements('in'))
			{
				var copy = this.textLiIn.clone(true);
				copy.inject(this.ulIn);
			}
		}
	},

	addItem: function(item)
	{
		if (this.status)
		{
			if (this.checkEmptyElements('in'))
			{
				if(this.ulIn.getElement('.textLi'))
					this.ulIn.getElement('.textLi').destroy();
			}

			var id = this.getIdFromCard(item);
			var li = this.getLiElement(item);

			this.addEvent('remove', item);
			this.createHiddenInput(id);

			var clone = li.clone();
			clone.set('id', 'incard_'+id);
			clone.inject(this.ulIn);

			var originalElements = li.getElements('a, .media_wrapper');
			var clonedElements = clone.getElements('a, .media_wrapper');
			clonedElements.each(function(elem,index) {
				elem.cloneEvents(originalElements[index]);
				elem.mediaId = id;
			});

			if(!this.checkEmptyElements('out'))
			{
				var copy = this.textLiOut.clone(true);
				copy.inject(this.ulOut);
			}
		}
	},

	getLiElement: function(item)
	{
		if (this.status)
		{
			return item.getParent('.list_entry');
		}
	},

	checkStatus: function()
	{
		if(this.status == false)
			console.log('CardFormSelector: Error');
		else
			console.log('CardFormSelector: Success');
	},

	checkEmptyElements: function(type)
	{
		if(this.status)
		{
			if(type == 'out')
			{
				if(this.ulOut.getChildren().length == 0)
					return false;
				else
					return true;
			}
			else
			{
				if(this.ulIn.getChildren().length == 0)
					return false;
				else

					return true;
			}
		}
	}
});

/**
 * Replaces all images with a certain src.
 * Useful when profile images are changed via ajax
 * [SU]
 */
function replaceImages(oldSrc, newSrc) {
	if (!oldSrc || !newSrc)
		return false;

	var images = $$('img[src='+oldSrc+']');
	images.each(function(img) {
		img.src = newSrc;
	});

	return images.length > 0;
}


function autoclearFocus() {
	if (this.get('value') == this.autoclearText)
		this.set('value', '');
}

function autoclearBlur() {
	if (this.get('value') == '')
		this.set('value', this.autoclearText);
}

function submitPinboard(pinboardForm) {
	//send form
	pinboardForm = $(pinboardForm);
	var url = $('assocPinboardUrl').get('value');
	new Request({
		'url':pinboardForm.action,
		'data':pinboardForm.toQueryString(),
		'onSuccess': function() {
			ajaxPagination(pinboardForm.getParent('.box'), url);
		}
	}).send();
}

// Javascript Email Verschlüsselung
function CryptMailto(mail, target)
{
	var n = 0;
	var r = "";
	var s = "mailto:"+mail;
	var e = mail;

	e = e.replace( /@/, " [at] ");
	e = e.replace( /\./g, " [dot] ");

	for( var i=0; i < s.length; i++ )
	{
		n = s.charCodeAt( i );
		if( n >= 8364 )
		{
			n = 128;
		}
		r += String.fromCharCode(n+1);
	}

	if($(target))
	{
		$(target).getParent().set('html','<a href="javascript:linkTo_UnCryptMailto(\''+ r +'\');">'+ e +'</a>');
	}

	//document.forms[0].cyptedEmailField.value = r;
	//document.forms[0].HTMLCyptedEmailField.value = "<a href=\"javascript:linkTo_UnCryptMailto('"+ r +"');\">"+ e +"</a>";
}

function UnCryptMailto( s )
{
	var n = 0;
	var r = "";
	for( var i = 0; i < s.length; i++)
	{
		n = s.charCodeAt( i );
		if( n >= 8364 )
		{
			n = 128;
		}
		r += String.fromCharCode( n - 1 );
	}
	return r;
}

function linkTo_UnCryptMailto( s )
{
	location.href=UnCryptMailto( s );
}



///////////////////////////////////////////////////////
// overlay.js


// Class für overlay
var Overlay = new Class({

            initialize : function() {
                // Overlay wrapper
                this.Overlay = new Element('div', {
                            'id' : 'Overlay'
                        });
                this.Overlay.inject($('Body'), 'top');

                // Overlay Content
                this.OverlayContent = new Element('div', {
                            'id' : 'OverlayContent'
                        });
                this.OverlayContent.inject(this.Overlay);

                // overlay background
                this.OverlayBG = new Element('div', {
                            'id' : 'OverlayBG'
                        });
                this.OverlayBG.setStyles({
                            opacity : 0.3,
                            display : 'none'
                        });

                // ie4 anpassungen
                if (Browser.Engine.trident4) {
                    this.OverlayBG.setStyles({
                                width : window.getSize().x,
                                height : $('MeinVerein').getSize().y
                            });

                    /*
                     * window.addEvent('scroll', function(e){
                     * this.OverlayBG.setStyle('top', window.getScroll().y); });
                     */
                    window.addEvent('resize', function(e) {
                                this.OverlayBG.setStyles({
                                            width : window.getSize().x,
                                            height : $('MeinVerein').getSize().y
                                        });
                            });
                }

                this.OverlayBG.inject($('Body'), 'top');
                this.OverlayBG
                        .set('html',
                                '<div id="InnerOverlayBG"><div id="Loader"></div></div>');
                this.Loader = $('Loader');
                this.Loader.setStyle('opacity', 0);

                // request
                this.Request = new Request({
                            url : '/overlay/',
                            method : 'post',
                            onSuccess : function(result) {
                                this.tmpContent = result;
                                this.dumpRequested();
                            }.bind(this),
                            onFailure : function() {
                                this.Error = true;
                            }.bind(this)
                        });

                // vars
                this.tmpContent;
                this.boolClick = true;
            },

            // parameters
            // ajax [string] = controller address
            // boolclick [bool] = if you can click on the overlay bg
            // fn [function]= function that is executed, after overlay content
            // is loaded
            // params [Array]= parameters that have to be passed with executing
            // the function
            show : function(ajax, boolClick, fn, params) {

                if (ajax) {
                    this.boolClick = boolClick;

                    // alle selects im IE6 wegschalten
                    if (Browser.Engine.trident4) {
                        $$('select').each(function(elem) {
                                    elem.setStyle('display', 'none');
                                });
                    }

                    if (fn) {
                        this.contentFunction = fn;
                        if (params) {
                            this.cFParameters = params;
                        } else {
                            this.cFParameters = new Array();
                        }
                    }

                    // Position
                    var pos;
                    if (window.innerHeight) {
                        pos = window.innerHeight / 2 - 16;
                    } else if (document.body && document.body.offsetHeight) {
                        pos = document.body.offsetHeight / 2 - 16;
                    } else {
                        pos = 0;
                    }

                    this.Loader.setStyles({
                                'top' : pos,
                                'opacity' : 0
                            });

                    // anzeigen
                    this.showBg();
                    this.Loader.fade(1);

                    // requesten
                    this.Request.cancel();
                    this.Request.options.url = ajax;
                    this.Request.send();
                } else {
                	 // anzeigen
                    this.showBg();
                    this.Loader.fade(1);
                    this.tmpContent = fn();
                    this.dumpRequested();
                }
            },

            contentFunction : null,

            emptyContentFunction : function() {
                this.contentFunction = null;
            },

            showBg : function() {

                this.OverlayBG.setStyles({
                            'display' : 'block'
                        });

                /*
                 * var Fx_show = new Fx.Morph(this.OverlayBG); Fx_show.start({
                 * opacity : 0.3 });
                 */

                // soll OverlyBG ggeklickt werden?
                this.OverlayBG.addEvent('click', function(e) {

                            e.stop();
                            if (this.boolClick)
                                this.close();
                            return false;
                        }.bind(this));
            },

            dumpRequested : function() {

                // styles
                this.Loader.fade(0);
                // this.Overlay.setStyle('opacity', 0);
                this.Overlay.setStyle('display', 'block');
                this.OverlayContent.setStyle('display', 'block');

                this.OverlayContent.set('html', this.tmpContent);
                updateScreenLayout(this.OverlayContent);

                if (this.contentFunction) {
                    this.contentFunction.attempt(this.cFParameters);
                }

                // Position
                var pos = window.getScroll().y + 100;
                if (pos < 0) {
                    pos = 0;
                }

                this.OverlayContent.setStyles({
                            'top' : pos
                        });

                // close_indicator
                $$(this.OverlayContent.getElements('.close_indicator')).each(
                        function(elem) {
                            elem.removeEvents('click');
                            if (this.boolClick) {
                                elem.addEvent('click', function(e) {
                                            e.stop();
                                            MV_Overlay.close();
                                        });
                            }
                        });

                // effekt
                // this.Overlay.fade(1);
            },

            close : function() {

                // alle selects im IE6 wegschalten
                if (Browser.Engine.trident4) {
                    $$('select').each(function(elem) {
                                elem.setStyle('display', 'block');
                            });
                }

                this.Request.cancel();
                this.emptyContentFunction();
                this.Loader.setStyle('opacity', 0);
                this.OverlayBG.setStyle('display', 'none');
                this.Overlay.setStyle('display', 'none');
                this.OverlayContent.setStyle('display', 'none');
                this.OverlayContent.set('html', '');
                this.boolClick = true;
                // reload page after cropping
                if (reloadPage)
                    window.location.reload();
            }

        });



///////////////////////////////////////////////////////
// rating.js


//Class für rating
/*
element =  class="rating"
*/
var Rating = new Class({
	initialize: function(element){
		this.element = element;
		this.form = this.element.getElement('.formRating');
		this.avgRating = this.element.getParent().getElement('.averageRating');
		this.ratingCount = this.element.getParent().getElement('.ratingCount');
		this.createEvents();

		//request eigenschaften setzen
		this.form.set('send', {
			method : 'post',
			onSuccess: function(responseText, responseXML){
				var response = JSON.decode(responseText);
				if(response.result == 'save'){
					//.rating  eliminieren
					if(this.element.getPrevious('dt')) {this.element.getPrevious('dt').destroy();}
					this.element.destroy();

					//durchschnit setzten
					this.avgRating.set('html', response.overallRating);
					this.avgRating.getParent('.accessibility').toggleClass('accessibility');

					//aktuelle bewertungen setzten
					var actualRatings = this.ratingCount.get('html').toInt() + 1;
					this.ratingCount.set('html', actualRatings);
				}
			}.bind(this)
		});
	
		//IE6 request
		this.IE6Request = new Request({
			method 		: 'post',
			url			: this.form.getProperty('action'),
			onSuccess	: function(responseText, responseXML){
								var response = JSON.decode(responseText);
								if(response.result == 'save'){
									//.rating  eliminieren
									if(this.element.getPrevious('dt')) {this.element.getPrevious('dt').destroy();}
									this.element.destroy();

									//durchschnit setzten
									this.avgRating.set('html', response.overallRating);
									this.avgRating.getParent('.accessibility').toggleClass('accessibility');

									//aktuelle bewertungen setzten
									var actualRatings = this.ratingCount.get('html').toInt() + 1;
									this.ratingCount.set('html', actualRatings);
								}
							}.bind(this)
		});
	},

	createEvents: function(){
		this.createdHidden = false;
		this.form.getElements('label').each(function(elem){
			elem.getElement('span').addEvents({
				'mouseenter' 	: function(e){
									e.stop();
									this.form.toggleClass(elem.getElement('span').get('class'));
									return false;
								}.bind(this),
				'mouseleave' 	: function(e){
									e.stop();
									this.form.toggleClass(elem.getElement('span').get('class'));
									return false;
								}.bind(this)
			});
		

		if(Browser.Engine.trident){
			var input = elem.getElement('input');
			elem.rating = input.value;
			if(!this.createdHidden){
				var Hidden = new Element('input',{'name': input.get('name'), 'type': 'hidden', 'id' : 'hiddenRating'}).inject(elem.getParent('fieldset'));
				this.createdHidden = true;
			}
			
			elem.addEvent('click', function(e){
				e.stop();
				$('hiddenRating').value = elem.rating;
				this.sendRating();
			}.bind(this));
		}
		else
			elem.getElement('input').addEvent('change', function(e){e.stop(); this.sendRating();}.bind(this));
		
		}.bind(this));

	},

	sendRating: function(){
		
		
		if(!Browser.Engine.trident){
			this.form.send();
		}
		else{
			//alle input type hidden bekommen
			var post = '';
			this.form.getElements('input').each(function(elem, index){
				if(elem.get('type').test('hidden'))
					post += elem.get('name') + '=' +  elem.get('value') + '&';		
			});
			this.IE6Request.send(post);
		}
		
		this.element.setStyle('height', this.element.getSize().y);
		this.element.set('html', '');
		this.element.addClass('loading_rating');
	}
});



///////////////////////////////////////////////////////
// senseo.js

var dataBuffer = new Array();

function closeOverlay() {
	var form = $('senseoform');
	form.getElements('input').each(function(input) {
		switch (input.type) {
			case 'checkbox':
			case 'radio':
				if (input.checked) {
					dataBuffer[input.id] = 'checked';
				} else {
					dataBuffer[input.id] = '';
				}
				break;
			case 'text':
			default:
				if (input.value != '') {
					dataBuffer[input.id] = input.value;
				} else {
					dataBuffer[input.id] = '';
				}
				break;
		}
	});	
	MV_Overlay.close();
}

function initSenseoForm() {
	var form = $('senseoform');
	form.addEvent('submit', function(e) {
		e.stop();
		var errors = 0;
		form.getElements('.validate').each(function(input) {
			if ((input.value == '') || ((input.type == 'checkbox') && (input.checked != true))) {
				if (input.type == 'text') {
					input.addClass('error').morph({
						'border-color': '#f00',
						'background-color': '#ffebe8'
					});
				} else if (input.type == 'checkbox') {
					var checkbox_div = new Element('div', {
						'class': 'error'
					});
					checkbox_div.wraps(input).morph({
						'background-color': '#f00',
						'padding-bottom': '2px',
						'padding-top': '8px',
						'padding-left': '2px',
						'padding-right': '2px',
						'display': 'inline'
					});
				}
				errors++;
			} else if ((input.hasClass('error') && (input.value != ''))) {
				input.removeClass('error').morph({
					'border-color': '#fff',
					'background-color': '#fff'
				});
			}
		});
		if (errors) {
			var error_msg = form.getElement('.error-message-box');
			if (error_msg) {
				error_msg.setStyles({
					'opacity': '0',
					'display': 'block'
				});
				error_msg.morph({
					'opacity': '1'
				});
			} else {
				var error_msg_div = new Element('div', {
					'class': 'error-message-box',
					'id': 'introtext',
					'html': 'Bitte füllen Sie die Pflichtfelder aus!'
				});
				var introtext = $('introtext');
				var errormsgbox = $('errormsgbox');
				error_msg_div.inject(errormsgbox, 'after');
				introtext.dispose();
				error_msg_div.setStyles({
					'opacity': '0',
					'display': 'block'
				});
				error_msg_div.morph({
					'opacity': '1'
				});
			}
		}
		
		if (!errors) {
			this.set('send', {onComplete: function(response) {
				if (response == 'fail') {
					var msg_div = new Element('div', {
						'class': 'error-message-box',
						'id': 'introtext',
						'html': 'Bei der Übermittlung ist etwas schief gegangen, probieren Sie es später noch einmal.'
					});
				} else if (response == 'success') {
					var msg_div = new Element('div', {
						'class': 'success-message-box',
						'id': 'introtext',
						'html': 'Die Bewerbung wurde erfolgreich übermittelt!'
					});
				}
				var introtext = $('introtext');
				var errormsgbox = $('errormsgbox');
				msg_div.inject(errormsgbox, 'after');
				introtext.dispose();
				msg_div.setStyles({
					'opacity': '0',
					'display': 'block'
				});
				msg_div.morph({
					'opacity': '1'
				});
				
				closeOverlay.delay(3000);
			}});
			this.send();
		}
		
		return false;
	});
	
	if (dataBuffer) {
		for (var i in dataBuffer) {
			if (typeof dataBuffer[i] == "function") continue;
			if (dataBuffer[i] != 'checked') {
				$(i).value = dataBuffer[i];
			} else {
				$(i).checked = 'checked';
			}
		}
	}
}



///////////////////////////////////////////////////////
// suggestion.js


//Class für AjaxfText -> vorschlag als liste holen
/*
element =  das fText, für die Vorschläge per Ajax geholt werden sollen
*/
var Suggestion = new Class({

	initialize: function(element){
		this.element = element;
		if(this.element.getProperty('alt') == null || this.element.getProperty('alt') == '')
			this.ajaxUrl = '/ajax/suggest/';
		else if (this.element.getProperty('alt') != '__INUSE__')
			this.ajaxUrl = this.element.getProperty('alt');

		if (this.element.getProperty('alt') != '__INUSE__')
		{
			this.startValue = this.element.value;
			this.elementName = this.element.name;
			this.hiddenAltValue = this.element.id+'Alt';
			element.setProperty('autocomplete', 'off');
			this.searchValue;
			this.searchId;
			this.WrapperWidth = this.element.getStyle('padding-left').toInt() + this.element.getStyle('padding-right').toInt() + this.element.getStyle('width').toInt();
			this.Wrapper = new Element('div', {'class': 'ajaxSuggWrapper', 'style': 'width: '+ this.WrapperWidth +'px'});
			this.requestSuggestion = new Request({
				url: this.ajaxUrl,
				method: 'post',
				onSuccess: function(result){this.tmpContent = result; this.dumpSuggestion();}.bind(this),
				onFailure: function(){this.Error = true;}.bind(this)
			});
			this.tmpContent;
			this.Highlighted = 0;
			this.preHighlighted;
			this.result_amount = 0;
			this.result_isShown = false;
			this.WrapperExists = false;
			this.WrapperHover = false;
			this.Wrapper.addEvent('mouseover',function(){this.WrapperHover = true;}.bind(this));
			this.Wrapper.addEvent('mouseout',function(){this.WrapperHover = false;}.bind(this));

			this.Error = false;
			this.createEvent();

			element.setProperty('alt', '__INUSE__');
		}
	},

	getSuggestion: function(){
		this.requestSuggestion.cancel();
		this.requestSuggestion.send('search/type='+ this.elementName +'&search/term='+ this.searchValue);
	},

	dumpSuggestion: function(){
		this.Wrapper.set('html', this.tmpContent);
		//nur falls results zurückkommen
		if(this.Wrapper.getElement('li')){
			var tmpHeight = this.element.getStyle('height').toInt() + (2*this.element.getStyle('padding-top').toInt()) + (2*this.element.getStyle('border-width').toInt());
				if(Browser.Engine.trident && this.element.getStyle('height').toInt() < 5)
					tmpHeight = tmpHeight + 13;

				this.Wrapper.setStyles({
				'position': 'absolute',
				'z-index': '2147483647',
				top: this.element.getPosition().y + tmpHeight,
				left: this.element.getPosition().x
				});

			//auf den einzelnen li muss event rauf
			var tmpli = this.Wrapper.getElements('li');
			this.result_amount = tmpli.length;
			tmpli.each(function(elem){
				this.createLiEvent(elem);
			}.bind(this));

			this.Wrapper.setStyle('display', 'block');
			this.result_isShown = true;
				if(!this.WrapperExists && !this.Error){
					this.Wrapper.inject(document.body);
					this.resetValues();
					this.WrapperExists = true;
				}
				else{this.Error = false;}
		}else{this.Wrapper.setStyle('display', 'none');}
	},

	createEvent: function(){
		this.element.addEvents({
			'keydown': function(e){
			if(e.key.test('enter')){this.insertIntoElement(this.Wrapper.getElements('li')[this.Highlighted - 1]);this.reset(); return false;}
			}.bind(this),

			'keyup': function(e){
			if(!e.key.test('left') || !e.key.test('right')){
				if(e.key.test('enter')){return false;}
				if(this.element.value.length > 1 && !(e.key.test('up') || e.key.test('down') )){
					this.searchValue = escape(this.htmlToString(this.element.value));
					this.resetValues();
					this.getSuggestion();
				}
				if(this.result_isShown && (e.key.test('up') || e.key.test('down')) ){
					this.changeHighlighted(e.key);
				}
			}
			}.bind(this),

			'blur' : function(e){
				e.stop();
				if(!this.WrapperHover){this.reset();}
				if(this.element.value == ''){this.element.value = this.startValue;}
			}.bind(this),

			'focus' : function(e){
				e.stop();
				//console.log('oh');
				if(this.element.value == this.startValue){this.element.value = '';}
			}.bind(this)
		});
	},

	createLiEvent: function(elem){
		elem.addEvent('click', function(e){
				e.stop();
				this.insertIntoElement(elem);
				this.reset();
				//this.element.form.submit();
				return false;
		}.bind(this));
	},

	htmlToString: function(string){
		string = string.replace(/&/g,'&amp;').
					 replace(/>/g,'&gt;').
					 replace(/</g,'&lt;').
					 replace(/"/g,'&quot;').
					 replace(/\'/g,'&apos;');
		return string;
	},

	changeHighlighted: function(dir){
		this.preHighlighted = this.Highlighted;
		var tmpbool = false;

			//zähler setzten
			if(dir.test('down') && this.Highlighted < this.result_amount){this.Highlighted++; tmpbool = true;}
			if(this.Highlighted > 1 && dir.test('up')){this.Highlighted--; tmpbool = true;}

			if(tmpbool){
				if( (this.preHighlighted >= 1) && (this.preHighlighted <= this.result_amount) ){
					this.Wrapper.getElements('li')[this.preHighlighted -1].toggleClass('hover');
				}
				var newLi = this.Wrapper.getElements('li')[this.Highlighted - 1];
				newLi.toggleClass('hover');
			}


	},

	insertIntoElement: function(elem)
	{
		var alt = elem.getChildren('a')[0].getProperty('alt');

		var txt = elem.getChildren('a')[0].get('text');
		this.element.value = txt;
		this.searchValue = this.element.value;
		if(alt != null && $(this.hiddenAltValue))
			$(this.hiddenAltValue).value = alt;
		/*else
			//console.log('HIDDEN NOT FOUND: '+this.hiddenAltValue);
			*/
	},

	resetValues: function(){
		this.Highlighted = 0;
		this.result_amount = 0;
		this.result_isShown = false;
	},
	reset: function(){
		this.Wrapper.set('html', '');
		this.Wrapper.setStyle('display', 'none');
			this.resetValues();
	}
});



///////////////////////////////////////////////////////
// swfobject.js

/* SWFObject v2.1 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var b="undefined",Q="object",n="Shockwave Flash",p="ShockwaveFlash.ShockwaveFlash",P="application/x-shockwave-flash",m="SWFObjectExprInst",j=window,K=document,T=navigator,o=[],N=[],i=[],d=[],J,Z=null,M=null,l=null,e=false,A=false;var h=function(){var v=typeof K.getElementById!=b&&typeof K.getElementsByTagName!=b&&typeof K.createElement!=b,AC=[0,0,0],x=null;if(typeof T.plugins!=b&&typeof T.plugins[n]==Q){x=T.plugins[n].description;if(x&&!(typeof T.mimeTypes!=b&&T.mimeTypes[P]&&!T.mimeTypes[P].enabledPlugin)){x=x.replace(/^.*\s+(\S+\s+\S+$)/,"$1");AC[0]=parseInt(x.replace(/^(.*)\..*$/,"$1"),10);AC[1]=parseInt(x.replace(/^.*\.(.*)\s.*$/,"$1"),10);AC[2]=/r/.test(x)?parseInt(x.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof j.ActiveXObject!=b){var y=null,AB=false;try{y=new ActiveXObject(p+".7")}catch(t){try{y=new ActiveXObject(p+".6");AC=[6,0,21];y.AllowScriptAccess="always"}catch(t){if(AC[0]==6){AB=true}}if(!AB){try{y=new ActiveXObject(p)}catch(t){}}}if(!AB&&y){try{x=y.GetVariable("$version");if(x){x=x.split(" ")[1].split(",");AC=[parseInt(x[0],10),parseInt(x[1],10),parseInt(x[2],10)]}}catch(t){}}}}var AD=T.userAgent.toLowerCase(),r=T.platform.toLowerCase(),AA=/webkit/.test(AD)?parseFloat(AD.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,q=false,z=r?/win/.test(r):/win/.test(AD),w=r?/mac/.test(r):/mac/.test(AD);/*@cc_on q=true;@if(@_win32)z=true;@elif(@_mac)w=true;@end@*/return{w3cdom:v,pv:AC,webkit:AA,ie:q,win:z,mac:w}}();var L=function(){if(!h.w3cdom){return }f(H);if(h.ie&&h.win){try{K.write("<script id=__ie_ondomload defer=true src=//:><\/script>");J=C("__ie_ondomload");if(J){I(J,"onreadystatechange",S)}}catch(q){}}if(h.webkit&&typeof K.readyState!=b){Z=setInterval(function(){if(/loaded|complete/.test(K.readyState)){E()}},10)}if(typeof K.addEventListener!=b){K.addEventListener("DOMContentLoaded",E,null)}R(E)}();function S(){if(J.readyState=="complete"){J.parentNode.removeChild(J);E()}}function E(){if(e){return }if(h.ie&&h.win){var v=a("span");try{var u=K.getElementsByTagName("body")[0].appendChild(v);u.parentNode.removeChild(u)}catch(w){return }}e=true;if(Z){clearInterval(Z);Z=null}var q=o.length;for(var r=0;r<q;r++){o[r]()}}function f(q){if(e){q()}else{o[o.length]=q}}function R(r){if(typeof j.addEventListener!=b){j.addEventListener("load",r,false)}else{if(typeof K.addEventListener!=b){K.addEventListener("load",r,false)}else{if(typeof j.attachEvent!=b){I(j,"onload",r)}else{if(typeof j.onload=="function"){var q=j.onload;j.onload=function(){q();r()}}else{j.onload=r}}}}}function H(){var t=N.length;for(var q=0;q<t;q++){var u=N[q].id;if(h.pv[0]>0){var r=C(u);if(r){N[q].width=r.getAttribute("width")?r.getAttribute("width"):"0";N[q].height=r.getAttribute("height")?r.getAttribute("height"):"0";if(c(N[q].swfVersion)){if(h.webkit&&h.webkit<312){Y(r)}W(u,true)}else{if(N[q].expressInstall&&!A&&c("6.0.65")&&(h.win||h.mac)){k(N[q])}else{O(r)}}}}else{W(u,true)}}}function Y(t){var q=t.getElementsByTagName(Q)[0];if(q){var w=a("embed"),y=q.attributes;if(y){var v=y.length;for(var u=0;u<v;u++){if(y[u].nodeName=="DATA"){w.setAttribute("src",y[u].nodeValue)}else{w.setAttribute(y[u].nodeName,y[u].nodeValue)}}}var x=q.childNodes;if(x){var z=x.length;for(var r=0;r<z;r++){if(x[r].nodeType==1&&x[r].nodeName=="PARAM"){w.setAttribute(x[r].getAttribute("name"),x[r].getAttribute("value"))}}}t.parentNode.replaceChild(w,t)}}function k(w){A=true;var u=C(w.id);if(u){if(w.altContentId){var y=C(w.altContentId);if(y){M=y;l=w.altContentId}}else{M=G(u)}if(!(/%$/.test(w.width))&&parseInt(w.width,10)<310){w.width="310"}if(!(/%$/.test(w.height))&&parseInt(w.height,10)<137){w.height="137"}K.title=K.title.slice(0,47)+" - Flash Player Installation";var z=h.ie&&h.win?"ActiveX":"PlugIn",q=K.title,r="MMredirectURL="+j.location+"&MMplayerType="+z+"&MMdoctitle="+q,x=w.id;if(h.ie&&h.win&&u.readyState!=4){var t=a("div");x+="SWFObjectNew";t.setAttribute("id",x);u.parentNode.insertBefore(t,u);u.style.display="none";var v=function(){u.parentNode.removeChild(u)};I(j,"onload",v)}U({data:w.expressInstall,id:m,width:w.width,height:w.height},{flashvars:r},x)}}function O(t){if(h.ie&&h.win&&t.readyState!=4){var r=a("div");t.parentNode.insertBefore(r,t);r.parentNode.replaceChild(G(t),r);t.style.display="none";var q=function(){t.parentNode.removeChild(t)};I(j,"onload",q)}else{t.parentNode.replaceChild(G(t),t)}}function G(v){var u=a("div");if(h.win&&h.ie){u.innerHTML=v.innerHTML}else{var r=v.getElementsByTagName(Q)[0];if(r){var w=r.childNodes;if(w){var q=w.length;for(var t=0;t<q;t++){if(!(w[t].nodeType==1&&w[t].nodeName=="PARAM")&&!(w[t].nodeType==8)){u.appendChild(w[t].cloneNode(true))}}}}}return u}function U(AG,AE,t){var q,v=C(t);if(v){if(typeof AG.id==b){AG.id=t}if(h.ie&&h.win){var AF="";for(var AB in AG){if(AG[AB]!=Object.prototype[AB]){if(AB.toLowerCase()=="data"){AE.movie=AG[AB]}else{if(AB.toLowerCase()=="styleclass"){AF+=' class="'+AG[AB]+'"'}else{if(AB.toLowerCase()!="classid"){AF+=" "+AB+'="'+AG[AB]+'"'}}}}}var AD="";for(var AA in AE){if(AE[AA]!=Object.prototype[AA]){AD+='<param name="'+AA+'" value="'+AE[AA]+'" />'}}v.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AF+">"+AD+"</object>";i[i.length]=AG.id;q=C(AG.id)}else{if(h.webkit&&h.webkit<312){var AC=a("embed");AC.setAttribute("type",P);for(var z in AG){if(AG[z]!=Object.prototype[z]){if(z.toLowerCase()=="data"){AC.setAttribute("src",AG[z])}else{if(z.toLowerCase()=="styleclass"){AC.setAttribute("class",AG[z])}else{if(z.toLowerCase()!="classid"){AC.setAttribute(z,AG[z])}}}}}for(var y in AE){if(AE[y]!=Object.prototype[y]){if(y.toLowerCase()!="movie"){AC.setAttribute(y,AE[y])}}}v.parentNode.replaceChild(AC,v);q=AC}else{var u=a(Q);u.setAttribute("type",P);for(var x in AG){if(AG[x]!=Object.prototype[x]){if(x.toLowerCase()=="styleclass"){u.setAttribute("class",AG[x])}else{if(x.toLowerCase()!="classid"){u.setAttribute(x,AG[x])}}}}for(var w in AE){if(AE[w]!=Object.prototype[w]&&w.toLowerCase()!="movie"){F(u,w,AE[w])}}v.parentNode.replaceChild(u,v);q=u}}}return q}function F(t,q,r){var u=a("param");u.setAttribute("name",q);u.setAttribute("value",r);t.appendChild(u)}function X(r){var q=C(r);if(q&&(q.nodeName=="OBJECT"||q.nodeName=="EMBED")){if(h.ie&&h.win){if(q.readyState==4){B(r)}else{j.attachEvent("onload",function(){B(r)})}}else{q.parentNode.removeChild(q)}}}function B(t){var r=C(t);if(r){for(var q in r){if(typeof r[q]=="function"){r[q]=null}}r.parentNode.removeChild(r)}}function C(t){var q=null;try{q=K.getElementById(t)}catch(r){}return q}function a(q){return K.createElement(q)}function I(t,q,r){t.attachEvent(q,r);d[d.length]=[t,q,r]}function c(t){var r=h.pv,q=t.split(".");q[0]=parseInt(q[0],10);q[1]=parseInt(q[1],10)||0;q[2]=parseInt(q[2],10)||0;return(r[0]>q[0]||(r[0]==q[0]&&r[1]>q[1])||(r[0]==q[0]&&r[1]==q[1]&&r[2]>=q[2]))?true:false}function V(v,r){if(h.ie&&h.mac){return }var u=K.getElementsByTagName("head")[0],t=a("style");t.setAttribute("type","text/css");t.setAttribute("media","screen");if(!(h.ie&&h.win)&&typeof K.createTextNode!=b){t.appendChild(K.createTextNode(v+" {"+r+"}"))}u.appendChild(t);if(h.ie&&h.win&&typeof K.styleSheets!=b&&K.styleSheets.length>0){var q=K.styleSheets[K.styleSheets.length-1];if(typeof q.addRule==Q){q.addRule(v,r)}}}function W(t,q){var r=q?"visible":"hidden";if(e&&C(t)){C(t).style.visibility=r}else{V("#"+t,"visibility:"+r)}}function g(s){var r=/[\\\"<>\.;]/;var q=r.exec(s)!=null;return q?encodeURIComponent(s):s}var D=function(){if(h.ie&&h.win){window.attachEvent("onunload",function(){var w=d.length;for(var v=0;v<w;v++){d[v][0].detachEvent(d[v][1],d[v][2])}var t=i.length;for(var u=0;u<t;u++){X(i[u])}for(var r in h){h[r]=null}h=null;for(var q in swfobject){swfobject[q]=null}swfobject=null})}}();return{registerObject:function(u,q,t){if(!h.w3cdom||!u||!q){return }var r={};r.id=u;r.swfVersion=q;r.expressInstall=t?t:false;N[N.length]=r;W(u,false)},getObjectById:function(v){var q=null;if(h.w3cdom){var t=C(v);if(t){var u=t.getElementsByTagName(Q)[0];if(!u||(u&&typeof t.SetVariable!=b)){q=t}else{if(typeof u.SetVariable!=b){q=u}}}}return q},embedSWF:function(x,AE,AB,AD,q,w,r,z,AC){if(!h.w3cdom||!x||!AE||!AB||!AD||!q){return }AB+="";AD+="";if(c(q)){W(AE,false);var AA={};if(AC&&typeof AC===Q){for(var v in AC){if(AC[v]!=Object.prototype[v]){AA[v]=AC[v]}}}AA.data=x;AA.width=AB;AA.height=AD;var y={};if(z&&typeof z===Q){for(var u in z){if(z[u]!=Object.prototype[u]){y[u]=z[u]}}}if(r&&typeof r===Q){for(var t in r){if(r[t]!=Object.prototype[t]){if(typeof y.flashvars!=b){y.flashvars+="&"+t+"="+r[t]}else{y.flashvars=t+"="+r[t]}}}}f(function(){U(AA,y,AE);if(AA.id==AE){W(AE,true)}})}else{if(w&&!A&&c("6.0.65")&&(h.win||h.mac)){A=true;W(AE,false);f(function(){var AF={};AF.id=AF.altContentId=AE;AF.width=AB;AF.height=AD;AF.expressInstall=w;k(AF)})}}},getFlashPlayerVersion:function(){return{major:h.pv[0],minor:h.pv[1],release:h.pv[2]}},hasFlashPlayerVersion:c,createSWF:function(t,r,q){if(h.w3cdom){return U(t,r,q)}else{return undefined}},removeSWF:function(q){if(h.w3cdom){X(q)}},createCSS:function(r,q){if(h.w3cdom){V(r,q)}},addDomLoadEvent:f,addLoadEvent:R,getQueryParamValue:function(v){var u=K.location.search||K.location.hash;if(v==null){return g(u)}if(u){var t=u.substring(1).split("&");for(var r=0;r<t.length;r++){if(t[r].substring(0,t[r].indexOf("="))==v){return g(t[r].substring((t[r].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(A&&M){var q=C(m);if(q){q.parentNode.replaceChild(M,q);if(l){W(l,true);if(h.ie&&h.win){M.style.display="block"}}M=null;l=null;A=false}}}}}();


///////////////////////////////////////////////////////
// timepicker.js

var TimeSpinner=new Class({Implements:[Events,Options],version:0.4,options:{increment:15,separator:":",range:{low:-1,high:-1},delay:200,alarm:[],doAlarm:Class.empty},initialize:function(a,c,b){if(!a)return false;$defined(c)&&this.setOptions(c);this.timespinner=a;this.date=new Date;if($defined(b))if(b instanceof Date)this.date=b;else{c=b%60;this.date.setMinutes(c);this.date.setHours((b-c)/60)}this.doaction="";b=(new Element("button",{type:"button"})).addClass("timespinner_plus").injectAfter(a); b.addEvent("mousedown",function(){this.doStart("inc")}.pass("inc",this));b.addEvent("mouseup",function(){this.doStop()}.pass("",this));b=(new Element("button",{type:"button"})).addClass("timespinner_minus").injectAfter(a);b.addEvent("mousedown",function(){this.doStart("dec")}.pass("dec",this));b.addEvent("mouseup",function(){this.doStop()}.pass("",this));this.fixTime();this.addEvent("doclick",function(){switch(this.doaction){case "inc":this.incTime();break;case "dec":this.decTime();break;case "cancel":this.doaction= "";return;default:return}this.fireEvent("doclick","",this.options.delay)});this.addEvent("doAlarm",this.options.doAlarm)},doStart:function(a){this.doaction=a;this.fireEvent("doclick","",0)},doStop:function(){this.doaction="cancel"},setTime:function(a){if(a instanceof Date)this.date=a;else this.date.setTime(a);this.fixTime()},getTime:function(){return this.date},setInc:function(a){this.options.increment=a;this.fixTime()},getInc:function(){return this.options.increment},fixTime:function(){var a=this.date.getMinutes(); this.date.setMinutes(a-a%this.options.increment);if(this.options.range.high>-1){var c=this.date.getHours()*60+this.date.getMinutes();if(c>=this.options.range.high){a=this.options.range.high%60;this.date.setMinutes(a);this.date.setHours((this.options.range.high-a)/60)}}if(this.options.range.low>-1){c=this.date.getHours()*60+this.date.getMinutes();if(c<=this.options.range.low){a=this.options.range.low%60;this.date.setMinutes(a);this.date.setHours((this.options.range.low-a)/60)}}var b=this.date.getHours(); a=this.date.getMinutes();this.timespinner.value=(b<10?"0":"")+b+this.options.separator+(a<10?"0":"")+a;c=this.date.getHours()*60+this.date.getMinutes();this.options.alarm.each(function(d){d==c&&this.fireEvent("doAlarm",{who:this.timespinner.id,time:d},0)},this)},incTime:function(a){if($defined(a)==false)a=this.options.increment;this.date.setTime(this.date.getTime()+a*6E4);this.fixTime()},decTime:function(a){if($defined(a)==false)a=this.options.increment;this.date.setTime(this.date.getTime()-a*6E4); this.fixTime()}});TimeSpinner.implement(new Events,new Options);


///////////////////////////////////////////////////////
// videoplayerinclude.js

//var swfObjectScript = Asset.javascript('/js/swfobject.js');
var startVideoPlayer = function (dir, width, height, duration) {
	if (dir) {
		var flashVars = {file: dir,videoWidth: width,videoHeight: height,duration: duration};
		var parameter = {quality: 'best',loop: 'false',scale: 'noscale',wmode: 'window',devicefont: 'false',bgcolor: '#000000',menu: 'false',allowFullScreen: 'true',allowScriptAccess:'sameDomain',salign: 'lt'};
		var attributes = {id: 'videoplayer',name: 'videoplayer',align: 'middle'};
		swfobject.embedSWF("/flash/videoplayer.swf", "MV_Player", "630", "472", "9.0.0", "", flashVars, parameter, attributes);
	}
	else {
		var element = $('MV_Player');
		if (element) {
			element.set('html', '<strong>Dieses Video ist sichtbar, sobald dessen Konvertierung abgeschlossen ist.</strong>');
		}
	}
}


///////////////////////////////////////////////////////
// /export/home/www/meinverein/meinverein-test/webroot/js/common.js/domready.js


window.addEvent('domready', function(){
	
	if(Browser.Engine.trident4)
		document.body.className = 'script';

	//commercialChecker();
	//overlay starten
	MV_Overlay = new Overlay();

	//alle spans reingeneriern
	updateScreenLayout($(document.body));

	/*DEPRECATED -> domwalker
	//vorschlag event auf ajaxfTexte legen
	$$('.ajaxfText').each(function(elem){var fTextProposal = new Suggestion(elem); });

	//hover events auf auswahllisten mit löschfunktion, beispiel: interessen entfernen etc.
	$$('.removalList li label').each(function(elem) {
			elem.addEvent('mouseover', function() {this.getParent().toggleClass('hover');});
			elem.addEvent('mouseout', function() {this.getParent().toggleClass('hover');});
			elem.addEvent('click', function() {
			if(this.getParent().getParent().getChildren().length > 1) {this.getParent().destroy();	}
		});
	});
*/
	//abteilungen öffnen
	if ($('Filter')){
		var FilterH4 = $('Filter').getElement('h4');

	if(FilterH4 && FilterH4.getElement('.selected')){
		filterIndi = false;
		var tmpContent = FilterH4.getParent().getElement('.content');
		/*if (tmpContent)
			tmpContent.setStyles({'opacity' : 0, 'display' : 'none'});
		*/
		//overlay zum nicht-selektieren
		generateItems(FilterH4, 'span', new Array('overlay'), 'bottom');

		//effekt
		//filterSlide = new Fx.Morph(tmpContent, {onComplete : function(){if(!filterIndi){this.element.setStyle('display', 'none');}}});
		var is_leaving = false;
		var filterTimeout;
			FilterH4.getNext('.content').addEvent('mouseleave', function(e){
				e.stop();
				if(!is_leaving){
					is_leaving = true;
					filterTimeout = filterToggler.delay(500);
				}
			});
			FilterH4.getNext('.content').addEvent('mouseenter', function(e){
				e.stop();
				if(is_leaving){
					is_leaving = false;
					$clear(filterTimeout);
				}
			});


			FilterH4.addEvent('click', function(e){
				e.stop();
				if(is_leaving){
					$clear(filterTimeout);
				}
				filterToggler();
				is_leaving = false;
			});

		}
	}
	/*DEPRECATED -> domwalker
	//header scroller
	$$('#ForeignProfiles .content').each(function(elem){
		if(elem.getElements('li').length > 3){
			var foreignSlider = new hSlider(elem, 90, 3, 5);
			}
		});

	//alle Countdowns starten
	$$('.countdown').each(function(elem){var countdown = new Countdown(elem);});

	//textareas events für pinboard etc.
	$$('.board .fTextarea').each(function(elem){
		elem.addEvents({
		'focus' : textareaFocus,
		'blur'	: textareaBlur
		});

	});
*/

	//colorThemeRadioSelection();


	//let cancel buttons in pinboard close form section
	/*DEPRECATED -> domwalker
	$$('.pinboard input.fCancel').each(function(el)
	{
		el.addEvent('click', function()
		{
			var fieldset = this.getParent('fieldset');
			if (fieldset)
				fieldset.addClass('closed');
		}.bind(el));
	});
	*/
	//initialize image upload for profile pic
	/*DEPRECATED -> domwalker
	var portraitUpload = $('userPortraitUpload');
	if (portraitUpload){

		var submitUrl = '';
		var cancelUrl = '';

				if (portraitUpload.hasClass('assoc_logo'))
				{
			var assocId = portraitUpload.getElement('.mcard').get('title');
			portraitUpload.getElement('.mcard').removeProperty('title');
			submitUrl = '/associations/set_logo/'+assocId+'/';
			cancelUrl = '/associations/restore_logo/'+assocId+'/';
		}
		else if (portraitUpload.hasClass('assoc_photo'))
				{
			var assocId = portraitUpload.getElement('.mcard').get('title');
			portraitUpload.getElement('.mcard').removeProperty('title');
			submitUrl = '/association_settings/set_photo/'+assocId+'/';
			cancelUrl = '/association_settings/restore_photo/'+assocId+'/';
		}
		else
				{
			submitUrl = '/profile/set_profile_image/';
			cancelUrl = '/profile/restore_profile_image/';
		}

		var portraitUploader = new ProfileImageUpload({
			'submitUrl': submitUrl,
			'cancelUrl': cancelUrl,
			url: $('userPortraitUpload').action,
			fieldName: 'Media/upload',
			path: '/flash/Swiff.Uploader.swf',
			limitSize: 50 * 1024 * 1024, // 50Mb @TODO:[SU] What maximum filesize to use?
			limitFiles: 1,
			typeFilter: {
				'Images (*.jpg, *.jpeg, *.gif, *.png, *.bmp, *.tga, *.pcx)': '*.jpg; *.jpeg; *.gif; *.png; *.bmp; *.tga; *.pcx'
			},
			// The changed parts!
			debug: true, // enable logs, uses console.log
			target: 'userPortraitSelectImage' // the element for the overlay (Flash 10 only)
		});

		var cancelButton = $('userPortraitUploadCancel');
		if (cancelButton) {
			cancelButton.addEvent('click', function(e) {
				e.stop();
				portraitUploader.cancel();
				return false;
			});
		}

		var submitButton = $('userPortraitUploadSubmit');
		if (submitButton) {
			submitButton.addEvent('click', function(e){
				e.stop();
				portraitUploader.submit();
				return false;
			});
		}

		$('userPortraitSelectImage').addEvent('click', function(e) {
			e.stop();
			portraitUploader.browse();
			return false;
		});

		$('userPortraitUploadImage').addEvent('click', function(e)
		{
			e.stop();
			portraitUploader.upload();
			return false;
		});
	}


	/*DEPRECATED -> domwalker
	$$('.pinboard .delete_entry a').each(function(link)
	{
			link.addEvent('click', function(e)
			{
				e.stop();
				new MessageBox('/overlay/question_box/100',
				{
					onYes: function()
					{
						window.location.href = link.href;
					}
				})
				return false;
			});
	});
	*/
	checkForInterest();
	generateInfoboxes();

	/*DEPRECATED -> domwalker
		//drag_selection
		$$('.drag_selection strong').each(function(elem){
				 var tmp = generateItems(elem, 'span', new Array('toggle_indicator'), 'bottom')
				 elem.addEvent('click', function(e){
					e.stop();
					this.getParent('.drag_selection').toggleClass('open_drag_selection');
					});
			});
	*/
	var imageSelection = new CardFormSelector({'formId': 'imageSelection'});

	/*DEPRECATED -> domwalker
	$$('.autoclear').each(function(el) {
		el.autoclearText = el.get('title');
		el.removeProperty('title');
		el.addEvent('focus', autoclearFocus);
		el.addEvent('blur',  autoclearBlur);
	});
	*/

});




