	// framework.js
	// ver 0.8

	$(document).ajaxError(function(e, xhr, settings, exception) {
			window.alert (settings.url+' '+exception);
		}
	);
	
			
	// GALLERY
	var galleryID=0;
	function loadGallery ($anchor, id) {

		$this=$anchor;
		sideBarUpdateRequests++;


		$.getJSON (jQuery.ideagento.libs.gallery.dataPath+'folders/'+id+'.json', function (data) {
		
			var breadCrumb='';
			if (id!=galleryID) {
				for (var i=0; i<data['parentPath'].length; i++) {
					breadCrumb='<A class="clickable" onclick="loadGallery ($this, '+data['parentPath'][i]['id']+')">'+data['parentPath'][i]['title']+'</A>'+breadCrumb;
					if (data['parentPath'][i]['id']==galleryID) break;
				}
			}
		
			if (data['folders'].length>0) {
				$this
					.empty ()
					.append ('<DIV class="contentArea"><DIV class="header"><DIV class="breadCrumb">'+breadCrumb+' '+data['title']+'</DIV></DIV></DIV>')
				;
				var $contentArea=$('.contentArea', $this);
				for (var i=0; i<data['folders'].length; i++) {
					var $folder=$('<DIV class="container clickable" folder="'+data.folders[i]['id']+'"><DIV class="thumbContainer"><IMG src="'+jQuery.ideagento.libs.gallery.imageLocation+data.folders[i]['preview']+'_tn.jpg"></DIV><DIV class="description">'+data['folders'][i]['title']+'</DIV></DIV>');
					$folder
						.appendTo ($contentArea)
						.click (function () {
							loadGallery ($this, $(this).attr ('folder'));
						})
					;
				}			
			} else {

				$this
					.empty ()
					.append ('<DIV class="contentArea"><DIV class="header"><DIV class="breadCrumb">'+breadCrumb+' '+data['title']+'</DIV></DIV><IMG class="contentImage" src="/_lib/img/clearpixel.gif"></DIV>')
					.append ('<DIV class="thumbArea"><DIV class="scrollLeft"></DIV><DIV class="scrollRight"></DIV><DIV class="innerThumbArea"></DIV></DIV>');
				;

			var $contentImage, $innerThumbArea, $thumbArea;
			var innerThumbAreaWidth=0;

			$contentImage=$('.contentImage', $this);
			
			$innerThumbArea=$('.innerThumbArea', $this);
			$innerThumbArea.css ('left', '75px');
			$thumbArea=$('.thumbArea', $this);
			for (var dummy=0, $wrapper; dummy<data.images.length; dummy++) {
				innerThumbAreaWidth+=jQuery.ideagento.libs.gallery.thumbHeight*(data.images[dummy]['width']/data.images[dummy]['height'])+10;
				$wrapper=$('<SPAN />')
					.appendTo ($innerThumbArea)
					.addClass ('thumbnail')
				;
				$('<IMG src="'+jQuery.ideagento.libs.gallery.imageLocation+data.images[dummy]['id']+'_tn.jpg">')	
					.css ({opacity: '0.6', height: jQuery.ideagento.libs.gallery.thumbHeight+'px', 'vertical-align': 'bottom'})
					.attr ('fadeIn', 0)
					.attr ('fadeOut', 0)
					.attr ('imageID', dummy)
					.bind ('mouseover', function () {
						if ($(this).attr ('fadeIn')==0) {
							$(this).attr ('fadeIn', 1);
							$(this).stop ().animate ({
								height: '75px',
								'margin-top': '0px',
								opacity: 1
							}, 'slow', 'swing', function () {
								$(this).attr ('fadeIn', 0);
							});
						}
					})
					.bind ('mouseout', function () {
						if ($(this).attr ('fadeOut')==0) {
							$(this).attr ('fadeOut', 0)
							$(this).animate ({
								height:	'50px',
								opacity: 0.6,
								'margin-top': '12px'
							}, 'normal', 'linear', function () {
								$(this).attr ('fadeOut', 0);
							});
						}
					})
					.bind ('click', function () {
						$contentImage.attr ('imageID', $(this).attr ('imageID'));
						$contentImage.animate ({
							opacity: 0
						}, 'fast', 'linear', function () {
							var image=data.images[$(this).attr ('imageID')];
							var imageObj=new Image ();
							if (parseInt (image['height'])<jQuery.ideagento.libs.gallery.imageMaxY) {
								$contentImage.css ('margin-top', parseInt ((jQuery.ideagento.libs.gallery.imageMaxY-image['height'])/2)+'px');
								$contentImage.css ('height', image['height']+'px');
							} else {
								$contentImage.css ('margin-top', '0px');
								$contentImage.css ('height', jQuery.ideagento.libs.gallery.imageMaxY+'px');
							}
							imageObj.src=jQuery.ideagento.libs.gallery.imageLocation+image['id']+'.jpg';
							$contentImage.attr ('src', jQuery.ideagento.libs.gallery.imageLocation+image['id']+'.jpg');
							if (imageObj.complete) {
								$contentImage.animate ({ opacity: 1 }, 'slow', 'linear');
							} else {
								$(imageObj).bind ('load', function () {
									$contentImage.animate ({ opacity: 1 }, 'slow', 'linear');
								});
							}
						});								
					})

				.appendTo ($wrapper);
			}
			// $innerThumbArea.css ('width', (innerThumbAreaWidth+30)+'px');
			$('.scrollRight', $this)	
				.bind ('mouseover', function () {
					var left=parseInt($innerThumbArea.css ('left'));
					if (left<=($thumbArea.width ()-innerThumbAreaWidth)) return;
					var duration=(-1)*($thumbArea.width ()-innerThumbAreaWidth-left-75)/jQuery.ideagento.libs.gallery.thumbScrollSpeed;
					$innerThumbArea.animate ({
						'left': '-='+(-1)*($thumbArea.width ()-innerThumbAreaWidth-left-75)
					}, {
						'duration': duration,
						easing: 'linear',
						queue: false
					})			
				})
				
				.bind ('mouseout', function () {
					$innerThumbArea.stop ();
				})
			;
						
			$('.scrollLeft', $this)	
				.bind ('mouseover', function () {
					var left=parseInt($innerThumbArea.css ('left'))-75;
					var duration=-left/jQuery.ideagento.libs.gallery.thumbScrollSpeed;
					if (left>=0) return;
					$innerThumbArea.animate ({
						'left': '+='+Math.abs(left)
					}, {
						'duration': duration,
						easing: 'linear',
						queue: false,
					});	
				})
				.bind ('mouseout', function () {
					$innerThumbArea.stop ();
				})
			;
						
						
			$('img[imageID=0]').trigger ('click');
			}
			
			sideBarUpdateRequests--;
			$('#sidebar').trigger ('refresh');
			
			});
		return false;
	}
	jQuery.fn.inlineGallery = function (map) {
		$(this).empty ();
		$(this).wrap ('<DIV class="container ui-helper-clearfix small inlineGalleryWrapper"></DIV>');
		galleryID=$(this).attr ('id');
		loadGallery ($(this), galleryID);
		// $(this).attr ('title', '');
	}

	// TABS
	jQuery.fn.tabView = function (map) {
		var $this=this;
		var $tabContent=$('<DIV class="tabContent ui-helper-clearfix"></DIV>').appendTo ($this);
		$('li a', $this).bind ('click', function () {
		
			if ($(this).hasClass ('noAjax')) {
			} else {
				sideBarUpdateRequests++;
				$('li', $this).removeClass ('active');
				$(this).parent ().addClass ('active');
				$tabContent.load (this.href, function () {	
					sideBarUpdateRequests--;
					$('#sidebar').trigger ('refresh');
					$('#messageWindowContent').trigger ('refresh');
				});
				return false;
			}

		});
		$('li a:eq(0)', $this).trigger ('click');
	}
	
	// EXPANDABLE
	jQuery.fn.expandableView = function (map) {
		var $this=$(this);
		var $headLine=$(':first', $this);
		$headLine.addClass (($this.hasClass ('minified')?'expandable-icon-minified':'expandable-icon-expanded'));
		$headLine
			.addClass ('clickable')
			.bind ('click', function () {
				sideBarUpdateRequests++;
				$headLine.next ().toggle ('slow', function () {
					sideBarUpdateRequests--;
					$('#sidebar').trigger ('refresh');
				});
				$headLine.toggleClass ('expandable-icon-expanded').toggleClass ('expandable-icon-minified');
				$this.toggleClass ('minified');
			})
		;
	}

	// BREADCRUMB
	var breadCrumb={top:{title:'', href:''}, chapter:{title:'', href:''}, section:{title:'', href:''}, subsection:{title:'', href:''}};

	// LOGIN	
	function createOverlay (msg) {
		$('body')
			.css ('overflow', 'hidden')
			.append ('<DIV id="layerOverlay"></DIV>')
		;
		$('#layerOverlay').position ({
			my: 'center',
			at: 'center',
			of: window
		});
		var $msg=$('<DIV id="messageWindowContent"></DIV>');
		$msg.append (msg);
		
		var $messageWindow=$('<DIV id="messageWindow"></DIV>');
		$messageWindow
			.appendTo ('body')
			.append ($msg)
			.bind ('refresh', function () {
				$messageWindow
					.position ({
						my: 'center',
						at: 'center',
						of: window
					})
				;
			})
			.trigger ('refresh')
		;
	}
	function destroyOverlay () {
		$('#layerOverlay').fadeToggle ('fast', function () {
			$('#layerOverlay').remove ();
			$('body').css ('overflow', 'auto')
		});
		$('#messageWindow').fadeToggle ('fast', function () {
			$('#messageWindow').remove ();
			
		});
	}
	function createPersonalLoggedIn () {
		var userData=$.evalJSON ($.cookie ('userData'));
		var $personal=$('#personal');
		$('.content', $personal)
			.empty ()
			.html ('Sie sind eingeloggt als '+userData['vorname']+' '+userData['nachname']+'<UL class="linkList"><LI><A href="/registration/">zum persönlichen Bereich</A></LI></UL>')
		;
		$('.footer', $personal)
			.empty ()
			.addClass ('ui-helper-clearfix')
			.html ('<BUTTON type="button" id="logoutButton">abmelden</BUTTON>')
		;
		
		$('#logoutButton', $personal).click (function () {			
		sideBarUpdateRequests++;
			$.ajax ({
				url: '/_lib/php/registrated/logout.php',
				dataType: 'json',
				type: 'post',
				global: false,
				contentType: 'application/x-www-form-urlencoded',
				success: function (data) {	
					$.cookie('userData', null, { path: '/' });
					$.cookie('stayAliveKey', null, { path: '/' });
					createPersonalLoggedOut ();
				}
			});								
		});
		$('.private').removeClass ('hidden');		
		sideBarUpdateRequests--;
		$('#sidebar').trigger ('refresh');
	}
	function createPersonalLoggedOut () {
		var $personal=$('#personal');
		$('.content', $personal)
			.addClass ('ui-helper-clearfix')
			.empty ()
			.html ('<label for="email">E-Mail</label><INPUT type="text" name="email"><label for="pw">Passwort</label><INPUT type="password" name="pw"><INPUT type="checkbox" name="stay">angemeldet bleiben<BR><A href="/personal/register/" class="RIGHT">registrieren</A>')
		;
		$('.footer', $personal)
			.empty ()
			.addClass ('ui-helper-clearfix')
			.html ('<BUTTON type="button" id="loginButton">anmelden</BUTTON>')
		;
		
		$('#loginButton', $personal).click (function () {	
			sideBarUpdateRequests++;
			$.ajax ({
				url: '/_lib/php/registrated/login.php',
				dataType: 'json',
				data: { 
					email: $('#personal input[name=email]').val (),
					pw: $('#personal input[name=pw]').val (),
					stay: $('#personal input[name=stay]').attr('checked')
				},
				type: 'post',
				global: false,
				contentType: 'application/x-www-form-urlencoded',
				beforeSend: function () {
					createOverlay ($('<SPAN>'+jQuery.ideagento.msgs.wait+'</SPAN>'));
				},
				success: function (data) {	
					if (data!=null) {							
						$.cookie('userData', $.toJSON (data), { path:'/' });
						createPersonalLoggedIn ();	
					} else {
						$('#personal .footer .error').remove ();
						$('#personal .footer').prepend ('<DIV class="error">FEHLER - falsche EMail-Adresse, oder falsches Passwort</DIV>');
					}
					destroyOverlay ();
					sideBarUpdateRequests--;
					$('#sidebar').trigger ('refresh');
				}
			});								
		});
		sideBarUpdateRequests--;
		$('#sidebar').trigger ('refresh');
		
	}


	
	
	function animateFade () {
	
		$image=$('.animationFader').last ();
		$image.fadeToggle (4000, function () {
			var $this=$(this);	
			$this
				.prependTo ($('#headerAnimation'))
				.css ('display', '')
			;
			window.setTimeout ('animateFade ()', 3000);									
		});
	
	}
	
	function initAnimations () {
	
		if (typeof (getCSS ('#headerAnimation .animationFader[title="1"]', 'backgroundImage'))!='undefined' || typeof (getCSS ('#headerAnimation [title=\'1\'].animationFader', 'backgroundImage'))!='undefined') {
			for (var i=1; typeof (getCSS ('#headerAnimation .animationFader[title="'+i+'"]', 'backgroundImage'))!='undefined'; i++) {
				$('#headerAnimation').prepend ('<DIV class="animationContainer animationFader" title="'+i+'"></DIV>')
			}
			for (var i=1; typeof (getCSS ('#headerAnimation [title=\''+i+'\'].animationFader', 'backgroundImage', 'backgroundImage'))!='undefined'; i++) {
				$('#headerAnimation').append ('<DIV class="animationContainer animationFader" title="'+i+'"></DIV>')
			}
			window.setTimeout ('animateFade ()', 3000);			
		}
	}
	
	
	// GOOGLE-MAPS
	function showGoogleMapsTermine (config) {
	
	
		myPosition=null;
		if ($('#googleMapTermine').length) {
			$.getJSON ('/_data/termine'+config.year+'.json', function (data) {					
				$('#googleMapTermine').googleMap ({ center: [config.geo.x, config.geo.y], zoom: config.geo.zoom, navigationControl: false });
				var startAdress=(typeof ($.cookie ('userData'))=='undefined' || $.cookie ('userData')==null )?null:($.evalJSON ($.cookie ('userData')))['adresse'];
					
				if (startAdress!=null) {
					$('#googleMapTermine').googleMap ('addMarker', {
						position: startAdress,
						icon: jQuery.ideagento.libs.googleMaps.icons.pin_orange,
						callBack: function (marker) {
							myPosition=marker;
						}
					});
				}
					
				$(document).bind ('themeSwitched', function () {
					google.maps.event.trigger(jQuery.ideagento.libs.googleMaps.maps.googleMapTermine.object, 'resize');
					$('#googleMapTermine').googleMap ('setCenter', {
						center: [51.508742, 10.656738]
					});
				});
				
				var now=new Date ();				
				for (var i=0, content; i<data.length; i++) {
					content='<DIV class="infoWindowContent"><STRONG>'+data[i]['name']+'</STRONG><BR>';
					var abgelaufenerTermin=1;
					for (var j=0; j<data[i]['wochen'].length; j++) {
						content+=((j==0)?'':'<BR>');
						content+=data[i]['wochen'][j]['datum'];
						if ((data[i]['wochen'][j].timestamp*1000+1000*60*60*24*2)>now.getTime ()) abgelaufenerTermin=0;
					}
					content+='</DIV>';
					if (!abgelaufenerTermin) {
					$('#googleMapTermine').googleMap ('addMarker', { 
						position: [data[i]['geo']['x'],data[i]['geo']['y']], 
						icon: jQuery.ideagento.libs.googleMaps.icons.pin_blue,
						infoWindow: {
							content: content
						},
						wrappedData: {
							link: data[i]['rel_url']
						},
						mouseover: function (event) {
							event.data.element.showInfoWindow ();
							if (myPosition!=null) {
								$('#googleMapTermine').googleMap ('calcRoute', {
									route:[
										{marker: myPosition},
										{marker: event.data.element}
									],
									callBack: function (response) {
										var responseText='<P class="infoWindowCalcRoute">Entfernung: '+response.routes[0].legs[0].distance.text+'<BR>Fahrtdauer: '+response.routes[0].legs[0].duration.text+'</P>';
										jQuery.ideagento.libs.googleMaps.directions.request.route[1].marker.properties.infoWindow.object.setContent (jQuery.ideagento.libs.googleMaps.directions.request.route[1].marker.properties.infoWindow.content+responseText);
									}
								});
							}
						},
						mouseout: function (event) { event.data.element.hideInfoWindow (); },
						click: function (event) { window.location.href=event.data.element.properties.wrappedData.link; }
					});						
					}
				}					
			});
		}
	};
	
	function  showGoogleMapsTerminSidebar(year) {
		myPosition=null, targetPosition=null;
		$.getJSON ('/_data/termine'+year+'.json', function (data) {		
			for (var i=0; i<data.length; i++) {
			
				if (location.href.search (data[i]['rel_url'])!=-1) {
					$('#sideBarMapTermine').googleMap ({
						center: [data[i].geo.x, data[i].geo.y],
						zoom: 5,
						navigationControl: false
					});	

					$('#sideBarMapTermine').googleMap ('addMarker', { 
						position: [data[i]['geo']['x'],data[i]['geo']['y']], 
						icon: jQuery.ideagento.libs.googleMaps.icons.pin_blue,
						click: function (event) {
							$('#sideBarMapTermine').googleMap ('setZoom', {
								zoom: 8
							});
						},
						callBack: function (marker) {
							targetPosition=marker;
							var startAdress=(typeof ($.cookie ('userData'))=='undefined' || $.cookie ('userData')==null )?null:($.evalJSON ($.cookie ('userData')))['adresse'];

							if (startAdress!=null) {
								$('#sideBarMapTermine').googleMap ('addMarker', {
									position: startAdress,
									icon: jQuery.ideagento.libs.googleMaps.icons.pin_orange,
									callBack: function (marker) {
										myPosition=marker;			

										jQuery.ideagento.libs.googleMaps.directions.display= new google.maps.DirectionsRenderer({
											preserveViewport: false,
											markerOptions: {
												visible: false
											}
										});
										
										$('#sideBarMapTermine').googleMap ('calcRoute', {
											route:[
												{marker: myPosition},
												{marker: targetPosition}
											],
											callBack: function (response) {
												var responseText='<P class="infoWindowCalcRoute">Entfernung: '+response.routes[0].legs[0].distance.text+'<BR>Fahrtdauer: '+response.routes[0].legs[0].duration.text+'</P>';
												$('#sideBarMapTermine').after (responseText);
											}
										});																
									}
								});
							}					
						}
					});					
				}
			}
		});
	};
	
		
		
	// DOCUMENT-READY
	$(document).ready (function () {
	

		if (environment=='development') $('body').prepend ('<DIV id="debug" style="position: absolute;"></DIV>');
		jQuery.ideagento.browser.dim.windowHeight=$(window).height ();
		jQuery.ideagento.browser.dim.windowWidth=$(window).width ();
		initAnimations ();
		initImageText ();
		$('#content a[href^=http]').attr ('targer', '_blank');
		
		// BOOKMARKS
		var title=encodeURIComponent ('spectaculum.de - '+$('title').html ());
		var url=encodeURIComponent (window.location.href);
		var description=encodeURIComponent ($('meta[name=description]').attr ('content'));
		$('#bookmarks a[title="delicious"]').attr ('href', 'http://del.icio.us/post?url='+url+'&title='+title);
		$('#bookmarks a[title=twitter]').attr ('href', 'http://twitter.com/home?status='+url);
		$('#bookmarks a[title=facebook]').attr ('href', 'http://de.facebook.com/sharer.php?u='+url+'&t='+title);
		$('#bookmarks a[title=mrwong]').attr ('href', 'http://www.mister-wong.de/index.php?action=addurl&bm_url='+url+'&bm_description='+title);
		$('#bookmarks a[title=myspace]').attr ('href', 'http://www.myspace.com/index.cfm?fuseaction=postto&t='+title+'&c='+description+'&u='+url);
		$('#bookmarks a[title=digg]').attr ('href', 'http://digg.com/submit?phase=2&url='+url+'&title='+title);
		$('#bookmarks a[title=webnews]').attr ('href', 'http://www.webnews.de/einstellen?url='+url+'&title='+title);
		$('#bookmarks a[title=yigg]').attr ('href', 'http://www.yigg.de/neu?exturl='+url+'&exttitle='+title);
		
		
		// THEME PICKER 2
		if (typeof (jQuery.ideagento)!='undefined' && jQuery.ideagento.data.themes.length) {
			var themeDummy=theme.split ('/');
			themeDummy=themeDummy[themeDummy.length-2];
			var $themeContainer=$('<DIV class="container"><DIV class="header">Layout</DIV><DIV class="content"><P>Wählen Sie das Layout, in dem Sie spectaculum.de erleben möchten:</P></DIV><DIV class="footer"></DIV></DIV>');
			$themeContainer.appendTo ('#sidebar');
			var $themePicker=$('<SELECT style="width: 100%"></SELECT>');
			$('.content', $themeContainer).append ($themePicker);
			
			for (var i=0; i<jQuery.ideagento.data.themes.length; i++) {
				var $theme=$('<OPTION value="'+i+'">'+jQuery.ideagento.data.themes[i]['title']+'</OPTION>');
				if (themeDummy==jQuery.ideagento.data.themes[i]['title']) $theme.attr ('selected', 'selected');
				$theme.appendTo ($themePicker);
			}
			
			$themePicker
					.bind ('change', function (event) {
						var themeNumber=$(this).val ();
						$('body')
							.append ('<DIV id="fadeSite" style="background-color: #000; display: none; position: absolute; top: 0px; z-Index: 9999; width: 100%; height: '+$(document).height ()+'px"></DIV>')
						;
						$('#fadeSite')
							.fadeToggle ('slow', function () {
								$.get (jQuery.ideagento.data.themes[themeNumber]['path']+'styles2011.css', function (data){
									$('#themeStyle').remove ();
									$('#themeLink').remove ();
									$("head").append('<style id="themeStyle">'+data+'</style>');
									initImageText ();
									initCloud ();
									jQuery.ideagento.browser.dim.sidebarWidth=$('#sidebar .container').width ();	
									var colorScheme='light';
									if (jQuery.ideagento.data.themes[themeNumber]['title']=='gothic') colorScheme='dark';
									$('.facebookLikeBox').html ('<DIV style="height: 393px; width: '+(parseInt ($('.container .content').width ())-2)+'px; overflow: hidden;"><iframe id="facebookLikeBox" src="//www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fmpsfestival&amp;width='+$('.container .content').width ()+'&amp;height=395&amp;colorscheme='+colorScheme+'&amp;show_faces=false&amp;border_color=%23fff&amp;stream=true&amp;header=false" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:'+$('.container .content').width ()+'px; height:395px; margin:-1px;" allowTransparency="true"></iframe></DIV>');
									
									$('#fadeSite').fadeToggle ('slow', function () {
										$('#fadeSite').remove ();
									});
									$.cookie ('theme', jQuery.ideagento.data.themes[themeNumber]['path'], { path:'/', expires: 60 });
									$('#footer').css ('visibility', 'hidden');
									window.setTimeout ('initAnimations ()', 300);			
									window.setTimeout ("$('#sidebar').trigger ('refresh')", 1000);									
									$(document).trigger ('themeSwitched');
								})
							})
						;																								
					})			
			;
		}		

		// LOGIN	
		if (!personal) {
			var $personal=$('<DIV id="personal" class="container"><DIV class="header">Persönlicher Bereich</DIV><DIV class="content"></DIV><DIV class="footer"></DIV></DIV>');
			$personal.appendTo ('#sidebar');
			sideBarUpdateRequests++;
			if (typeof ($.cookie)!='undefined' && $.cookie ('userData')) {
				createPersonalLoggedIn ();
			} else {
				createPersonalLoggedOut ();
			}
			
			if ($.cookie('stayAliveKey')!=null && $.cookie('userData')==null) {
				$('button', $personal).trigger ('click');
			}
		}
		
		
		
		// INLINE-GALERIEN
		$('.inlineGallery').each (function () {
			$(this).inlineGallery ();			
		});
		
		// OVERLAY-LINKS
		$('.showOverlay').click (function () {
			var $this=$(this);
			createOverlay ($('<SPAN>'+jQuery.ideagento.msgs.wait+'</SPAN>'));
			$('#messageWindowContent').load ($this.attr ('href')+' .overlayContent', function () {
					$('#messageWindow').css ('display', 'block');
					$('.tabContainer', $('#messageWindowContent')).each (function () { $(this).tabView (); });
					$('#messageWindowContent').trigger ('refresh');
			});			
			return false;
		});
		if (getUrlVars()['overlay']) $('.showOverlay[href='+getUrlVars()['overlay']+']').trigger ('click');

		
		// TABS
		$('.tabContainer').each (function () {
			$(this).tabView ();			
		});
		
		// EXPANDABLE
		$('.expandable').each (function () {
			$(this).expandableView ();
		});		

		// BREADCRUMB
		$('link').each (function () {
			switch (this.rel) {
				case 'top':	
					breadCrumb.top['href']=this.href;
					breadCrumb.top['title']=this.title;
				break;
				case 'chapter':	
					breadCrumb.chapter['href']=this.href;
					breadCrumb.chapter['title']=this.title;
				break;
				case 'section':	
					breadCrumb.section['href']=this.href;
					breadCrumb.section['title']=this.title;
				break;
				case 'subsection':	
					breadCrumb.subsection['href']=this.href;
					breadCrumb.subsection['title']=this.title;
				break;
			}
					
		});
		
		var htmlBreadCrumb='';		
		if (breadCrumb.top['title']) {
			if (breadCrumb.top['href']) htmlBreadCrumb+='<A class="internalLink" href="'+breadCrumb.top['href']+'">';
			htmlBreadCrumb+=breadCrumb.top['title'];
			if (breadCrumb.top['href']) htmlBreadCrumb+='</A>'; else htmlBreadCrumb+='<A></A>';
		}		
		if (breadCrumb.chapter['title']) {
			if (breadCrumb.chapter['href']) htmlBreadCrumb+='<A class="internalLink" href="'+breadCrumb.chapter['href']+'">';
			htmlBreadCrumb+=breadCrumb.chapter['title'];
			if (breadCrumb.chapter['href']) htmlBreadCrumb+='</A>'; else htmlBreadCrumb+='<A></A>';
		}
		if (breadCrumb.section['title']) {
			if (breadCrumb.section['href']) htmlBreadCrumb+='<A class="internalLink" href="'+breadCrumb.section['href']+'">';
			htmlBreadCrumb+=breadCrumb.section['title'];
			if (breadCrumb.section['href']) htmlBreadCrumb+='</A>'; else htmlBreadCrumb+='<A></A>';
		}
		if (breadCrumb.subsection['title']) {
			if (breadCrumb.subsection['href']) htmlBreadCrumb+='<A class="internalLink" href="'+breadCrumb.subsection['href']+'">';
			htmlBreadCrumb+=breadCrumb.subsection['title'];
			if (breadCrumb.subsection['href']) htmlBreadCrumb+='</A>'; else htmlBreadCrumb+='<A></A>';
		}		
		if (htmlBreadCrumb!='') {
			htmlBreadCrumb+=$('title').html ();	
		}
		$('#main').prepend ($('<DIV id="breadcrumb">'+htmlBreadCrumb+'&nbsp;</DIV>'));


	

		
		// NEWS
		if (typeof (newsCategory)=='string') {
			sideBarUpdateRequests++;
			$.getJSON (jQuery.ideagento.libs.news.dataPath+'views/'+newsCategory+'_last_5.json', function (data) {
				if (data.length) {
					var from={title: $('title').text (), href: window.location.href};
					$newsContainer=$('<DIV class="container"><FORM id="newsForm" method="post" action="'+jQuery.ideagento.libs.news.scriptPath+'"><INPUT type="hidden" name="from" value=\''+$.toJSON (from)+'\'><INPUT type="hidden" name="breadCrumb" value=\''+$.toJSON (breadCrumb)+'\'><INPUT type="hidden" name="view"><INPUT type="hidden" name="entry"></FORM><DIV class="header">Aktuelles</DIV><DIV class="content"></DIV></DIV>');
					var now=new Date ().getTime ();
					var ids4FullView=[];
					var j=0;
					for (var i=0; i<data.length && j<jQuery.ideagento.libs.news.entries4NewsBox; i++) {
						if (1000*data[i]['date']<now && 1000*data[i]['expiration_date']>now) {
							j++;
							var datum=new Date (1000*data[i]['date']);
							var entry=$('<P entry="'+data[i]['id']+'" view="'+newsCategory+'" class="ui-helper-clearfix"></P>');
							entry.html ('<strong class="right">'+data[i]['rubrik']+'</strong><strong>'+datum.strdate ('%d.%m.%Y')+'</strong><br>'+data[i]['title']+'<A href="'+jQuery.ideagento.libs.news.scriptPath+'?view='+newsCategory+'&entry='+data[i]['id']+'" class="right">mehr</A>');
							
							$('.content', $newsContainer).append (entry);
							$('a', entry).click (function () {
								$this=$(this);
								var entry= $this.closest ('p').attr ('entry');
								var view= $this.closest ('p').attr ('view');
								var $form=$('#newsForm');
						
								$('input[name=entry]', $form).val (entry);
								$('input[name=view]', $form).val (view);
								$form.submit ();
								return false;
							});
							if (j<=jQuery.ideagento.libs.news.entries4FullView) {
								ids4FullView.push (data[i]['id']);
							}
						}
					}
					
					if (j>0) {
						$newsContainer
							.append ('<DIV class="footer"><A href="/_data/blog2011/rss/all.xml" class="rss">&nbsp;</A><A href="/extras/news/?view='+newsCategory+'">Archiv</A></DIV>')
							.prependTo ('#sidebar');
						;
						$('.footer a[href^="/extras/news/"]', $newsContainer).click (function () {
							var $form=$('#newsForm');
							$('input[name=entry]', $form).val ('');
							$('input[name=view]', $form).val (newsCategory);
							$form.submit ();
							return false;
						});					
					}
					
					if (ids4FullView.length) {
					
						var $containerNews=$('#containerLastNewsEntry');
						if ($containerNews.length) {
							var map=[]
							for (var i=0; i<ids4FullView.length; i++) {
								map[i]={
									url: jQuery.ideagento.libs.news.dataPath+'entries/'+ids4FullView[i]+'.json',
									data: ''
								};
							}
							
						
							$.getJSONs (map, function (data) {
								____rata=data;
								var $containerNews=$('#containerLastNewsEntry');
			
								for (var i=0; i<data.length; i++) {
									var datum=new Date (1000*data[i].response.date);
									$containerNews
										.append ('<H3>'+datum.strdate ('%d.%m.%Y')+': '+data[i].response.title+'</H3>')
										.append (data[i].response.teaser)
										.append ('<DIV class="expandable minified"><P>Eintrag lesen</P><DIV class="expandableContainer">'+data[i].response.content+'</DIV>')
									;
								}
								$('.expandable', $containerNews).each (function () {
									$(this).expandableView ();
								});
;
							});
						
						
						
						}
										
					}
					
				}
				sideBarUpdateRequests--;
				$('#sidebar').trigger ('refresh');
			});
		
		}
		
		var colorScheme='light';
		if (theme=='/_lib/css/gothic/') colorScheme='dark';
		$('.facebookLikeBox').html ('<DIV style="height: 393px; width: '+(parseInt ($('.container .content').width ())-2)+'px; overflow: hidden;"><iframe id="facebookLikeBox" src="//www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fmpsfestival&amp;width='+$('.container .content').width ()+'&amp;height=395&amp;colorscheme='+colorScheme+'&amp;show_faces=false&amp;border_color=%23fff&amp;stream=true&amp;header=false" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:'+$('.container .content').width ()+'px; height:395px; margin:-1px;" allowTransparency="true"></iframe></DIV>');
		
		
		$('#sidebar').trigger ('refresh');
		
	});
	
	
	
	
	// Utility-Functions
	

	
	
jQuery.getJSONs = function (map, callback) {

	var i=map.length;
	var retData=[];
	
	function jsonRequest (j) {
		$.ajax ({
		
			url: map[j]['url'],
			dataType: 'json',
			data: map[j]['data'],
			global: false,
			success: function (data) {	
				retData[j]={response: data, request: map[j]};
			},
			error: function () {
				retData[j]={response: null, request: map[j]};
			},
			complete: function () {
				i--;
				if (i==0) callback (retData);					
			}
			
		});
	}	
	for (var j=0; j<map.length; j++) jsonRequest (j);
}	

function getCSS (theClass, element) {

	var cssRules;

	var added = false;
	var cssEntries=''
	for (var S = 0; S < document.styleSheets.length; S++){

		if (document.styleSheets[S]['rules']) {
			cssRules = 'rules';
		} else if (document.styleSheets[S]['cssRules']) {
			cssRules = 'cssRules';
		} 

		for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) {
			var singleSelectors=typeof (document.styleSheets[S][cssRules][R].selectorText)!='undefined'?document.styleSheets[S][cssRules][R].selectorText.split (','):[];
			for (var dummy=0; dummy<singleSelectors.length; dummy++) {
				cssEntries+=singleSelectors[dummy]+'<br>';
				if (singleSelectors[dummy].replace (/^\s+/, '').replace (/\s+$/, '')==theClass && document.styleSheets[S][cssRules][R].style[element]) return (document.styleSheets[S][cssRules][R].style[element]);
			}
		}		
	}
}

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

Date.prototype.strdate = function(retValue) {

  
  if (this.getYear ()<999) intAddYears=1900; else intAddYears=0;

  retValue=retValue.replace (/%m/g, (1+this.getMonth ()).toString ().strpad (2, '0', 1));
  retValue=retValue.replace (/%d/g, this.getDate ().toString ().strpad (2, '0', 1));
  retValue=retValue.replace (/%Y/g, (intAddYears+this.getYear ()));

  retValue=retValue.replace (/%H/g, (this.getHours ().toString ().strpad (2, '0', 1)));
  retValue=retValue.replace (/%i/g, (this.getMinutes ().toString ().strpad (2, '0', 1)));
  retValue=retValue.replace (/%s/g, (this.getSeconds ().toString ().strpad (2, '0', 1)));
  
  return (retValue);
}


String.prototype.strpad = function () {

  var STR_PAD_RIGHT=0, STR_PAD_LEFT=1, STR_PAD_BOTH=2;
  var retValue=new String(this);

  switch (arguments.length) {
    case 0:	return (retValue);
    		break;
    case 1: strPadChar=' ';
            intPadLength=arguments[0];
            strPadPosition=STR_PAD_RIGHT;

            break;
    case 2: strPadChar=arguments[1].substr (0,1);
            intPadLength=arguments[0];
            strPadPosition=STR_PAD_RIGHT;
            break;
    case 3: strPadChar=arguments[1].substr (0,1);
            intPadLength=arguments[0];
            strPadPosition=arguments[2];
            break;
  }

  switch (strPadPosition) {
    case 0: for (var dummy=this.length; dummy<intPadLength; dummy++) {
              retValue+=strPadChar;
            }
            break;
    case 1: for (var dummy=this.length; dummy<intPadLength; dummy++) {
              retValue=strPadChar+retValue;
            }
            break;
    case 2: for (var dummy=this.length; dummy<intPadLength; dummy+=2) {
              retValue+=strPadChar;
              if (retValue.length==intPadLength) break;
              retValue=strPadChar+retValue;
            }
            break;

  }

  return (retValue);
}

function clone(obj) {
        if(obj == null || typeof(obj) != 'object') return obj;
        var c = new obj.constructor();
        for(var key in obj) {
                c[key] = clone(obj[key]);
        }
        return c;
}

String.prototype.trim=function () { return this.replace (/^\s+/, '').replace (/\s+$/, ''); }
function debug (text) { $('#debug').html ($('#debug').html ()+text+'<br>') }

function strip_tags (input, allowed) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Luke Godfrey
    // +      input by: Pul
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +      input by: Alex
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Marc Palau
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Eric Nagel
    // +      input by: Bobby Drake
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Tomasz Wesolowski
    // +      input by: Evertjan Garretsen
    // +    revised by: Rafał Kukawski (http://blog.kukawski.pl/)
    // *     example 1: strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>');
    // *     returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
    // *     example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
    // *     returns 2: '<p>Kevin van Zonneveld</p>'
    // *     example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
    // *     returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
    // *     example 4: strip_tags('1 < 5 5 > 1');
    // *     returns 4: '1 < 5 5 > 1'
    // *     example 5: strip_tags('1 <br/> 1');
    // *     returns 5: '1  1'
    // *     example 6: strip_tags('1 <br/> 1', '<br>');
    // *     returns 6: '1  1'
    // *     example 7: strip_tags('1 <br/> 1', '<br><br/>');
    // *     returns 7: '1 <br/> 1'
    allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
        commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
    return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
        return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
    });
}
