/**
 * @author krampitz
 */

//----------------------------
// basisfunktionen
//----------------------------

/**
 * Prueft, ob der verwendete Browser Internet Explorer ist.
 * @return boolean true, wenn User Agent IE ist, sonst false
 */
function isIE(version){
	if(navigator.appName == "Microsoft Internet Explorer"){
		if(! version)
			return true;
		if(version == 6 && navigator.appVersion.search(/MSIE 6.0/) != -1)
			return true;
		if(version == 7 && navigator.appVersion.search(/MSIE 7.0/) != -1)
			return true;
		if(version == 8 && navigator.appVersion.search(/MSIE 8.0/) != -1)
			return true;
	}
	return false;
}

/**
 * Prueft, ob der verwendete Browser Internet Explorer 6 oder aelter ist.
 * @return boolean true, wenn User Agent IE6 oder aelter ist, sonst false
 *//*
function isIE6OrLess(){
	var agt=navigator.userAgent.toLowerCase();
	var is_major = parseInt(navigator.appVersion);
	var is_minor = parseFloat(navigator.appVersion);
	var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
	return (is_ie && (is_major == 4) && (agt.search(/msie [56]\./)!=-1) );
}*/

/**
 * Prueft, ob point innerhalb der Grenzen von elm liegt. Gibt true oder false zurueck.
 * @param {x:integer, y:integer} point
 * @param {Object} elm
 * @return boolean true, wenn point innerhalb von elm liegt, sonst false
 */
function isInElement(point, elm) {
	var x = point.x;
	var y = point.y;
	var elm = elm;

	 var dOffset = document.viewport.getScrollOffsets();

	if ((x > elm.viewportOffset()[0]+elm.cumulativeScrollOffset()[0]+dOffset[0]+elm.getWidth() || x < elm.viewportOffset()[0]+elm.cumulativeScrollOffset()[0]+dOffset[0])
	|| (y > elm.viewportOffset()[1]+elm.cumulativeScrollOffset()[1]+dOffset[1]+elm.getHeight() || y < elm.viewportOffset()[1]+elm.cumulativeScrollOffset()[1]+dOffset[1])) {
		return false;
	} else {
		return true;
	}
}

/**
 * Stellt Debug-Messages für Firefox, IE8, Opera, Safari, Chrome (Konsole) und IE<8 (alert) zur Verfügung.
 * @param string text
 * @return void
 */
function lg(text) {
	if (false)
	{
		if (typeof(opera) != "undefined" && opera != null) {
			opera.postError(text);
			return;
		}
		else
			if (typeof(console) != "undefined" && console != null) {
				console.log(text);
				return;
			}
	}
}

// *******************************
// * Kalender Overlay
// *    in $(document).ready wird noch ein Klick-Handler 
// *    auf den Startseiten_Teaser gesetzt
// *******************************

// setzt den Klick-Handler fuer alle Kalender-internen Links
function setClickHandlerCalendar() {
	jQuery('.blockPage a.calendar-internal,.blockPage a.fn-tab').click(function(event){
		event.preventDefault();
		if (jQuery(this).attr('id') == 'calendar-overlay-close') {
			jQuery.unblockUI();
		} else {
			doCalendarAjax(jQuery(this).attr('href'));
		}
	});
}
// Kalender-Overlay-AJAX-Reload und Setzen der Klick-Handler
function doCalendarAjax(href) {
	href = href + '&overlay=1';
	new Ajax.Request(href, {
		method: 'GET',
		onSuccess: function(response) {
			jQuery('.blockPage').html(response.responseText);
			window.setTimeout('setClickHandlerCalendar()', 1);
		}
	});
}


// *******************************
// * Array Funktionen
// *******************************
 Array.prototype.in_array = function(needle) {
	for (var i = 0; i < this.length; i++) {
		if(needle === this[i])
			return true;
	}
	return false;
}



var Selectpulldown;
var MainnavigationLayer;
var AjaxLayer;
var metaTimer = undefined;
var jsPulldowns = [];
var initiativen = [];
var ajaxRoutinePostfix = 'index.php';

var etrackerWhitelist = new Array('aktion-mensch.de/lotterie', 'aktion-mensch.de/sonderverlosung', 'aktion-mensch.de/zusammen');

(function($){
	/**
	 * Prueft, ob point innerhalb der Grenzen von elm liegt. Gibt true oder false zurueck.
	 * @param {x:integer, y:integer} point
	 * @param {Object} elm
	 * @return boolean true, wenn point innerhalb von elm liegt, sonst false
	 */
	function isInElementJQ(point, elm) {
		var x = point.x;
		var y = point.y;
		var elm = elm;

		if (x == 0 && y == 0) {
			return true;
		}

		if ((x > elm.offset().left+elm.width() || x < elm.offset().left)
		|| (y > elm.offset().top+elm.height() || y < elm.offset().top)) {
			return false;
		} else {
			return true;
		}
	}


	// callback fuer suchbereich-auswahl
	 setSearchLocation =  function(elm) {
		if ($('#searchcontainer') && $('#pd-search') && $('#searchlocation')) {
			elm.addClass('active');

			// hidden field aktualisieren
			$('#searchlocation').attr('value', elm.data('collection'));

			// Platzhalter aktualiseren und ggf. Placeholder-Plugin nochmal anwenden
			placeholderValue = 'Suche (' + elm.data('caption') + ')';
			if (placeholderValue.length > 23) {
				placeholderValue = placeholderValue.substr(0,23)+'...';
			}
			if ($('#searchterm input[placeholder]').attr('value') == $('#searchterm input[placeholder]').attr('placeholder')) {
				$('#searchterm input[placeholder]').attr('placeholder', placeholderValue).val(placeholderValue);
			} else {
				$('#searchterm input[placeholder]').attr('placeholder', placeholderValue);
			}
			
			toggleSearchContainer();
			return true;
		} else {
			return false;
		}
	}
	// funktion fuer click-event
	boundSearchFunction = function(event) {
		if (!isInElementJQ(Event.pointer(event), $('#searchcontainer')) && event.type == 'click') {
			toggleSearchContainer();
		}
	}
	// ein/ausblenden des suchbereich-layers
	toggleSearchContainer = function() {
		if ($('#searchcontainer').hasClass('active')) {
			document.stopObserving("click", boundSearchFunction);
			$('#pd-search').attr("aria-expanded", "false");
			$('#searchscope').fadeOut(200).attr("aria-hidden", "true");
		} else {
			document.observe("click", boundSearchFunction);
			$('#pd-search').attr("aria-expanded", "true");
			$('#searchscope').fadeIn(200).attr("aria-hidden", "false");
		}
		$('#searchcontainer').toggleClass('active');
	}
	
	// callback fuer die positonierung des login-layer
	initLoginLayer = function($toggle, $layer) {
		var paddingleft = $layer.css('paddingLeft').substring(0,$layer.css('paddingLeft').indexOf('px'));		
		var paddingright = $layer.css('paddingRight').substring(0,$layer.css('paddingRight').indexOf('px'));		
		$layer.css('width', ($('#metanavigation-box').width() - paddingleft - paddingright));		
	}
	
	// bilder-toggle (inactive / active)
	toggleImage = function(img) {
		var type = img.src.slice( -3 );
	 	if (img.src.indexOf('-active') == -1) {
			img.src = img.src.replace('.'+type, '-active.'+type);
		} else {
			img.src = img.src.replace('-active.'+type, '.'+type);
		}
	}

	// save_as text (browserspezifisch)
	toggleSaveAS = function(detectedUA) {
		if (detectedUA.browser == 'Explorer') {
			$('p.save-as').html('(Rechtsklick, "Ziel speichern unter...")');
		}
		if (detectedUA.browser == 'Firefox') {
			$('p.save-as').html('(Rechtsklick, "Ziel speichern unter...")');
		}
		if (detectedUA.browser == 'Safari') {
			$('p.save-as').html('(Rechtsklick, "Verknüpfte Datei laden unter ...")');
		}
		if (detectedUA.browser == 'Chrome') {
			$('p.save-as').html('(Rechtsklick, "Link speichern unter...")');
		}
		if (detectedUA.browser == 'Opera') {
			$('p.save-as').html('(Rechtsklick, "Verlinkten Inhalt speichern als...")');
		}
	}

	$(document).ready(function() {
		var detectedUA = $(document).browserDetection();
		toggleSaveAS(detectedUA);

		if (!(!(detectedUA.browser == 'Explorer' && detectedUA.browserversion < 10) && !(detectedUA.browser == 'Firefox' && detectedUA.browserversion < 4 && detectedUA.os == 'WindowsXP') && !(detectedUA.browser == 'Chrome' && detectedUA.os == 'WindowsXP') && !(detectedUA.browser == 'Safari' && detectedUA.browserversion < 5.1 ) && !(detectedUA.browser == 'Opera' && detectedUA.browserversion < 11) && !(detectedUA.browser == 'Opera' && detectedUA.os == 'WindowsXP'))) {
			$('html').removeClass('wf-active');
		}

		if (detectedUA.os == 'Windows7' && detectedUA.browser == 'Firefox' && detectedUA.browserversion >= 4) {
			$('html').addClass('wf-special');
		}

		// MetaWeb deaktivieren
		//$('html').removeClass('wf-active');

		if (!(detectedUA.browser == 'Explorer' && detectedUA.browserversion < 7)) {
			$('body').addClass('dynd');
			
			initElemsPossiblyInDynamicContent('body');
			
			if ($('#alertbox')) {
				$('#alertbox').animate({backgroundColor: '#ffff00'}, 2000).animate({backgroundColor: '#ffffcc'}, 500);
			}
	
			// ajax-layer
			$('.fn-ajax-layer').each(function(index, ajaxlayer) {
				new AjaxLayer(ajaxlayer);
			});

			// tablists
			jQuery(document).ready(function() {
				jQuery('.fn-tab').each(function(index, tab) {
					new TabList(tab);
				});
			});

			// Suche
			$('#searchsubmit').hover(
				function() {$(this).toggleClass('hover');}
			);

			$('#pd-search').click(function(event) {
				toggleSearchContainer();
				event.preventDefault();
			});

			// Bei 'ESC' schliessen
			$('#searchcontainer').keyup(function(event) {
				if (event.keyCode == '27' && $('#searchcontainer').hasClass('active')) {
					toggleSearchContainer();
				}
			});

			$('#searchscope li a').click(function(event) {
				$(this).parents('ul').find('.active').removeClass('active');
				setSearchLocation($(this));
				event.preventDefault();
			});				
			
			// Bilder mit Lightbox-Zoom (nur wenn die Lightbox Lib eingebunden ist)
			if (jQuery.fn.lightBox) {
				$('.zoomable a[rel=lightbox]').lightBox();
			}
						
			// Hauptnavigation
			var showmncontent = false;

			$('.mn-link').each(function(elm) {
				var elm = $(this);
				id = $(this).attr('id').substring(3);
				new MainnavigationLayer(elm, id, {});
			});


			// Subnavigation
			$('#subnavigation .sn').each(function(elm) {
				if (!$(this).hasClass('active')) {
					$(this).children('ul').attr('aria-hidden', 'true').hide().end().find('a.sn-btn').attr('aria-expanded', 'false');
				}

				$(this).children('.sn-btn').click(function(event) {
					if (!$(this).parent('li').hasClass('active')) {
						// geoeffnete punkte schliessen
						$('#subnavigation').find('.active').children('.lvl-2').attr('aria-hidden', 'true').slideUp(200).end().find('a.sn-btn').attr('aria-expanded', 'false').attr('tabindex', '0').end().parents('#subnavigation').find('.sn').removeClass('active');
						// aktuellen punkt oeffnen
						$(this).parent().addClass('active').find('.lvl-2').attr('aria-hidden', 'false').slideDown(200).end().children('a.sn-btn').attr('aria-expanded', 'true').attr('tabindex', '-1');
					}
					event.preventDefault();
				});
			});


			// Overlay für den Kalender generieren
			if ($('#kalenderblatt-teaser')) {
				$('#kalenderblatt-teaser a').click(function(event) {
					event.preventDefault();
					$.blockUI();
        			$('.blockOverlay').click($.unblockUI); 
					doCalendarAjax($(this).attr('href'));

					$('.blockOverlay,.blockPage').css({cursor: 'default'});
					$('.blockPage').css({ 
		                top:  ($(window).height() - 575) / 2 + 'px', 
		                left: ($(window).width() - 730) / 2 + 'px', 
		                width: '732px',
						height: 'auto',
						background: 'none',
						border: 'none'
		            });
				});
			}


			// Ausblenden der zusätzlichen Label-<span>: (wenn Institution)
			$('span.institutionHidden').hide();

			// Ein-/Ausblenden der Institutuion-Felder beim Klick des Radiobuttons "account_type"
			$('input[name="account_type"]').change(function() {
				switch($(this).val()) {
					case "private":$('#institutionHidden').slideUp();break;
					default:$('#institutionHidden').slideDown();break;
				}
			});

			// Ein-/Ausblenden der Assistenz-Felder beim Laden der Seite
			if(!($('input[name="assistance"]').attr('checked'))) {
				$('#assistanceHidden').hide();
			}

			// Ein-/Ausblenden der Assistenz-Felder beim Klick der checkbox "assistance"
			$('input[name="assistance"]').change(function() {
				if($(this).attr('checked')) {
					$('#assistanceHidden').slideDown();
				} else {
					$('#assistanceHidden').slideUp();					
				}
			});

			// Ein-/Ausblenden der Newsletter-Felder beim Laden der Seite
			if(!($('input[name="newsletter"]').attr('checked'))) {
				$('#newsletterversionHidden').hide();
			}

			// Ein-/Ausblenden der Newsletter-Felder beim Klick der checkbox "newsletter"
			$('input[name="newsletter"]').change(function() {
				if($(this).attr('checked')) {
					$('#newsletterversionHidden').slideDown();
				} else {
					$('#newsletterversionHidden').slideUp();
				}
			});

		} else {
			$('html').removeClass('wf-active');

			$.ifixpng($('body').data('rel2rootweb')+'img/basics/pixel.gif');
			$('img').not('img.social, img.stickylink').ifixpng();
			
			// nur das erste Bild jeder Slideshow anzeigen
			$('.slideshow li').attr('style', 'display:none;');
			$('.slideshow li').removeClass('clearfix');
			$('.slideshow li:first-child').attr('style', 'display:block;');
			$('.slideshow li:first-child').addClass('clearfix');
		}

		// Rating
		$('#pagerating').addClass('js');
		$('.ratinglinks').each(function(){
			var self = this;
			var targetPos = $('#pagerating').position();
			targetPos.left = Math.round(targetPos.left) + 2;
			var h4Width = Math.round($('h4').width());
			$('h4').css('width', h4Width+'px');
			$(this).addClass('hiddenstars js')
					.css({
						'position' : 'absolute',
						'margin-top' : '0',
						'left' : targetPos.left,
						'top' : 0
					})
					.find('li').addClass('js')
					.find('a').addClass('stars-0');
			$('a', this).bind('mouseover focus', function(ev){
				$(self).removeClass('hiddenstars');
				$('#pagerating').addClass('hiddenstars');
				var score = $(this).data('score');
				for (s=1; s<=score; s++) {
					$('a[data-score='+s+']', self).removeClass('stars-0');
				}
			}).bind('mouseout blur', function(ev){
				$(self).addClass('hiddenstars');
				$('#pagerating').removeClass('hiddenstars');
				$('a', self).addClass('stars-0');
			}).bind('click', function(ev){
				ev.preventDefault();
				var url = this.href;
				var score = $(this).data('score');
				var id = $(this).data('id');
				var film = $(this).data('film');
				$.ajax({
					type: "POST",
					url: url,
					data: "ajax=y",
					dataType: "json",
					cache: false,
					async: false,
					success: function(result) {
						ET_Event.click(film+'%3A%20'+score+'%20Sterne%20%28Filmfestival%29', '');
						$("#pagerating").removeClass().addClass('js stars stars-'+result.rate);
						$("#pagerates").html(result.rates);
						$(".ratinglinks").detach();
						/*if ($("#toprating-"+sid)) {
							$("#toprating-"+sid).removeClass().addClass('stars stars-'+result.rate);
						}*/
						//unTooltip();
					},
					error: function(result) {
					}
				});
			});
		});
	})


	function initElemsPossiblyInDynamicContent(context){
		var detectedUA = $(document).browserDetection();
		
		if (!(detectedUA.browser == 'Explorer' && detectedUA.browserversion < 7)) {

			// Links veretrackern
			// Es existiert ein Duplikat der Veretrackerung angepasst an Prototype (s.u.)
			if ($('body').data('et')) {
				$(context).find("a[href^='http']").filter(function() {
					var inWhitelist = false;
					for (i = 0; i < etrackerWhitelist.length; i++) {
						if (this.href.indexOf(etrackerWhitelist[i]) > -1) {
							inWhitelist = true;
						}
					}
					return (inWhitelist || (this.hostname.replace(/www./, '') != location.hostname.replace(/www./, '') && this.hostname != 'www.etracker.de'));
				}).each(function(){
					var externalUrl =  $(this).attr('href');
					//var indexOfParameter = externalUrl.indexOf('?');
					var linkName = externalUrl;
					/*
					if (indexOfParameter > 0) {
						linkName = externalUrl.substring(0, externalUrl.indexOf('?'));
					}
					*/
					$(this).click(function(event) {
						$(this).attr('href','http://www.etracker.de/lnkcnt.php?et=' + $('body').data('et') + '&url=' + escape(externalUrl) + '&lnkname=' + escape(linkName)).addClass('external');
					});
				});
			}

			// JS-Pulldowns
			initPulldowns(context);

			// Platzhalter-Fallback entfernen
			$(context).find('input[placeholder]').each(function() {
				if ($(this).attr('value') == $(this).attr('placeholder')) {
					$(this).attr('value', '');
				}
			});

			// Platzhalter mittels Plugin in allen Browsern anzeigen
			$(context).find('input[placeholder]').placeholder();

			// Button hover
			$(context).find('input.btn-gray').hover(
				function() {$(this).toggleClass('hover');}
			);

			// popups
			popify(context);
		}

	}

	MainnavigationLayer = function(elem, id, params) {
		this.init(elem, id, params);
	};
	MainnavigationLayer.prototype = {
		timeoutLeave: null,
		timeoutEnter: null,
		lastCorrected : null,

		init : function(elem, id, params){
			this.$elem = $(elem);
			this.id = id;
			this.content;
			this.params = params || {};
			this.$mnlayer = $("#mncontent-box");			
			this.$mncontent = $("#mncontent");			
			this.$mnpointer = $("#mnpointer");			
			this.$mnlayer.mouseover($.proxy(function(){
				window.clearTimeout(MainnavigationLayer.timeoutLeave);
				MainnavigationLayer.timeoutLeave = null;
			}, this));
			this.$mnlayer.mouseleave($.proxy(this, "mouseleave"));
			this.$elem.mouseenter($.proxy(this, "mouseenter"));
			this.$elem.mouseleave($.proxy(this, "mouseleave"));

			if(this.params.followLink == false) {
				this.$elem.click(function(ev){ev.preventDefault();});
			}
		},

		mouseenter: function(ev) {
			window.clearTimeout(MainnavigationLayer.timeoutLeave);
			MainnavigationLayer.timeoutLeave = null;
			var fail = true;
			
			if(!MainnavigationLayer.timeoutEnter) {
				MainnavigationLayer.timeoutEnter = window.setTimeout($.proxy( this, "show" ), 200);
			}
		},

		mouseleave: function() {
			window.clearTimeout(MainnavigationLayer.timeoutEnter);
			MainnavigationLayer.timeoutEnter = null;

			this.$mnlayer.clearQueue();
			if(!MainnavigationLayer.timeoutLeave) {
				MainnavigationLayer.timeoutLeave = window.setTimeout($.proxy( this, "hide" ), 200);
			}
		},

		hide: function() {
			if(! isIE()) {
				var that = this;
				this.$mnlayer.fadeOut(200, function(){that.$mncontent.html('');});
			} else {
				this.$mnlayer.hide();
				this.$mncontent.html('');
			}

			this.$elem.attr('aria-expanded', 'false');
			this.$mnlayer.attr('aria-hidden', 'true');
		},

		loadContent: function(){
			jQuery.ajax({
				url: $('body').data('rel2rootweb') + ajaxRoutinePostfix,
				type: 'POST',
				context: this,
				data: {ajax: 'y', ajax_routine: 'mnavlayer', section: this.id, ajax_refererPageID: $$('body')[0].readAttribute('data-refererPageID')},
				success: function(data, textStatus, jqXHR){					
					this.$mncontent.html(data);
					initElemsPossiblyInDynamicContent('body #' + this.$mnlayer.attr('id'));
					this.correctHeights(this.id);
				}
			});
		},

		correctHeights: function(id){
			/*
			if (MainnavigationLayer.lastCorrected == id){				
				return;
			}
			*/		   

			var $container = this.$mncontent.find('.full');
			if ($container.length>0){
				for(c=0; c<$container.length; c++){
					var $subcols = $($container[c]).children('.col2v3, .col1v3, .col1v2');					
					if ($subcols.length>0){
						var maxHeight = 0;
						for(s=0; s<$subcols.length; s++){							
							maxHeight = Math.max($($subcols[s]).height(), maxHeight);
						}

						if (maxHeight>0){
							MainnavigationLayer.lastCorrected = id;
							
							for(s=0; s<$subcols.length; s++){
								var $subcol = $($subcols[s]);
								if ($subcol.height()<maxHeight){
									var $subElms = $subcol.children('.rounded-box');
									if ($subElms.length>0){
										$subElm = $($subElms[$subElms.length-1]);
										$subElm.height($subElm.height() + (maxHeight - $subcol.height()));
									}
								}
							}
						}
					}

					var $subsubcols = $($container[c]).find('.sub-left, .sub-right');
					if ($subsubcols.length>0){
						var subMaxHeight = 0;
						for(s=0; s<$subsubcols.length; s++){
							subMaxHeight = Math.max($($subsubcols[s]).height(), subMaxHeight);
						}

						if (subMaxHeight>0){
							MainnavigationLayer.lastCorrected = id;

							for(s=0; s<$subsubcols.length; s++){
								var $subsubcol = $($subsubcols[s]);
								if ($subsubcol.height()<subMaxHeight){
									$subsubcol.height(subMaxHeight);
								}
							}
						}
					}
				}
			}
		},

		show: function(ev) {
			this.loadContent();
			
			var x, y, pointerX, pointerY;
			y = $('#navigation').offset().top + $('#navigation').height() + 15;
			x = $('#maincontent').offset().left - $('#header').offset().left - 5;

			pointerX = Math.round(this.$elem.offset().left + (this.$elem.innerWidth() / 2) - $('#maincontent').offset().left - 5);
			pointerY = - 12;

			this.$mnlayer.css({left: x +"px",
								top: y + "px",
								position: "absolute"});

			if(this.$mnlayer.css("display") != "none"){
				this.$mnpointer.stop().animate({left: pointerX +"px", top: pointerY +"px"}, 100);
			} else {				
				this.$mnpointer.css({left: pointerX +"px",
									top: pointerY + "px",
									position: "absolute"});
			}

			if(! isIE()) {
				this.$mnlayer.fadeIn(200);
			} else {
				this.$mnlayer.show();
			}

			this.correctHeights(this.id);

			this.$elem.attr('aria-expanded', 'true');
			this.$mnlayer.attr('aria-hidden', 'false');

			this.$mnlayer.show();
		}
	};

	AjaxLayer = function(elem) {
		this.init(elem);
	};
	AjaxLayer.prototype = {
		timeoutLeave: null,
		timeoutEnter: null,

		init : function(elem){
			this.$elem			= $(elem);
			this.$layer			= $("#" + this.$elem.attr("aria-controls"));
			this.params			= this.$elem.data("params");
			this.ajax_params	= this.$elem.data("ajax_params");
			this.ajax_ssl		= this.$elem.data("ajax_ssl")=="y";
			this.opened			= false;
			
			if (!this.params)		this.params = {};
			if (!this.ajax_params)	this.ajax_params = {};

			this.caching		= this.params['caching'] == 'y';
			this.cache			= '';
			
			this.initCallback		= this.params['initCallback'];
			this.preOpenCallback	= this.params['preOpenCallback'];
			this.postOpenCallback	= this.params['postOpenCallback'];

			this.classesStart	= {};
			if (this.params['toggleClasses']){				
				for (handle in this.params['toggleClasses']){
					this.classesStart[handle] = $(handle).hasClass();
				}
			}

						
			this.behaviour = this.params['behaviour'] == 'mouseover' ? 'mouseover' : 'click';

		    this.boundBodyClicked = this.bodyClicked.bindAsEventListener(this);

			if (this.behaviour == 'click') {
				this.$elem.click($.proxy(this, "click"));
				this.$elem.click(function(ev){ev.preventDefault();});
			} else {
				this.$layer.mouseover($.proxy(this, "clearTimeoutLeave"));
				this.$layer.mouseleave($.proxy(this, "mouseleave"));
				this.$elem.mouseenter($.proxy(this, "activate"));
				this.$elem.mouseleave($.proxy(this, "mouseleave"));
			}
			this.$elem.keyup($.proxy(this, "keyPress"));
			this.$layer.keyup($.proxy(this, "keyPress"));

			this.checkCallback("initCallback");
		},

		clearTimeoutEnter: function() {			
			window.clearTimeout(this.timeoutEnter);
			this.timeoutEnter = null;
		},
		clearTimeoutLeave: function() {			
			window.clearTimeout(this.timeoutLeave);
			this.timeoutLeave = null;
		},

		setCache: function(content){
			if (this.caching){
				this.cache = content;
			}
		},

		getCache: function(){
			return this.caching && this.cache.length>0 ? this.cache : '';
		},

		loadContent: function(){
			var url, data;
			if (this.ajax_params["ajax_routine"]){				
				url = $('body').data(this.ajax_ssl ? 'rel2rootweb_ssl' : 'rel2rootweb') + ajaxRoutinePostfix;
			} else {
				url = this.$elem.attr("href");
			}

			data = this.ajax_params;
			data['ajax'] = 'y';

			var content = this.getCache();
			if (typeof(content)=='string' && content.length>0){
				this.$layer.html(content);
			} else {
				jQuery.ajax({
					url: url,
					type: 'POST',
					context: this,
					data: data,
					success: function(data, textStatus, jqXHR){
						this.$layer.html(data);
						this.setCache(data);
						this.checkCallback("postOpenCallback");
					}
				});
			}
		},

		checkCallback: function (name){			
			if (this[name]){
				var func = eval(this[name]);
				if ($.isFunction(func)){
					func(this.$elem, this.$layer);
				}
			}
		},

		click: function(event) {
			if (this.opened) {
				this.clearTimeoutEnter();
				this.$layer.clearQueue();
				if(!this.timeoutLeave) {
					this.timeoutLeave = window.setTimeout($.proxy( this, "hide" ), 100);
				}
			} else {
				this.activate(event);
			}
		},

		activate: function(ev) {
			this.checkCallback("preOpenCallback");

			this.clearTimeoutLeave();
			
			if(!this.timeoutEnter) {				
				this.timeoutEnter = window.setTimeout($.proxy( this, "show" ), 200);
				this.loadContent();
			}

			ev.preventDefault();
			ev.stopImmediatePropagation();
			if (this.behaviour == 'click') {
				document.observe("click", this.boundBodyClicked);
			}
		},

		mouseleave: function() {
			this.clearTimeoutEnter();
			this.$layer.clearQueue();
			if(!this.timeoutLeave) {
				this.timeoutLeave = window.setTimeout($.proxy( this, "hide" ), 100);
			}
		},

		keyPress: function(event) {
			if (event.keyCode == 27) { // ESC
				this.clearTimeoutEnter();
				this.$layer.clearQueue();
				if(!this.timeoutLeave) {
					this.timeoutLeave = window.setTimeout($.proxy( this, "hide" ), 100);
				}
			}
		},

		hide: function() {
			this.opened = false;

			if(! isIE()) {
				this.$layer.fadeOut(200);
			} else {
				this.$layer.hide();
			}

			this.toggleClasses('hide');

			this.$elem.attr('aria-expanded', 'false');
			this.$layer.attr('aria-hidden', 'true');
		},

		show: function(ev) {
			this.opened = true;

			if(! isIE()) {
				this.$layer.fadeIn(200);
			} else {
				this.$layer.show();
			}

			this.toggleClasses('show');

			this.$elem.attr('aria-expanded', 'true');
			this.$layer.attr('aria-hidden', 'false');
		},

		toggleClasses: function(mode){			
			if (this.params['toggleClasses']){
				for (handle in this.classesStart){
					var elm = $(handle);
					var className = this.params['toggleClasses'][handle];
					if (mode=='hide'){
						if (this.classesStart[handle]){
							elm.addClass(className);
						} else {
							elm.removeClass(className);
						}
					} else {
						if (this.classesStart[handle]){
							elm.removeClass(className);
						} else {
							elm.addClass(className);
						}
					}					
				}
			}
		},

		bodyClicked: function(event) {
			if (!isInElementJQ(Event.pointer(event), this.$layer)) {
				this.clearTimeoutEnter();
				this.$layer.clearQueue();
				if(!this.timeoutLeave) {
					this.timeoutLeave = window.setTimeout($.proxy( this, "hide" ), 100);
				}
				document.stopObserving("click", this.boundBodyClicked);
			}
		}
	};


	TabList = function(elem) {
		this.init(elem);
	};
	TabList.prototype = {

		init : function(elem){
			this.$elem			= $(elem);
			this.$tabnav		= this.$elem.closest(".tabnav");
			this.$content		= this.$elem.closest(".elementcontainer").find(".elmcontent").first();

			if (this.$elem.closest('li').hasClass('active')){
				this.highlight();
			}

			this.params			= this.$elem.data("params");
			this.ajax_params	= this.$elem.data("ajax_params");
			this.ajax_ssl		= this.$elem.data("ajax_ssl")=="y";

			if (!this.params)		this.params = {};
			if (!this.ajax_params)	this.ajax_params = {};

			this.caching		= this.params['caching'] == 'y';
			this.$elem.data('ajaxTab_caching', this.caching);

			this.initCallback		= this.params['initCallback'];
			this.preChangeCallback	= this.params['preChangeCallback'];
			this.postChangeCallback	= this.params['postChangeCallback'];

			if (this.params['ajax']=='y'){
				this.$elem.click($.proxy(this, "activate"));
				this.$elem.click(function(ev){ev.preventDefault();});
			}
			
			this.checkCallback("initCallback");			
		},

		cacheCurrentContent: function(){
			var $currentActiveTab = this.$tabnav.find('li.active a').first();

			if ($currentActiveTab.data('ajaxTab_caching')){
				$currentActiveTab.data('ajaxTab_cachedContent', this.$content.html());
			}
		},

		getMyCache: function(){
			return this.caching ? this.$elem.data('ajaxTab_cachedContent') : '';
		},

		loadContent: function(){
			var url, data;
			if (this.ajax_params["ajax_routine"]){
				url = $('body').data(this.ajax_ssl ? 'rel2rootweb_ssl' : 'rel2rootweb') + ajaxRoutinePostfix;
			} else {
				url = this.$elem.attr("href");
			}

			data = this.ajax_params;
			data['ajax'] = 'y';

			var content = this.getMyCache();
			if (typeof(content)=='string' && content.length>0){
				this.cacheCurrentContent();
				this.show(content);
				this.highlight();
			} else {
				$.ajax({
					url: url,
					type: 'POST',
					context: this,
					data: data,
					success: function(data, textStatus, jqXHR){
						this.cacheCurrentContent();
						this.show(data);
						this.highlight();
						this.checkCallback("postChangeCallback");
					}
				});
			}
		},

		show: function(content){
			this.$content.empty();
			this.$content.html(content);
			if(! isIE()) {
				this.$content.fadeTo(200, 1);
			} else {
				this.$content.show();
			}
		},

		checkCallback: function (name){
			if (this[name]){
				var func = eval(this[name]);
				if ($.isFunction(func)){
					func(this.$elem, this.$content);
				}
			}
		},

		activate: function(ev) {
			this.checkCallback("preChangeCallback");

			if(! isIE()) {
				this.$content.fadeTo(200, 0, $.proxy(this, "loadContent"));
			} else {
				this.$content.hide();
				this.loadContent();
			}

			ev.preventDefault();
		},


		highlight: function() {
			this.$tabnav.find('li').removeClass('active');
			this.$elem.closest('li').addClass('active');

			this.$tabnav.find('a').attr('aria-selected', 'false').attr('tabindex', 0);
			this.$elem.attr('aria-selected', 'true').attr('tabindex', -1);

			this.$content.attr('aria-labelledby', this.$elem.closest('li').attr('id'));
			this.$content.attr('role', 'tabpanel');
		}
	};


	// Placeholder Plugin by snikch
	// https://github.com/snikch/jquery-placeholder-plugin
	$.extend({
		placeholder : {
			settings : {
				focusClass: 'placeholderFocus',
				activeClass: 'placeholder',
				overrideSupport: false,
				preventRefreshIssues: true
			},
			debug : false,
			log : function(msg){
				if(!$.placeholder.debug) return;
				msg = "[Placeholder] " + msg;
				$.placeholder.hasFirebug ?
				console.log(msg) :
				$.placeholder.hasConsoleLog ?
					window.console.log(msg) :
					alert(msg);
			},
			hasFirebug : "console" in window && "firebug" in window.console,
			hasConsoleLog: "console" in window && "log" in window.console
		}

	});

    // check browser support for placeholder
    $.support.placeholder = 'placeholder' in document.createElement('input');

	// Replace the val function to never return placeholders
	$.fn.plVal = $.fn.val;
	$.fn.val = function(value) {
		$.placeholder.log('in val');
		if(this[0]) {
			$.placeholder.log('have found an element');
			var el = $(this[0]);
			if(value != undefined)
			{
				$.placeholder.log('in setter');
				var currentValue = el.plVal();
				var returnValue = $(this).plVal(value);
				if(el.hasClass($.placeholder.settings.activeClass) && currentValue == el.attr('placeholder')){
					el.removeClass($.placeholder.settings.activeClass);
				}
				return returnValue;
			}

			if(el.hasClass($.placeholder.settings.activeClass) && el.plVal() == el.attr('placeholder')) {
				$.placeholder.log('returning empty because it\'s a placeholder');
				return '';
			} else {
				$.placeholder.log('returning original val');
				return el.plVal();
			}
		}
		$.placeholder.log('returning undefined');
		return undefined;
	};

	// Clear placeholder values upon page reload
	$(window).bind('beforeunload.placeholder', function() {
		var els = $('input.' + $.placeholder.settings.activeClass);
		if(els.length > 0)
			els.val('').attr('autocomplete','off');
	});


    // plugin code
	$.fn.placeholder = function(opts) {
		opts = $.extend({},$.placeholder.settings, opts);

		// we don't have to do anything if the browser supports placeholder
		if(!opts.overrideSupport && $.support.placeholder)
		    return this;

        return this.each(function() {
            var $el = $(this);

            // skip if we do not have the placeholder attribute
            if(!$el.is('[placeholder]'))
                return;

            // we cannot do password fields, but supported browsers can
            if($el.is(':password'))
                return;

			// Prevent values from being reapplied on refresh
			if(opts.preventRefreshIssues)
				$el.attr('autocomplete','off');

            $el.bind('focus.placeholder', function(){
                var $el = $(this);
                if(this.value == $el.attr('placeholder') && $el.hasClass(opts.activeClass))
                    $el.val('')
                       .removeClass(opts.activeClass)
                       .addClass(opts.focusClass);
            });
            $el.bind('blur.placeholder', function(){
                var $el = $(this);

				$el.removeClass(opts.focusClass);

                if(this.value == '')
                  $el.val($el.attr('placeholder'))
                     .addClass(opts.activeClass);
            });

            $el.triggerHandler('blur');

			// Prevent incorrect form values being posted
			$el.parents('form').submit(function(){
				$el.triggerHandler('focus.placeholder');
			});

        });
    };


	// BrowserDetect Plugin by stoimen
	// http://www.stoimen.com/blog/2009/07/16/jquery-browser-and-os-detection-plugin/
	// angepasst von krampitz
	$.fn.browserDetection = function() {
		var BrowserDetect = {
			init: function () {
				this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
				this.version = this.searchVersion(navigator.userAgent)
					|| this.searchVersion(navigator.appVersion)
					|| "an unknown version";
				this.OS = this.searchString(this.dataOS) || "an unknown OS";
			},
			searchString: function (data) {
				for (var i=0;i<data.length;i++)	{
					var dataString = data[i].string;
					var dataProp = data[i].prop;
					this.versionSearchString = data[i].versionSearch || data[i].identity;
					if (dataString) {
						if (dataString.indexOf(data[i].subString) != -1)
							return data[i].identity;
					}
					else if (dataProp)
						return data[i].identity;
				}
			},
			searchVersion: function (dataString) {
				var index = dataString.indexOf(this.versionSearchString);
				if (index == -1) return;
				return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
			},
			dataBrowser: [
				{
					string: navigator.userAgent,
					subString: "Chrome",
					identity: "Chrome"
				},
				{string: navigator.userAgent,
					subString: "OmniWeb",
					versionSearch: "OmniWeb/",
					identity: "OmniWeb"
				},
				{
					string: navigator.vendor,
					subString: "Apple",
					identity: "Safari",
					versionSearch: "Version"
				},
				{
					prop: window.opera,
					versionSearch: "Version",
					identity: "Opera"
				},
				{
					string: navigator.vendor,
					subString: "iCab",
					identity: "iCab"
				},
				{
					string: navigator.vendor,
					subString: "KDE",
					identity: "Konqueror"
				},
				{
					string: navigator.userAgent,
					subString: "Firefox",
					identity: "Firefox"
				},
				{
					string: navigator.vendor,
					subString: "Camino",
					identity: "Camino"
				},
				{		// for newer Netscapes (6+)
					string: navigator.userAgent,
					subString: "Netscape",
					identity: "Netscape"
				},
				{
					string: navigator.userAgent,
					subString: "MSIE",
					identity: "Explorer",
					versionSearch: "MSIE"
				},
				{
					string: navigator.userAgent,
					subString: "Gecko",
					identity: "Mozilla",
					versionSearch: "rv"
				},
				{ 		// for older Netscapes (4-)
					string: navigator.userAgent,
					subString: "Mozilla",
					identity: "Netscape",
					versionSearch: "Mozilla"
				}
			],
			dataOS : [
				{
					string: navigator.userAgent,
					subString: "Windows NT 6.1",
					identity: "Windows7"
				},
				{
					string: navigator.userAgent,
					subString: "Windows NT 5.1",
					identity: "WindowsXP"
				},
				{
					string: navigator.platform,
					subString: "Win",
					identity: "Windows"
				},
				{
					string: navigator.platform,
					subString: "Mac",
					identity: "Mac"
				},
				{
					string: navigator.userAgent,
					subString: "iPhone",
					identity: "iPhone/iPod"
				},
				{
					string: navigator.platform,
					subString: "Linux",
					identity: "Linux"
				}
			]

		};

		BrowserDetect.init();
		return {os : BrowserDetect.OS, browser : BrowserDetect.browser, browserversion : BrowserDetect.version};
	};



	/*
	* jQuery Color Animations
	* Copyright 2007 John Resig
	* Released under the MIT and GPL licenses.
	*/

    // We override the animation for all of these color styles
    jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
        jQuery.fx.step[attr] = function(fx){
            if ( !fx.colorInit ) {
                fx.start = getColor( fx.elem, attr );
                fx.end = getRGB( fx.end );
                fx.colorInit = true;
            }

            fx.elem.style[attr] = "rgb(" + [
                Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
                Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
                Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
            ].join(",") + ")";
        }
    });

    // Color Conversion functions from highlightFade
    // By Blair Mitchelmore
    // http://jquery.offput.ca/highlightFade/

    // Parse strings looking for color tuples [255,255,255]
    function getRGB(color) {
        var result;

        // Check if we're already dealing with an array of colors
        if ( color && color.constructor == Array && color.length == 3 )
            return color;

        // Look for rgb(num,num,num)
        if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
            return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

        // Look for rgb(num%,num%,num%)
        if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
            return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

        // Look for #a0b1c2
        if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
            return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

        // Look for #fff
        if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
            return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

        // Look for rgba(0, 0, 0, 0) == transparent in Safari 3
        if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
            return colors['transparent'];

        // Otherwise, we're most likely dealing with a named color
        return colors[jQuery.trim(color).toLowerCase()];
    }

    function getColor(elem, attr) {
        var color;

        do {
            color = jQuery.curCSS(elem, attr);

            // Keep going until we find an element that has color, or we hit the body
            if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
                break;

            attr = "backgroundColor";
        } while ( elem = elem.parentNode );

        return getRGB(color);
    };

    // Some named colors to work with
    // From Interface by Stefan Petre
    // http://interface.eyecon.ro/

    var colors = {
        aqua:[0,255,255],
        azure:[240,255,255],
        beige:[245,245,220],
        black:[0,0,0],
        blue:[0,0,255],
        brown:[165,42,42],
        cyan:[0,255,255],
        darkblue:[0,0,139],
        darkcyan:[0,139,139],
        darkgrey:[169,169,169],
        darkgreen:[0,100,0],
        darkkhaki:[189,183,107],
        darkmagenta:[139,0,139],
        darkolivegreen:[85,107,47],
        darkorange:[255,140,0],
        darkorchid:[153,50,204],
        darkred:[139,0,0],
        darksalmon:[233,150,122],
        darkviolet:[148,0,211],
        fuchsia:[255,0,255],
        gold:[255,215,0],
        green:[0,128,0],
        indigo:[75,0,130],
        khaki:[240,230,140],
        lightblue:[173,216,230],
        lightcyan:[224,255,255],
        lightgreen:[144,238,144],
        lightgrey:[211,211,211],
        lightpink:[255,182,193],
        lightyellow:[255,255,224],
        lime:[0,255,0],
        magenta:[255,0,255],
        maroon:[128,0,0],
        navy:[0,0,128],
        olive:[128,128,0],
        orange:[255,165,0],
        pink:[255,192,203],
        purple:[128,0,128],
        violet:[128,0,128],
        red:[255,0,0],
        silver:[192,192,192],
        white:[255,255,255],
        yellow:[255,255,0],
        transparent: [255,255,255]
    };

	function popify(context){
		$(context).find('a[rel=popup]').each(function(index, elm) {
			elm = $(elm);
			var popupURL = elm.attr('href');
			popupURL = popupURL + (popupURL.indexOf('?') == -1 ? '?' : '&') + 'popup=y';
			elm.attr('href', popupURL);
			elm.click(function(event){
				popup(this.href);
				event.preventDefault();
			});
		});
	}

	function popup(url, name, width, height) {
		if (typeof name=="undefined"){
			name = "popup";
		}
		if (typeof width=="undefined"){
			width = 770;
		}
		if (typeof height=="undefined"){
			height = 600;
		}
		popstring = "scrollbars,resizable,width=" + width + ",height=" + height;
		var popup = window.open(url, name, popstring);
		popup.focus();

		return false;
	}
	
	
	/*
	 * jQuery ifixpng plugin
	 * (previously known as pngfix)
	 * Version 2.1  (23/04/2008)
	 * @requires jQuery v1.1.3 or above
	 *
	 * Examples at: http://jquery.khurshid.com
	 * Copyright (c) 2007 Kush M.
	 * Dual licensed under the MIT and GPL licenses:
	 * http://www.opensource.org/licenses/mit-license.php
	 * http://www.gnu.org/licenses/gpl.html
	 */

	 /**
	  *
	  * @example
	  *
	  * optional if location of pixel.gif if different to default which is images/pixel.gif
	  * $.ifixpng('media/pixel.gif');
	  *
	  * $('img[@src$=.png], #panel').ifixpng();
	  *
	  * @apply hack to all png images and #panel which icluded png img in its css
	  *
	  * @name ifixpng
	  * @type jQuery
	  * @cat Plugins/Image
	  * @return jQuery
	  * @author jQuery Community
	  */

	/**
	 * helper variables and function
	 */
	$.ifixpng = function(customPixel) {
		$.ifixpng.pixel = customPixel;
	};

	$.ifixpng.getPixel = function() {
		return $.ifixpng.pixel || 'images/pixel.gif';
	};

	var hack = {
		ltie7  : $.browser.msie && $.browser.version < 7,
		filter : function(src) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='"+src+"')";
		}
	};

	/**
	 * Applies ie png hack to selected dom elements
	 *
	 * $('img[@src$=.png]').ifixpng();
	 * @desc apply hack to all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').ifixpng();
	 * @desc apply hack to element #panel and all images with png extensions
	 *
	 * @name ifixpng
	 */

	$.fn.ifixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			// in case rewriting urls
			var base = $('base').attr('href');
			if (base) {
				// remove anything after the last '/'
				base = base.replace(/\/[^\/]+$/,'/');
			}
			if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
				if ($$.attr('src')) {
					if ($$.attr('src').match(/.*\.png([?].*)?$/i)) { // make sure it is png image
						// use source tag value if set
						var source = (base && $$.attr('src').search(/^(\/|http:)/i)) ? base + $$.attr('src') : $$.attr('src');
						// apply filter
						$$.css({filter:hack.filter(source), width:$$.width(), height:$$.height()})
						  .attr({src:$.ifixpng.getPixel()})
						  .positionFix();
					}
				}
			} else { // hack png css properties present inside css
				var image = $$.css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)) {
					image = RegExp.$1;
					image = (base && image.substring(0,1)!='/') ? base + image : image;
					$$.css({backgroundImage:'none', filter:hack.filter(image)})
					  .children().children().positionFix();
				}
			}
		});
	} : function() {return this;};

	/**
	 * Removes any png hack that may have been applied previously
	 *
	 * $('img[@src$=.png]').iunfixpng();
	 * @desc revert hack on all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').iunfixpng();
	 * @desc revert hack on element #panel and all images with png extensions
	 *
	 * @name iunfixpng
	 */

	$.fn.iunfixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var src = $$.css('filter');
			if (src.match(/src=["']?(.*\.png([?].*)?)["']?/i)) { // get img source from filter
				src = RegExp.$1;
				if ($$.is('img') || $$.is('input')) {
					$$.attr({src:src}).css({filter:''});
				} else {
					$$.css({filter:'', background:'url('+src+')'});
				}
			}
		});
	} : function() {return this;};

	/**
	 * positions selected item relatively
	 */

	$.fn.positionFix = function() {
		return this.each(function() {
			var $$ = $(this);
			var position = $$.css('position');
			if (position != 'absolute' && position != 'relative') {
				$$.css({position:'relative'});
			}
		});
	};

})(jq);


//--------------------------------------------------------------
// LEGACY CODE (PROTOTYPE)
//--------------------------------------------------------------
$(document).observe("dom:loaded", function() {
	
	// paging bei news initialisieren
	if ($$('#feedcontent .pager').length) {
		new Feedpager($('feedcontent'), {showCount: 2});
	}
	
	// paging in social media box initialisieren
	if ($$('#socialmedia .pager').length) {
		new Pager($('socialmedia'), {showCount: 1});
	}
		
	// paging bei medienserien initialisieren
	$$('.seriespager').each(function(elm){
		new Pager(elm, {showCount: 3});
	});
		
	// accordions des jahresberichts initialisieren
	$$('.accordion').each(function(elm){
		accordion = new Accordion(elm);
	});
	
	// Initialisiere den Chronik-Slider
	if ($('timelineslider')) {
		chronik = new ChronikSlider({});
	}

	if (!isIE(6)) {
		// Startseite: Initiativen
		initiativen = [
				{id: 'init-default', key: "default", activeImg: "", inactiveImg: ""},
				{id: 'init-soviel', key: "soviel", activeImg: "img/content/logo-soviel.png", inactiveImg: "img/content/logo-soviel-inactive.png"},
				{id: 'init-biene', key: "biene", activeImg: "img/content/logo-biene.png", inactiveImg: "img/content/logo-biene-inactive.png"},
				{id: 'init-efa', key: "efa", activeImg: "img/content/logo-efa.png", inactiveImg: "img/content/logo-efa-inactive.png"},
				{id: 'init-xundco', key: "xundco", activeImg: "img/content/logo-xundco.png", inactiveImg: "img/content/logo-xundco-inactive.png"},
				{id: 'init-respect', key: "respect", activeImg: "img/content/logo-respect.png", inactiveImg: "img/content/logo-respect-inactive.png"},
				{id: 'init-ratgeber', key: "familienratgeber", activeImg: "img/content/logo-familienratgeber.png", inactiveImg: "img/content/logo-familienratgeber-inactive.png"}
		];
		// Initialisiere die Initiativen-Links
		if ($('initiativen')) {
			initiativen.each(function(elm) {
				new InitLink(elm);
			});
		}

		// Initialisiere die Auf-Zu-Schieber (Startseite)
		$$('.openhandler').each(function(elm){
			new Expandable(elm);
		});

		// Initialisiere die Slideshows
		$$('.slideshow').each(function(elm){
			new Pager(elm, {showCount: 1});
		});
	}
	
	// dieses piece kuemmert sich um das Ausfahren der Passwort-Zeilen beim Bilderdownload
	if ($$('.passwordcontainer').length && $$('.passwordtrigger').length == $$('.passwordcontainer').length) {
		// geh durch die passwortcontainer auf der seite
		$$('.passwordcontainer').each(function(pwc){
			// bau dir die ID des passworttriggers aus der ID des pwasswortcontainers zusammen und cache das element
			var pwc = pwc;
			var pwt = $(pwc.identify().split('passwordcontainer')[0] + "passwordtrigger");
			
			if (pwc && pwt) {
				if (pwc.hasClassName("pwerror")) {
					pwt.hide();	
				} else {
					pwc.hide();
					
					pwt.observe("click", function(event){
						event.stop();
						pwc.appear();
						pwt.fade();
					});
				}
			}
		});
	}
	
	// Initialisiere die Resizable Images des Jahresberichts
	$$('.resizableimg').each(function(elm){
		if (elm.down('a') && elm.down('a').down('img')) {
			var link = elm.down('a');
			var img = link.down('img');
			var smallsrc = img.src;
			var bigsrc = link.href;
			var captionWidth = false;
			
			if (elm.down('.imagecaption')) {
				captionWidth = elm.down('.imagecaption').getStyle('width');
			}
			
			link.observe("click", function(event){
				event.stop();
				
				if (img.src == smallsrc) {
					img.src = bigsrc;
					link.href = smallsrc;

					if (link.down('.plus') && link.down('.minus')) {
						link.down('.plus').setStyle('display:none;');
						link.down('.minus').setStyle('display:block;');
					}
					
					if (captionWidth) {
						elm.down('.imagecaption').setStyle('width:auto;');
						if (elm.down('.imagecaption').down('.caption-mini') && elm.down('.imagecaption').down('.caption-maxi')) {
							elm.down('.imagecaption').down('.caption-mini').setStyle('display:none;');
							elm.down('.imagecaption').down('.caption-maxi').setStyle('display:block;');
						}
					}
					
					link.title = link.title.replace(/Vergrößern/, "Verkleinern");
				} else {
					img.src = smallsrc;
					link.href = bigsrc;
					
					if (link.down('.plus') && link.down('.minus')) {
						link.down('.plus').setStyle('display:block;');
						link.down('.minus').setStyle('display:none;');
					}

					if (captionWidth) {
						elm.down('.imagecaption').setStyle('width:'+captionWidth+';');
						if (elm.down('.imagecaption').down('.caption-mini') && elm.down('.imagecaption').down('.caption-maxi')) {
							elm.down('.imagecaption').down('.caption-mini').setStyle('display:block;');
							elm.down('.imagecaption').down('.caption-maxi').setStyle('display:none;');
						}
					}
					
					link.title = link.title.replace(/Verkleinern/, "Vergrößern");
					
					// Ein Rendering-Bug im Firefox 3.6 erfordert diesen Trick mit sich aendernder Positionierung
					elm.setStyle('position:relative;');
					function bl(elm) {
						elm.setStyle('position:static;');
					}
					bl.delay(0.6, elm);						
				}
				
			});
		}
	});
	
	// Initialisiere Kalendar-Funktionalitaeten.
	// Als Funktion gekapselt, damit sie sich bei Bedarf selber aufrufen kann.
	(function initializeCalendar() {
		if ($('calendar')) {

			if (!$('event-tooltip')) {
				var tooltip = new Element("div", {
					id: "event-tooltip",
					style: "display: none",
					role: "tooltip"
				});
				$(document.body).insert(tooltip);
			}

			var cal = $('calendar');
			var tt = $('event-tooltip');

			// Termin-Links durchgehen und mit Funktionalitaet belegen		
			cal.select('td a').each(function(link) {
				link.writeAttribute("title","");
				
				link.observe("mouseover", function(event) {
					event.stop();
					
					// wenn der content schon gecached wurde, nimm aus cache
					if (link.retrieve('content')) {
						tt.update(link.retrieve('content'));
						repositionTooltip();
					} else {
						new Ajax.Updater(tt, this.href.replace(/index.php|detail.php/, "index.php"), {
							parameters: {ajax: 'y', ajax_routine: 'eventlayer'},
							onSuccess: function(response) {
								// content cachen
								link.store("content", response.responseText);
								repositionTooltip();
							}
						});
					}

					Effect.Queues.get('endfade').invoke("cancel");
					
					tt.appear({
						duration:0.2,
						delay:0.3,
						queue: {
							scope: "startfade",
							limit:1
						}
					});
					
					// setzt den tooltip unterhalb des gehoverten termins
					function repositionTooltip() {
						tt.setStyle({
							left: (link.cumulativeOffset()[0] - 8 ) + "px",
							top: (link.cumulativeOffset()[1] + 26 ) + "px"
						});
						
						// sicher stellen, dass der tooltip nicht aus der seite ragt
						var dims = tt.getDimensions();
						var vport = document.viewport.getDimensions();
						while (parseInt(tt.getStyle("left"))+dims.width+2 > vport.width) {
							tt.setStyle({
								"left": (parseInt(tt.getStyle("left"))-2)+"px"
							});
						}
					}
					
				}.bindAsEventListener(link));
				
				// getriggert beim verlassen des Termin-Links
				link.observe("mouseout", function(event) {
					Effect.Queues.get('startfade').invoke("cancel");
					Effect.Queues.get('endfade').invoke("cancel");
					tt.fade({
						duration:0.2,
						delay: 0.2,
						queue: {
							scope: "endfade",
							limit:1
						}
					});
					
				}.bindAsEventListener(link));
			});
			
			// getriggert beim ueberfahren des tooltips
			tt.observe("mouseover", function(event) {
				Effect.Queues.get('endfade').invoke("cancel");
				tt.appear({
					duration:0.0,
					transition: Effect.Transitions.full,
					queue: {
						scope: "startfade",
						limit:1
					}
				});
			});
			
			// getriggert beim verlassen des tooltips
			tt.observe("mouseout", function(event) {
				Effect.Queues.get('endfade').invoke("cancel");
				tt.fade({
					duration:0.2,
					delay: 0.2,
					queue: {
						scope: "endfade",
						limit:1
					}
				});
			});
			
			
			// Monats-Paging per AJAX nachladen
			cal.select('.pager a').each(function(link) {
				link.observe("click", function(event) {
					event.stop();
					new Ajax.Updater(cal, this.href, {
						parameters: {ajax: 'y', ajax_routine: 'calendar'},
						insertion: 'after',
						onComplete: function() {
							cal.select("a").invoke("stopObserving");
							cal.remove();
							initializeCalendar();
						}
					});
				}.bindAsEventListener(link));
			});
		}
	})();
	
	// ersetzen der Channel-Links im Presseverteiler durch Radio-Buttons
	var links = [$('info-email'), $('info-fax'), $('info-post')];
	links.each(function(link) {
		if (link) {
			var value = link.id.replace('info-', '');
			var selected = "";
			
			if ($F('hidden-channel') == value) {
				selected = "checked='checked'";
			}
			
			link.insert({
				before: '<input type="radio" name="channel" value="'+value.escapeSpecialChars()+'" id="'+link.id+'-input" '+selected+' /> <label class="channel" for="'+link.id+'-input">' + link.innerHTML + '</label>'
			});
			link.remove();
			
			var input = $(link.id+'-input');
			input.observe("change", function(event) {
				
				if ($('errorblock')) {
					$('errorblock').remove();
				}
				$$('label.error').each(function(label) {
					label.innerHTML = label.innerHTML.replace(/<strong.*?<\/strong>&nbsp;/, "");
					label.removeClassName("error");
				});
				$$('input[aria-invalid="true"]').invoke("writeAttribute", "aria-invalid", "false");
									
				if (input.value == "email") {
					$('strasse').writeAttribute("aria-required", "false");
					$$('label[for="strasse"]')[0].innerHTML = $$('label[for="strasse"]')[0].innerHTML.replace(" *", "");
					
					$('plz').writeAttribute("aria-required", "false");
					$$('label[for="plz"]')[0].innerHTML = $$('label[for="plz"]')[0].innerHTML.replace(" *", "");
					
					$('ort').writeAttribute("aria-required", "false");
					$$('label[for="ort"]')[0].innerHTML = $$('label[for="ort"]')[0].innerHTML.replace(" *", "");
					
					$('fax').writeAttribute("aria-required", "false");
					$$('label[for="fax"]')[0].innerHTML = $$('label[for="fax"]')[0].innerHTML.replace(" *", "");
				} else
				if (input.value == "fax") {
					$('strasse').writeAttribute('aria-required', "false");
					$$('label[for="strasse"]')[0].innerHTML = $$('label[for="strasse"]')[0].innerHTML.replace(" *", "");
					
					$('plz').writeAttribute("aria-required", "false");
					$$('label[for="plz"]')[0].innerHTML = $$('label[for="plz"]')[0].innerHTML.replace(" *", "");
					
					$('ort').writeAttribute("aria-required", "false");
					$$('label[for="ort"]')[0].innerHTML = $$('label[for="ort"]')[0].innerHTML.replace(" *", "");
					
					$('fax').writeAttribute("aria-required", "true");
					$$('label[for="fax"]')[0].innerHTML += " *";
				} else
				if (input.value == "post") {
					$('strasse').writeAttribute('aria-required', "true");
					$$('label[for="strasse"]')[0].innerHTML += " *";
					
					$('plz').writeAttribute("aria-required", "true");
					$$('label[for="plz"]')[0].innerHTML += " *";
					
					$('ort').writeAttribute("aria-required", "true");
					$$('label[for="ort"]')[0].innerHTML += " *";
					
					$('fax').writeAttribute("aria-required", "false");
					$$('label[for="fax"]')[0].innerHTML = $$('label[for="fax"]')[0].innerHTML.replace(" *", "");
				}
			});
		}
	})
	if ($('hidden-channel')) {
		$('hidden-channel').remove();
	}
	
	// tooltips für die medien-uebersichtsliste initialisieren
	$$('.medien .tooltip a').each(function(elm) {
		id = parseInt(elm.href.split("id=")[1]);

		if($(elm).classNames() == 'pictureseries')
			new Tooltip(elm, id, {upsideDown: 1, showPagerItems: 6});
		else if($(elm).classNames() == 'audioseries' || $(elm).classNames() == 'videoseries' || $(elm).classNames() == 'quotationseries')
			new Tooltip(elm, id, {upsideDown: 1, showPagerItems: 10});
		else
			new Tooltip(elm, id, {upsideDown: 1});
	});
	
	// tooltips für die medien in der "verwandte inhalte" box initialisieren
	$$('.sidebox .medien a').each(function(elm) {
		id = parseInt(elm.href.split("id=")[1]);

		if($(elm).classNames() == 'pictureseries')
			new Tooltip(elm, id, {upsideDown: 0, showPagerItems: 6});
		else if($(elm).classNames() == 'audioseries' || $(elm).classNames() == 'videoseries' || $(elm).classNames() == 'quotationseries')
			new Tooltip(elm, id, {upsideDown: 0, showPagerItems: 10});
		else
			new Tooltip(elm, id, {upsideDown: 0});
	});
	
});

function initPulldowns (context) {
	$$(context + ' .pulldown').each(function(pulldown, index) {
		if (pulldown.hasClassName("datefilter")) {
			jsPulldowns.push(new Datefilterpulldown(pulldown, index));
		} else if (pulldown.hasClassName("contact")) {
			jsPulldowns.push(new Contactfilterpulldown(pulldown, index));
		} else if (pulldown.hasClassName("hpportal")) {
			jsPulldowns.push(new Pulldown(pulldown, index));
		} else {
			jsPulldowns.push(new Selectpulldown(pulldown, index));
		}
	});
}

var Pulldown = Class.create({
	initialize: function(elm, elmIndex) {
		this.element = elm;
		this.elmIndex = elmIndex;
		this.trigger = this.element.down(".pdhandler");
		this.content = this.element.down('.pdflesh');
		this.closeBtn = this.element.down(".pdclose") || null;
		this.opened = false;

		this.setLinkTabIndex(-1);

		var bordertop = 0;
		var borderbottom = 0;
		// Mindestbreite auf die Breite des Trigger setzen
		//if (this.content.getWidth() < this.trigger.getWidth()) {
			this.content.setStyle({
				width: (this.trigger.getWidth() - parseInt(this.trigger.getStyle("borderLeftWidth")) - parseInt(this.trigger.getStyle("borderRightWidth")) ) + "px"
			});
		//}

		this.element.writeAttribute('style', 'z-index:'+(1000-this.elmIndex)+';');
		this.trigger.writeAttribute('aria-controls', this.content.identify());
		this.trigger.writeAttribute('aria-expanded', 'false');

		this.boundBodyClicked = this.bodyClicked.bindAsEventListener(this);
		this.boundKeyPress = this.keyPress.bindAsEventListener(this);

		this.trigger.observe("click", this.click.bindAsEventListener(this));
		this.trigger.observe("keydown", this.keyPress.bindAsEventListener(this));

		// wenn ein CloseButton angegeben wurde (optional), dann mit Schließmechanik versehen.
		if (this.closeBtn) {
			this.closeBtn.observe("click", this.hide.bindAsEventListener(this));
		}

		// wenn schon mit Klasse "active" versehen, dann soll das Pulldown initial geöffnet sein
		if (this.element.hasClassName("active")) {
			this.show();
		}

		return this;
	},
	setLinkTabIndex: function(tabindex){
		var links = this.content.select('a');
		links.each(function(link){
			if (link.hasClassName('btn-gray')) {
				link.writeAttribute('tabindex', 0);
			} else {
				link.writeAttribute('tabindex', tabindex);
			}
		});
	},
	click: function(event) {
		event.stop();
		if (this.opened) {
			this.hide();
		} else {
			this.show();
		}
	},
	show: function() {
		if (!this.opened) {
			jsPulldowns.each(function(e){
				e.hide();
			});
			
			this.content.setStyle({position:"relative",left:"0px"});
			this.content.writeAttribute('aria-hidden', 'false');
			this.trigger.writeAttribute('aria-expanded', 'true');
			this.setLinkTabIndex(-1);
			this.opened = true;
			this.element.addClassName("active");

			// this checks if tooltip would be outside of the document and moves it to the left until it fits in
			var dims = this.content.getDimensions();
			var vport = document.viewport.getDimensions();

			while (parseInt(this.content.viewportOffset().left)+dims.width+2 > vport.width) {
				this.content.setStyle({
					left: (parseInt(this.content.getStyle("left"))-2)+"px"
				});
			}

			var that = this;
			var temp = function() {
				document.observe("click", that.boundBodyClicked);//von mousedown zu click geandert
				document.observe("keydown", that.boundKeyPress);
			}.delay(0.2);
		}
	},
	hide: function() {
		if (this.opened) {
			var focused = this.content.select('a.focused');
			if (focused.length) {
				$(focused[0]).removeClassName('focused');
			}
			this.content.setStyle({position:"absolute",left:"-10000px"});
			this.content.writeAttribute('aria-hidden', 'true');
			this.trigger.writeAttribute('aria-expanded', 'false');
			this.setLinkTabIndex(-1);
			this.opened = false;
			this.element.removeClassName("active");

			document.stopObserving("click", this.boundBodyClicked);
			document.stopObserving("keydown", this.boundKeyPress);
		}
	},
	bodyClicked: function(event) {
		var sOffset = document.viewport.getScrollOffsets();
		var pos = {
			x: event.pointer().x + sOffset[0],
			y: event.pointer().y + sOffset[1]
		};
		if (!isInElement(pos, this.content)) {
			this.hide();
			document.stopObserving("click", this.boundBodyClicked);//von mousedown zu click geandert
		}
	},
	keyPress: function(event) {
		if (this.opened) {
			switch(event.keyCode) {

				case 27: // ESC
					this.hide();
					document.stopObserving("click", this.boundBodyClicked);

					break;

				case 40: // Down
					event.stop();
					var focused = this.content.select('a.focused');
					if (focused.length) {
						var next = $(focused[0]).up().next();
						if (next != undefined) {
							$(focused[0]).removeClassName('focused');
							next.down('a').addClassName('focused').focus();
						}
					} else {
						this.content.select('a').first().addClassName('focused').focus();
					}

					break;

				case 38: // Up
					event.stop();
					var focused = this.content.select('a.focused');
					if (focused.length) {
						var previous = $(focused[0]).up().previous();
						if (previous != undefined) {
							$(focused[0]).removeClassName('focused');
							previous.down('a').addClassName('focused').focus();
						}
					}

					break;
			}
		} else {
			if (event.keyCode == 40) { // Down
				event.stop();
				this.show();
			}
		}
	}
});


var Selectpulldown =  Class.create(Pulldown, {
	initialize: function($super, ancestor, index) {
		this.ancestor = ancestor;
		this.textLength = 15;

		this.createFakePulldown();

		$super($(this.ancestor.identify()+'-mirror'), index);


		this.content.select("a.option").each(function(link){
			link.observe("click", this.itemChanged.bindAsEventListener(this, link))
		}.bind(this));
	},
	createFakePulldown: function() {
		var activeText = this.ancestor.select("option").find(function(option) {
			return option.selected
		}).innerHTML;

		var flesh = '<ul class="pdflesh noprint" aria-hidden="true">';
		var countOptions = this.ancestor.select('option').length;
		this.ancestor.select('option').each(function(option, index) {
			flesh += '<li';
			if (countOptions == (index+1)) {
				flesh += ' class="last"';
			}
			flesh += '><a href="#" class="option">' + option.innerHTML + '</a></li>';
		});
		flesh += '</ul>';

		var errorClass = '';
		if (this.ancestor.hasClassName('error')) {
			errorClass = ' error';
		}

		this.ancestor.insert({
			before: '<div class="jspulldown'+errorClass+'" id="'+this.ancestor.identify()+'-mirror"><a href="#" class="pdhandler" title="'+activeText+'"><span>'+activeText.truncate(this.textLength, "...")+'</span></a>'+flesh+'</div>'
		});

		this.ancestor.hide();
	},
	itemChanged: function(event, link) {
		event.stop();
		if (!this.ancestor.options[link.up("li").previousSiblings().length].selected) {
			this.ancestor.options[link.up("li").previousSiblings().length].selected = true;
			this.trigger.down("span").update(link.innerHTML.truncate(this.textLength, "..."));
		}
		this.hide();
	},
	show: function($super) {
		$super();

		if (this.opened) {
			this.content.setStyle("position:absolute; left:inherit;")
		}
	}
});

Object.extend(String.prototype, (function() {
	function escapeSpecialChars() {
		return this.replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
	}
	
	return {
		escapeSpecialChars: escapeSpecialChars
	}
})());

var Datefilterpulldown =  Class.create(Selectpulldown, {
	initialize: function($super, ancestor, index) {
		this.defaultDate = "TT.MM.JJJJ";
		
		$super(ancestor, index);

		this.content.addClassName('combobox');
		this.content.down(".btn-gray").observe("click", this.applyDate.bindAsEventListener(this));
	},
	createFakePulldown: function($super) {
		$super();
		
		this.ancestor.insert(this.fakeElm = new Element("option", {value:"", selected:"selected"}));
		
		var fromdate = this.defaultDate;
		var todate =this.defaultDate;
		
		if ($('fromdate')) {
			fromdate = $F('fromdate') || this.defaultDate;
			$('fromdate').remove();
		}
		if ($('todate')) {
			todate = $F('todate') || this.defaultDate;
			$('todate').remove();
		}
		
		if (fromdate != this.defaultDate && todate != this.defaultDate) {
			$(this.ancestor.identify() + '-mirror').down(".pdhandler").update("<span>Zeitrahmen</span>").title = "Zeitrahmen";
			this.ancestor.down("option[value='default']").value = "";
			this.fakeElm.selected = true;
		}
				
		var datefilter = '<label for="'+this.ancestor.identify()+'-l1'+'">von</label><input type="text" name="fromdate" value="'+fromdate.escapeSpecialChars() +'" maxlength="10" id="'+this.ancestor.identify()+'-l1'+'" />';
		datefilter += '<label for="'+this.ancestor.identify()+'-l2'+'">bis</label><input type="text" name="todate" value="'+todate.escapeSpecialChars()+'" maxlength="10" id="'+this.ancestor.identify()+'-l2'+'" />';
		datefilter += '<a class="btn-gray" href="#">Anwenden</a>';
		
		$(this.ancestor.identify()+'-mirror').down("ul").insert({
			bottom: "<li class='datefilter'>" + datefilter + "</li>"
		});
		
		$$('#' + this.ancestor.identify()+'-l1, #' + this.ancestor.identify()+'-l2').each(function(input) {
			input.observe("focus", function(event) {
				if (input.value == this.defaultDate) {
					input.value= "";
				}
			}.bindAsEventListener(this));
			
			input.observe("blur", function(event) {
				if (input.value == "") {
					input.value= this.defaultDate;
				}
			}.bindAsEventListener(this));
		}.bind(this));
	},
	applyDate: function(event) {
		event.stop();
		
		if ($F(this.ancestor.identify()+'-l2').match(/\d{2}\.\d{2}\.\d{4}$/) && $F(this.ancestor.identify()+'-l1').match(/\d{2}\.\d{2}\.\d{4}$/)) {
			this.trigger.update("<span>Zeitrahmen</span>");
			this.content.select('p.error').invoke("remove");
			
			this.fakeElm.selected = true;
			
			if (this.ancestor.up("form")) {
				this.ancestor.up("form").submit();
			}

			this.hide();
		} else {
			if (this.content.down('li.datefilter p.error')) {
				this.content.down('li.datefilter p.error').highlight({duration:2, endcolor:"#c9e4fa"});
			} else {
				this.content.down('li.datefilter').insert({
					top: "<p class='error'>Bitte Zeitangaben &uuml;berpr&uuml;fen</p>"
				});
			}
		}
	},
	itemChanged: function($super, event, link) {
		this.content.select('p.error').invoke("remove");
		$(this.ancestor.identify()+'-l2').value = this.defaultDate;
		$(this.ancestor.identify()+'-l1').value = this.defaultDate;
		
		$super(event, link);
	}
});

var Contactfilterpulldown =  Class.create(Selectpulldown, {
	initialize: function($super, ancestor, index) {
		$('jsenabled').value = '1';
		this.checkLotterySelected(ancestor.value);
		$super(ancestor, index);
	},
	createFakePulldown: function($super) {
		$super();
	},
	itemChanged: function($super, event, link) {
		this.checkLotterySelected(link.innerHTML);
		$super(event, link);
		document.location.href = "index.php?section=" + this.ancestor.value;
	},
	checkLotterySelected: function(option) {
		lg(option)
		if (option.toLowerCase()=='lotterie') {
			$('lotterynumbercontainer').show();
			$('lotterytextcontainer').show();
		} else {
			$('lotterynumbercontainer').hide();
			$('lotterytextcontainer').hide();
		}
	}
});


var Pager =  Class.create({
	initialize: function(elm, params) {
		lg("start initializing Pager ");
		
		params = params || {};
		this.element = elm;
		this.entries = this.element.select("li");
		this.next = this.element.down('.next');
		this.prev = this.element.down('.prev');
		this.showCount = params.showCount || 2;
		this.pageCount = this.entries.eachSlice(this.showCount).length;

		this.activePage = 1;
		if (this.element.down("li.active")) {
			this.activePage = Math.ceil((this.element.down("li.active").previousSiblings().length+1) / this.showCount);
		}
		this.pagenum = this.element.down('.pagenum');

		this.createPaging();

		// initialen Inhalt anzeigen
		this.showPage(this.activePage);

		this.next.observe("click", this.showNext.bindAsEventListener(this));
		this.prev.observe("click", this.showPrev.bindAsEventListener(this));

		lg("end initializing Pager");
	},
	createPaging: function() {
		lg("createPaging");
		// wenn mehr als eine Seite vorhanden ist, müssen die Statuspunkte generiert und
		// mit der Klickmechanik versehen werden
		if (this.pageCount > 1) {
			var dot;
			for (i = 0; i < this.pageCount; i++) {
				this.pagenum.insert(dot = new Element("div", {
					className: "dot"
				}));
				dot.observe("click", this.showPage.bind(this, i + 1));
				lg(dot)
			}
			var width = ((this.pageCount) * this.pagenum.down('.dot').getWidth()) || this.pageCount * 9;
			this.pagenum.setStyle({
				width: width + "px"
			});
		} else {
			this.next.hide();
			this.prev.hide();
		}
	},
	showNext: function(event) {
		event.stop();
		lg("showNext");

		if (this.activePage < this.pageCount) {
			this.showPage(this.activePage+1);
		} else {
			this.showPage(1);
		}

	},
	showPrev: function(event) {
		event.stop();
		lg("showPrev");

		if (this.activePage > 1) {
			this.showPage(this.activePage-1);
		} else {
			this.showPage(this.pageCount);
		}
	},
	showPage: function(page) {
		lg("showPage("+page+")");
		this.activePage = page;

		// verstecke nicht benötigte und zeige geforderte Seiten
		this.entries.eachSlice(this.showCount).each(function(group, index) {
			if (page != index+1 ) {
				group.invoke("hide");
			} else {
				group.invoke("show");
			}
		});

		// CSS noch anpassen an neuen internen Status
		if (this.pagenum.down('.active'))
			this.pagenum.down('.active').removeClassName("active");

		if(this.pagenum.select('.dot') != '') {
			this.pagenum.select('.dot')[page-1].addClassName("active");
		}
		
		// wenn img-title und ein element mit klasse "changeable-caption" vorhanden ist:
		// caption-element mit dem title-inhalt fuellen
		if (this.entries[page-1].down('img')!=null) {
			var title = this.entries[page-1].down('img').title;
			var caption = this.element.down('.changeable-caption');
			if (title!=null && title!='' && caption!=null) {
				caption.update(title);
			}
		}
	}
});


// erbt das meiste von Pager, nur initialize() und showPage() muessen ueberschrieben werden
var Feedpager =  Class.create(Pager, {
	initialize: function($super, elm, params) {
		//$super(elm, params);
		lg("start initializing Feedpager");

		params = params || {};
		this.element = elm;
		this.entries = this.element.select("li");
		this.next = this.element.down('.next');
		this.prev = this.element.down('.prev');
		this.activePage = 1;

		this.next.observe("click", this.showNext.bindAsEventListener(this));
		this.prev.observe("click", this.showPrev.bindAsEventListener(this));

		// groups speichert die anzahl der jeweiligen posts pro seite,
		// also z.B. [1, 2, 1, 1, 2]
		this.groups = [];
		var classPrefix = "news-1of";
		var elmcount;
		for (var i = 0; i < this.entries.length;) {

			// hol dir die Klassennamen des Listenelements und die Position
			// unserer Spezialklasse, die wir in classPrefix zwischengespeichert haben
			var classes = this.entries[i].classNames().toString();
			var pos = this.entries[i].classNames().toString().indexOf(classPrefix);

			// wenn wir einen validen Klassennamen haben, zieh dir die Anzahl
			// der Elemente in der Gruppe aus dem Namen
			if (pos > -1) {
				elmcount = classes.substr(pos + classPrefix.length, 1);
				elmcount = parseInt(elmcount);
			}
			// ist der Klassenname versehentlicherweise nicht korrekt,
			// setze den elmcount-Wert auf ganz hoch, was zu einem eleganten
			// Abbruch fuehrt
			else {
				elmcount = this.entries.length+1;
			}

			// falls versehentlich dem letzten element der newsliste die falsche
			// klasse (z.B. 1of2) mitgegeben wurde, obwohl es alleine ist
			if (i+elmcount >= this.entries.length ) {
				elmcount = this.entries.length - i;
			}

			// fuege die anzahl der posts auf dieser seite den groups hinzu
			this.groups.push(elmcount);
			this.entries[i].addClassName("nodivider");
			// erhoehe die schleifenvariable um den wert der posts, um erst bei den
			// elementen der naechsten seite weiterzumachen und keine doppelt zu zaehlen
			i += elmcount;

		}

		this.pageCount = this.groups.length;
		this.pagenum = this.element.down('.pagenum');

		this.createPaging();

		// initialen Inhalt anzeigen
		this.showPage(this.activePage);

		lg("end initializing Feedpager");

	},
	showPage: function(page) {
		lg("showPage("+page+")");
		this.activePage = page;

		// CSS der Paging-Punkte anpassen an neuen internen Status
		if (this.pagenum.down('.active'))
			this.pagenum.down('.active').removeClassName("active");
		this.pagenum.select('div')[this.activePage-1].addClassName("active");

		// verstecke nicht benötigte und zeige geforderte Seiten
		var current = 0;
		for (var i = 0; i < this.groups.length; i++) {
			if (i == this.activePage-1) {
				for (var j = 0; j < this.groups[i]; j++) {
					if (this.entries.length >= current + j) {
						this.entries[current + j].show();
					}
				}
			} else {
				for (var j = 0; j < this.groups[i]; j++) {
					if (this.entries.length >= current + j) {
						this.entries[current + j].hide();
					}
				}
			}
			current += this.groups[i];
		}

		lg("end showPage");
	}
});


// Tooltip, eingesetzt in der Mediathek Listenübersicht
var Tooltip = Class.create({
	initialize: function(elm, id, params) {
		this.element = elm;
		this.id = id;
		this.content = null;
		this.params = params || {};

		if (!$('tooltip')) {
			this.tooltip = new Element("div", {
				id: "tooltip",
				style: "display: none",
				role: "tooltip"
			});

			$(document.body).insert(this.tooltip);			

			this.tooltip.observe("mouseenter", this.tooltipenter.bindAsEventListener(this));
			this.tooltip.observe("mouseleave", this.mouseleave.bindAsEventListener(this));

		} else {
			this.tooltip = $('tooltip');
		}

		this.element.observe("mouseenter", this.mouseenter.bindAsEventListener(this));
		this.element.observe("mouseleave", this.mouseleave.bindAsEventListener(this));

		this.element.title = "";

		if (this.params) {
			if (this.params.followLink == false) {
				this.element.observe("click", function(event) {
					event.stop();
				}.bindAsEventListener(this));
			}
		}
	},
	mouseenter: function(event) {
		var fail = true;

		if (!this.content) {

			new Ajax.Updater($('tooltip'), 'index.php', {
				parameters: {
					type: this.element.classNames().toString(),
					id: this.id,
					ajax: 'y',
					ajax_routine: 'medialayer',
					php_self: escape(location.href)
				},
				onSuccess: function(transport){
					if (transport.responseText != "") {
						this.content = transport.responseText;
						fail = false;
					}
				}.bind(this),
				onComplete: function(){
					if (!fail)
						this.show(event);
				}.bind(this)
			});
		}
		else {
			$('tooltip').update(this.content);
			this.show(event);
		}
	},
	mouseleave: function(event) {
		this.hide();
	},
	show: function(event) {
		Effect.Queues.get('tip').each(function(effect) {effect.cancel();});

		if(this.params.showPagerItems && $$('#tooltip .seriespager li').size() > this.params.showPagerItems) {
			new Pager($$('#tooltip .seriespager')[0], {showCount: this.params.showPagerItems});
			$$('#tooltip .pager')[0].show();
		} else if(!this.params.showPagerItems && $$('#tooltip .seriespager li').size() > 3) {
			new Pager($$('#tooltip .seriespager')[0], {showCount: 3});
			$$('#tooltip .pager')[0].show();
		} else {
			if($$('#tooltip .pager')[0])
				$$('#tooltip .pager')[0].hide();
		}
				
		if (this.params.upsideDown) {
			this.tooltip.addClassName('upsideDown');
		} else {
			this.tooltip.removeClassName('upsideDown');
		}

		if (this.params.followMouse) {
			var y = event.pointerY();
			var x = event.pointerX();
		} else if (this.params.upsideDown) {
			var y = this.element.cumulativeOffset().top + this.element.getHeight();
			var x = this.element.cumulativeOffset().left;
		} else {
			var y = this.element.cumulativeOffset().top - this.tooltip.getHeight()+10;
			var x = this.element.cumulativeOffset().left;
		}

		this.tooltip.setStyle({
			left: x + "px",
			top: y + "px"
		});

		this.tooltip.appear({
			duration: 0.2,
			delay:0.3,
			queue: {
				position: 'end',
				scope: 'tip'
			}
		});
	},
	hide: function() {
		Effect.Queues.get('tip').each(function(effect) {effect.cancel();});

		this.tooltip.fade({
			duration: 0.1,
			delay:0.2,
			queue: {
				position: 'end',
				scope: 'tip'
			}
		});
	},
	tooltipenter: function(event) {
		Effect.Queues.get('tip').each(function(effect) {
			effect.cancel();
		});

		this.tooltip.appear({
			duration: 0.2,
			queue: {
				position: 'end',
				scope: 'tip'
			}
		});

	}
});

var Accordion = Class.create({
	initialize: function(elm) {
		var maxHeight = 0;
		var maxWidth = 0;
		this.element = elm;
		this.headlines = this.element.select('li > h2');
		this.contents = this.element.select('div.content').invoke("hide");
		this.element.select('h2').each(function(elm) {
			maxWidth = Math.max(elm.getWidth(), maxWidth);
		});
		this.entries = this.element.select('li').invoke("setStyle", "width:"+maxWidth+"px; ");
		this.active = null;
		this.animating = false;
		
		
		
		this.headlines.each(function(h2) {
			var index = this.entries.length - h2.up('li').nextSiblings().length - 1;
			
			h2.down("a").observe("click", function(event){
				event.stop();
				this.goToPage(index);
			}.bindAsEventListener(this));
			
		}.bind(this));
		
		this.goToPage(0);
	},
	goToPage: function(page) {
		if (this.active != page && !this.animating) {
			this.animating = true;
			var effects = [];
			var targetWidth;
			var fxParams = {
				sync: true
			};
			
			if (this.active != null) {
				targetWidth = this.headlines[page].show().getWidth();
				this.headlines[this.active].hide();
				effects.push(new Effect.Appear(this.headlines[this.active], fxParams));
				effects.push(new Effect.Fade(this.contents[this.active], fxParams));
				effects.push(new Effect.Morph(this.entries[this.active], {
					style: "width:"+targetWidth+"px",
					sync: true
				}));
			}
			
			targetWidth = this.contents[page].show().getWidth();
			this.contents[page].hide();
			effects.push(new Effect.Fade(this.headlines[page], fxParams));
			effects.push(new Effect.Appear(this.contents[page], fxParams));
			effects.push(new Effect.Morph(this.entries[page], {
				style: "width:"+targetWidth+"px",
				sync: true
			}));
			
			new Effect.Parallel(effects, {
				duration: 0.6,
				afterFinish: function() {
					this.active = page;
					this.animating = false;
				}.bindAsEventListener(this)
			});
			
		}
	}
});

var ChronikSlider = Class.create({
	initialize: function(params){
		this.build();
		this.observePaging();
	},
	build: function() {
		// falls es schon einen slider gibt, eventListener und slider selbst loeschen
		if (this.slider && this.slider.options && this.slider.options.onChange) {
			this.slider.options.onChange = null;
			this.slider = null;
		}
		
		// hol dir die anzahl der jahre
		this.valueElms = $('timelineslider').up().down(".timeline").childElements();

		// berechne den pixel-abstand zwischen den jahren und positioniere die jahre
		var width = Math.floor(($('timelineslider').getWidth() - this.valueElms[0].getWidth()) / (this.valueElms.length-1));
		this.widthVals = [];
		this.valueElms.each(function(li, index) {
			li.setStyle({
				left:Math.floor(index*width - li.getWidth()/2) + "px"
			});
			this.widthVals.push(Math.floor(index*width - li.getWidth()/2));
		}.bind(this));

		// wenn es noch kein aktuelles jahr gibt, hol es dir aus der timeline-beschriftung
		if (!this.currentYear)
			this.currentYear = parseInt(this.valueElms[0].up().down(".active").down().innerHTML);
		
		// wenn es noch kein naechstes jahr gibt, hol es dir aus der timeline-beschriftung.
		// wenn dort keins mehr ist (weil wir im letzten jahr des aktuellen timeframe sind),
		// dann hol es dir aus der URL des von PHP generierten "Next"-Link
		if (!this.nextYear) {
			if (this.valueElms[0].up().down(".active").nextSiblings().length) {
				this.nextYear = parseInt(this.valueElms[0].up().down(".active").nextSiblings()[0].down().innerHTML);
			} else {
				this.nextYear = $('timelinepaging').down('.next').href.toQueryParams()['year'] || 0;
			}
		}
		
		// wenn es noch kein vorheriges jahr gibt, hol es dir aus der timeline-beschriftung.
		// wenn dort keins mehr ist (weil wir im ersten jahr des aktuellen timeframe sind),
		// dann hol es dir aus der URL des von PHP generierten "Prev"-Link
		if (!this.prevYear) {
			if (this.valueElms[0].up().down(".active").previousSiblings().length) {
				this.prevYear = parseInt(this.valueElms[0].up().down(".active").previousSiblings()[0].down().innerHTML);
			} else {
				this.prevYear = $('timelinepaging').down('.prev').href.toQueryParams()['year'] || 0;
			}
		}

		// wenn es noch keinen aktuellen timeframe gibt, hol ihn dir aus der zeitabschnitt-liste
		// anhand der klasse des aktiven timeframes
		if (typeof(this.timeframe) == "undefined") {
			this.timeframe = $('timeframeselector').down('a.active').up('li').previousSiblings().length;
		}
		
		// erstelle den slider
		this.slider = new Control.Slider('timelinehandler', 'timelineslider', {
			minimum: 0,
			maximum: $('timelineslider').getWidth(),
			range: $R(0, this.widthVals[this.widthVals.length-1] + parseInt($('timelinehandler').getStyle("margin-left"))),
			onChange: this.onChange.bindAsEventListener(this),
			values: this.widthVals,
			sliderValue: this.getPositionFromYear(this.currentYear)
		});
		
	},
	observePaging: function() {
		// belege den next-link mit einem eventListener
		if ($('timelinepaging').down('.next')) {
			$('timelinepaging').down('.next').observe("click", this.goToNextYear.bindAsEventListener(this));
		}
		
		// belege den prev-link mit einem eventListener
		if ($('timelinepaging').down('.prev')) {
			$('timelinepaging').down('.prev').observe("click", this.goToPrevYear.bindAsEventListener(this));
		}
		
		// belege die timeframe-links mit einem eventListener
		$('timeframeselector').select('a').each(function(link, index){
			link.observe("click", this.goToTimeframe.bindAsEventListener(this, index));
		}.bind(this));
		
		this.managePagingVisibility();
	},
	// managePagingVisibility sorgt dafuer, dass immer nur die next/previous-Links
	// zu sehen sind, die auch Sinn machen und kuemmert sich um die korrekte
	// auszeichnung des aktiven timeframes
	managePagingVisibility: function() {
		if (this.nextYear) {
			$('timelinepaging').down('.next').show();
			$('timelinepaging').down('.next').update("Weiter zu " + this.nextYear);
		} else {
			$('timelinepaging').down('.next').hide();
		}
		
		if (this.prevYear) {
			$('timelinepaging').down('.prev').show();
			$('timelinepaging').down('.prev').update("Zur&uuml;ck zu " + this.prevYear);
		} else {
			$('timelinepaging').down('.prev').hide();
		}
		
		$('timeframeselector').down("a.active").removeClassName("active");
		$('timeframeselector').select("li")[this.timeframe].down("a").addClassName("active");
	},
	onChange: function(value) {
		// wenn jemand am slider rumzieht, hol dir das neue jahr
		if (this.valueElms[this.getIndexFromPosition(value)].down()) {
			var year = this.valueElms[this.getIndexFromPosition(value)].down().innerHTML;
			this.goToYear(year);
		}
	},
	goToYear: function(year) {
		// AJAX-request, wenn das jahr gewechselt wird (ueber slider oder prev/next-links)
		new Ajax.Request('?', {
			parameters: {
				year: year,
				lastYear: this.currentYear,
				ajax: true
			},
			onSuccess: this.ajaxSuccess.bindAsEventListener(this)
		});
	},
	goToTimeframe: function(event, timeframe) {
		// AJAX-request, wenn der timeframe gewechselt wird
		// (ueber klicks auf die timeframe-links)
		event.stop();
		this.timeframe = timeframe;

		new Ajax.Request('?', {
			parameters: {
				timeframe: this.timeframe,
				lastYear: this.currentYear,
				ajax: true
			},
			onSuccess: this.ajaxSuccess.bindAsEventListener(this)
		});
	},
	goToNextYear: function(event) {
		event.stop();
		this.goToYear(this.nextYear);
	},
	goToPrevYear: function(event) {
		event.stop();
		this.goToYear(this.prevYear);
	},
	getIndexFromPosition: function(pixels) {
		var vindex; 
		this.widthVals.each(function(val, index) {
			if (val == pixels) {
				vindex = index;
			}
		});	
		return vindex;
	},
	getIndexFromYear: function(year) {
		var vindex;
		this.valueElms.each(function(elm, index) {
			if (elm.down().innerHTML == year) {
				vindex = index;
			}
		});		
		return vindex;
	},
	getPositionFromYear: function(year) {
		var vposition;
		this.widthVals.each(function(position, index) {
			if (this.valueElms[index].down().innerHTML == year) {
				vposition = position;
			}
		}.bind(this));
		return vposition;
	},
	ajaxSuccess: function(request) {
		// wird ausgefuehrt, wenn das mit dem AJAX-request geklappt hat
		
		// setze die neue umgebung
		this.timeframe = request.responseJSON.timeframe;
		this.currentYear = request.responseJSON.currentYear;
		this.nextYear = request.responseJSON.nextYear;
		this.prevYear = request.responseJSON.prevYear;
		
		if (request.responseJSON.type == "simple") {
			// wenn es ein simpler request war (kein timeframe-wechsel)
			$('yeardetails').update(request.responseJSON.response);
			
			this.valueElms[this.getIndexFromYear(this.currentYear)].up().down(".active").removeClassName("active");
			this.valueElms[this.getIndexFromYear(this.currentYear)].addClassName("active");
			$('timelinehandler').setStyle({left: this.getPositionFromYear(this.currentYear) + "px"});
			
		} else if (request.responseJSON.type == "complex") {
			// wenn es ein komplexer request war (neues jahr hat anderen timeframe als vorheriges)
			$('timelinecontainer').update(request.responseJSON.timelinecontent);
			this.build();
		}
		
		// aktualisiere noch die anzeige der prev/next/timeframe-links
		this.managePagingVisibility();
	}
});

var InitLink = Class.create({
	// als elm erwartet wird ein objekt mit den folgenden eigenschaften:
	/*
	{
		id: 'init-biene',
		key: 'biene',
		activeImg: "img/content/logo-biene-active.png",
		inactiveImg: "img/content/logo-biene-inactive.png"
	}
	*/
	initialize: function(elm, root) {

		lg("start initializing InitLink");
		// setze defaultwerte
		root = root || $(document.body);			// höchste Initalisierungsebene (im Normalfall <body>)
		this.content = null;						// cache-variable für ajax-inhalt
		this.elements = root.select("."+elm.id);	// elements beinhaltet alle relevanten Links

		// wenn elements leer ist, brich die ganze Initialiserung ab
		if (!this.elements[0]) {
			lg("no link in DOM, aborted initializing InitLink");
			return;
		} 

		this.key = elm.key;
		this.activeImg = elm.activeImg;
		this.inactiveImg = elm.inactiveImg;
		
		// hol dir das derzeitige Bild, das den Link in der oberen Box repräsentiert
		this.domimg = $$("."+elm.id).find(function(link){
			if (link.down("img") && link.down("img").hasClassName('stickylink'))
				return link.down("img");
		});
		if (this.domimg) {
			this.domimg = this.domimg.down("img");
			this.defaultImg = this.domimg.src;
		}
		
		// in welchem Container befinden wir uns? muss später animiert werden
		this.expandable = this.elements[0].up(".elementcontainer").down(".subelement").identify();

		// setze EventListener auf alle meine Links
		this.elements.each(function(link){
			link.observe("click", this.click.bindAsEventListener(this));
			//link.href = 'javascript:void(0)'; // for IE9
		}.bind(this));
		
		// listen auf diese Events
		document.observe("initlinks:activate", this.setActive.bind(this));
		document.observe("initlinks:deactivate", this.setInactive.bind(this));
		document.observe("initlinks:reset", this.setDefault.bind(this));
		
		this.boundLoadAjax = this.loadAjax.bind(this);
		lg("finished initializing InitLink");
	},
	click: function(event) {
		event.stop();

		// aktiviere dieses Linkbild (if) bzw. setze alle Linkbilder zurück (else) 
		if (this.domimg) {
			// deaktiviere alle Links
			document.fire("initlinks:deactivate");
			// aktuell geklicktes bild aktivieren
			this.setActive();
		} else {
			document.fire("initlinks:reset");
		}

		// sollte der container offen sein, blende den
		// Inhalt aus und lade danach den neuen Inhalt
		if ($(this.expandable).hasClassName("active")) {
			new Effect.Morph($("init-contentcontainer"), {
				duration: 0.4,
				style: "opacity:0",
				afterFinish: this.boundLoadAjax,
				queue: {
					scope: $("init-contentcontainer").identify(),
					limit: 1
				}
			});
		}
		// sonst lade einfach direkt den neuen Inhalt
		else {
			this.loadAjax();
		}
	},
	loadAjax: function() {
		lg("loadAjax()");

		// nimm den content aus dem cache, wenn er schon vorhanden sein sollte
		if (this.content) {
			lg("Content taken from cache.");
			$('init-contentcontainer').update(this.content);
			this.initializeDynamicContent();
			this.reopenContainer();
		}
		// lade den content per ajax, da er noch nicht im cache war
		else {
			lg("Content not in cache.");
			new Ajax.Request('index.php', {
				parameters: {
					key: this.key,
					ajax: 'y', 
					ajax_routine: 'initiativen'
				},
				onSuccess: function(transport) {
					lg("Ajax success.");
					this.content = transport.responseText;
					$('init-contentcontainer').update(this.content);
					this.initializeDynamicContent();
					this.reopenContainer();
					
					// Links veretrackern
					// Duplikat der Veretrackerung angepasst an Prototype
					if ($$('body')[0].readAttribute('data-et')) {
						$('init-contentcontainer').select("a[href^='http']").each(function(elm){
							var inWhitelist = false;
							for (i = 0; i < etrackerWhitelist.length; i++) {
								if (elm.href.indexOf(etrackerWhitelist[i]) > -1) {
									inWhitelist = true;
								}
							}
							if (inWhitelist || (elm.hostname.replace(/www./, '') != location.hostname.replace(/www./, '') && elm.hostname != 'www.etracker.de')) {
								var externalUrl =  $(elm).readAttribute('href');
								//var indexOfParameter = externalUrl.indexOf('?');
								var linkName = externalUrl;
								/*
								if (indexOfParameter > 0) {
									linkName = externalUrl.substring(0, externalUrl.indexOf('?'));
								}
								*/
								elm.observe("click", function(event){
									$(elm).writeAttribute('href','http://www.etracker.de/lnkcnt.php?et=' + $$('body')[0].readAttribute('data-et') + '&url=' + escape(externalUrl) + '&lnkname=' + escape(linkName)).addClassName('external');
								});
							}
						});
					}


				}.bind(this)
			});
		}
	},
	initializeDynamicContent: function() {
		// initialisiere die Links in dem neuen Inhalt
		// (wenn keine vorhanden sein sollten, kümmert sich die Klasse automatisch darum)
		initiativen.each(function(elm) {
			new InitLink(elm, $('init-contentcontainer'));
		});

		// Initialisiere die Slideshows (falls welche drin sein sollten)
		$('init-contentcontainer').select('.slideshow').each(function(elm){
			new Pager(elm, {showCount: 1});
		});
		
		document.fire("expandable-"+this.expandable+":resize");
	},
	reopenContainer: function() {
		lg("reopenContainer()");

		// wenn der container offen ist, lass den inhalt einfaden
		if ($(this.expandable).hasClassName("active")) {
			this.containerFadeIn();
		}
		// ist der container geschlossen gewesen, sende das signal, ihn zu öffnen
		else {
			document.fire("expandable-"+this.expandable+":open");
			lg("fired: expandable-"+this.expandable+":open");
		}
	},
	containerFadeIn: function() {
		lg('containerFadein')
		// definiere gebundene Funktion
		this.boundFunc = function() {
			lg('containerFadein Effect.Morph')
			new Effect.Morph($("init-contentcontainer"), {
				duration: 0.4,
				style: "opacity:1",
				queue: {
					scope: $("init-contentcontainer").identify(),
					limit: 1
				}
			});
			document.stopObserving("expandable-"+this.expandable+":finishedResizing", this.boundFunc);
		}.bind(this);

		// observe ob der container fertig ist mit resizen, ruf dann die gebundene funktion auf (s.o.)
		document.observe("expandable-"+this.expandable+":finishedResizing", this.boundFunc);
		// gib dem container den befehl, zu resizen
		document.fire("expandable-"+this.expandable+":resize");

	},
	// die folgenden drei Funktionen setzen den Aktiv-Zustand des Link-Bildes (sofern vorhanden)
	setInactive: function() {
		lg("setInactive");
		if (this.domimg){
			this.domimg.src = this.inactiveImg;
			this.domimg.up().removeClassName('active');
		} 
	},
	setActive: function() {
		lg("setActive");
		if (this.domimg){
			this.domimg.src = this.activeImg;
			this.domimg.up().addClassName('active');
		}
	},
	setDefault: function() {
		lg("setDefault");
		if (this.domimg){
			this.domimg.src = this.defaultImg;
			this.domimg.up().removeClassName('active');
		}
	}
});

var Expandable = Class.create({
	initialize: function(elm, params) {
		lg("start initialize Expandable");
		this.openhandler = elm;
		this.handler = elm.up('a');
		this.secondaryHandler = null;
		this.element = this.handler.up('.hpportal-elm').down(".subelement");
//		this.content = this.element.down(".shadowcontent");
		this.content = this.element.down(0);
		this.active = false;
		this.height = this.content.getHeight();
		this.element.identify();  // versieht das Element mit einer ID, falls noch keine vorhanden ist
		/*
		if (this.element.up('.elementcontainer') && this.element.up('.elementcontainer').down('.secondaryopenhandler')) {
			this.secondaryHandler = this.element.up('.elementcontainer').down('.secondaryopenhandler');
		}
		*/
		
		// content initial verstecken, falls nicht eingeblendet
		if (this.content.readAttribute('aria-hidden')=='false') {
			// eingeblendet
			this.content.setStyle({
				overflow:"hidden"
			});
			this.element.addClassName("active");
			this.active = true;
			this.handler.writeAttribute('aria-expanded', 'true');
		} else {
			// ausgeblendet
			this.content.setStyle({
				height:"0px",
				overflow:"hidden",
				display:"none"
			});
			this.element.removeClassName("active");
			this.content.removeClassName('activated');
			this.handler.writeAttribute('aria-expanded', 'false');
		}
		
		this.handler.writeAttribute('aria-controls', this.element.identify());
		
		// öffnen-funktionalität
		this.handler.observe("click", this.click.bindAsEventListener(this));
		if (this.secondaryHandler) {
			this.secondaryHandler.observe("click", this.clickSecondary.bindAsEventListener(this));
		}
		
		// listener definieren
		document.observe("expandable-"+this.element.identify()+":toggle", this.click.bindAsEventListener(this));
		document.observe("expandable-"+this.element.identify()+":open", this.open.bind(this));
		document.observe("expandable-"+this.element.identify()+":close", this.close.bind(this));
		document.observe("expandable-all:close", this.close.bind(this));
		document.observe("expandable-"+this.element.identify()+":resize", this.resize.bind(this));
		
		lg("finished initializing Expandable");		
	},	
	updateTitles: function(){
		var from 	= this.active ? 'ausblenden' : 'anzeigen';
		var to 		= this.active ? 'anzeigen' : 'ausblenden';		
		
		this.handler.writeAttribute('title', this.handler.readAttribute('title').split(from).join(to));
		this.handler.update(this.handler.innerHTML.split(from).join(to));
		if (this.secondaryHandler) {
			this.secondaryHandler.writeAttribute('title', this.secondaryHandler.readAttribute('title').split(from).join(to));
		}		
	},
	click: function(event) {
		lg("click");
		event.stop();
		
		// halte alle effekte an
		Effect.Queues.get(this.element.identify()).each(function(effect) {effect.cancel();});
		
		if (this.active) {
			this.updateTitles();
			this.close();
		}
		else {
			this.updateTitles();
			this.open();
		}
	},
	clickSecondary: function(event) {
		lg("clickSecondary");
		event.stop();
		
		// halte alle effekte an
		Effect.Queues.get(this.element.identify()).each(function(effect) {effect.cancel();});
		
		if (!this.active) {
			this.updateTitles();
			this.open();
		}
	},	
	open: function() {
		if (!this.active) {
			lg("start opening");

			if (!isIE(7) && !isIE(6)) { // führt zu darstellungsproblemen
				document.fire("expandable-all:close");
			}
			
			// vorbereiten der neuen höhe
			this.content.setStyle({
				display:"block",
				height:"auto"
			});
			// hol die neue hoehe
			this.height = this.content.getHeight();

			this.content.setStyle({
				height:"0px"
			});

			// versteck den hilfs-oeeffner
			if (this.secondaryHandler) {
				this.secondaryHandler.hide();
			}

			this.handler.addClassName("open");
			
			// morphe zu neuer Höhe			
			this.element.addClassName("active");
			this.element.up(".elementcontainer").addClassName("active");
			this.active = true;
			new Effect.Morph(this.content, {
				duration: 1,
				style: "height:" + this.height + "px; padding-bottom:0px;",
				afterFinish: this.endOpen.bind(this),
				queue: {
					scope: this.element.identify(),
					limit: 1
				}
			});	
		}	
	},
	close: function() {		
		if (this.active) {
			lg("start closing");
			this.handler.removeClassName("open");
			this.element.removeClassName("active");
			this.element.up(".elementcontainer").removeClassName("active");
			this.content.removeClassName('activated');
			this.active = false;
			new Effect.Morph(this.content, {
				duration: 1,
				style: "height:0px; padding-bottom:0px;",
				afterFinish: this.endClose.bind(this),
				queue: {
					scope: this.element.identify(),
					limit: 1
				}
			});
			if (isIE(7) && this.element.down('.slideshow')!=null) {
				this.element.down('.slideshow').hide();
			}
		}
	},
	// funktion, die von höhe 1 zu höhe 2 resized
	resize: function() {
		// cache alte höhe
		var tempHeight = this.content.getHeight();
		// hole neue höhe
		this.content.setStyle({
			height:"auto"
		});
		var newHeight = this.content.getHeight();
		// setze wieder auf alte höhe
		this.content.setStyle({
			height:tempHeight+"px"
		});
		
		// morphe zu neuer höhe und feure den dazugehörigen event ab
		new Effect.Morph(this.content, {
			duration: 0.4,
			style: "height:"+newHeight+"px;",
			afterFinish: function() {
				document.fire("expandable-"+this.element.identify()+":finishedResizing");
			}.bind(this),
			queue: {
				scope: this.element.identify(),
				limit: 1
			}
		});
	},
	endOpen: function() {
		lg("end opening");
		document.fire("expandable-"+this.element.identify()+":finishedOpening");
		this.content.writeAttribute('aria-hidden', 'false');
		this.handler.writeAttribute('aria-expanded', 'true');
		this.content.addClassName('activated');
	},
	endClose: function() {
		lg("end closing");
		// zeig den hilfs-oeeffner
		if (this.secondaryHandler) {
			this.secondaryHandler.show();
		}
		this.content.setStyle({
			display:"none"
		});
		if (isIE(7) && this.element.down('.slideshow')!=null) {
			this.element.down('.slideshow').show();
		}
		document.fire("expandable-"+this.element.identify()+":finishedClosing");
		this.content.writeAttribute('aria-hidden', 'true');
		this.handler.writeAttribute('aria-expanded', 'false');
		
		// behebt bug in ie8
		var handlerStyle = this.handler.getStyle('margin');
		this.handler.setStyle({margin: '0'});
		this.handler.setStyle({margin: handlerStyle});
	}
});
