$(document).ready(function() {
	// !once - header
	$('#header').append('<span class="monitor">' +
							'<span class="header-tryme" />' +
							'<span class="header-monitor" />' +
							'<span class="header-batteries" />' +
							'<span class="arrow arrow-w" />' +
							'<span class="screen" />' +
							'<span class="bn bn-xxs" rel="xxs" />' +
							'<span class="bn bn-xs" rel="xs" />' +
							'<span class="bn bn-s" rel="s" />' +
							'<span class="bn bn-m" rel="m" />' +
							'<span class="bn bn-l" rel="l" />' +
							'<span class="bn bn-xl" rel="xl" />' +
						'</span>' +
						'<span class="radio">' +
							'<span id="radio" />' +
							'<span class="radio-bg"><span class="radio-box" style="display: none;" /></span>' +
							'<span class="radio-slogan" />' +
							'<span class="radio-bn radio-play" />' +
							'<select class="radio-select"></select>' +
							'<span class="radio-note-1" />' +
							'<span class="radio-note-2" />' +
							'<span class="radio-note-3" />' +
							'<span class="radio-note-4" />' +
						'</span>');
	$('#header').find('.bn').click(function() {
		var cache = new Image(),
			relimg = $(this).attr('rel'),
			newimg = 'http://static.tjg-dresden.de/media/img/bg-' + relimg + '.jpg',
			target = $('#background').stop(true).fadeTo(300, 0, function() {
				cache.onload = function() {
					target.css({ 'opacity': 0, 'background-image': 'url(' + cache.src + ')' }).fadeTo(300, 1);
					$('.screen').attr('className', 'screen screen-' + relimg);
					$.cookie('tjg_bg', relimg);
				}
				cache.src = newimg;
			});
	}).filter('.bn-' + ($.cookie('tjg_bg') || 'xxs')).click();

	// !	radio controls
	var box = $('.radio-box').hide(),
		notes = $('.radio-note-1,.radio-note-2,.radio-note-3,.radio-note-4').css('opacity', 0),
		select = $('#header').find('.radio-select'),
		minLeft = 565,
		maxLeft = 851,
		minDelay = 0,
		maxDelay = 1000,
		minDuration = 3000,
		maxDuration = 6000,
		animNoteIdle = false,
		animNoteStart = function(el, loop) {
			var step = 0,
				rand = Math.random();
			el.css({ 'left': Math.floor(rand * (maxLeft - minLeft + 1)) + minLeft, 'top': 150, 'opacity': 0 }).show();
			el.delay(loop ? 0 : Math.floor(rand * (maxDelay - minDelay + 1)) + minDelay);
			el.animate({ 'top': -el.height() }, {
				'duration': Math.floor(rand * (maxDuration - minDuration + 1)) + minDuration,
				'easing': 'linear',
				'step': function(s, fx) {
					if (step < 100 && animNoteIdle)
						$(this).css('opacity', step / 100).show();
					step++;
				},
				'complete': function() {
					if (animNoteIdle) animNoteStart($(this), true);
				}
			});
		},
		animNoteStop = function(el) {
			el.animate({ 'opacity': 0 }, {
				'duration': 1000,
				'queue': false,
				'complete': function() {
					el.hide().stop(true);
				}
			});
		};

	for (i in window.sounds)
		select.append('<option value="' + i + '"><strong>' + (parseInt(i) + 1) + '.</strong> ' + window.sounds[i].name + '</option>');
	select.change(function() {
		jwplayer('radio').playlistItem(select.val());
	});
	jwplayer('radio').setup({
		'flashplayer': 'http://static.tjg-dresden.de/media/swf/jwplayer-5.4.swf',
		'file': window.sounds[0].file,
		'playlist': window.sounds,
		'repeat': 'list',
		'allowfullscreen': false,
		'controlbar': 'none',
		'icons': false,
		'dock': false,
		'wmode': 'transparent',
		'volume': 100,
		'height': 1,
		'width': 1,
		'modes': [
			{ 'type': 'html5' },
			{ 'type': 'flash', 'src': 'http://static.tjg-dresden.de/media/swf/jwplayer-5.4.swf' },
			{ 'type': 'download' }
		],
		'events': {
			'onPlay': function() {
				$('.radio-bn').removeClass('radio-play').addClass('radio-pause');
				notes.each(function() {
					animNoteIdle = true;
					animNoteStart($(this));
				});
				box.show();
			},
			'onPause': function() {
				$('.radio-bn').removeClass('radio-pause').addClass('radio-play');
				notes.each(function() {
					animNoteIdle = false;
					animNoteStop($(this));
				});
				box.hide();
			},
			'onPlaylistItem': function(ev) {
				if (select.val() != ev.index)
					select.val(ev.index).change();
				/* box.show(); */
			}
		}
	});
	$('.radio-bn').click(function() {
		jwplayer('radio').play();
	});

	// !	screen
	var arrow = $('#header .arrow');
	setInterval(function() {
		arrow.toggleClass('arrow-w arrow-g');
	}, 600);

	// !once - page instance
	var tjg = new Page();
		tjg.jwcontrols = function() {
			return	'<span class="jwcontrols">' +
						'<span class="pp" />' +
						'<span class="progress">' +
							'<span class="position loadhead" />' +
							'<span class="position playhead" />' +
						'</span>' +
					'</span>';
		}
		tjg.jwsetup = function(stage, holder, video, image, events) {
			if (!holder.find('.jwcontrols').length)
				holder.prepend(tjg.jwcontrols);
			if (/safari/gi.test(navigator.userAgent) && !/chrome|icab|opera/gi.test(navigator.userAgent))
				holder.find('.progress').hide();
			return {
				'flashplayer': 'http://static.tjg-dresden.de/media/swf/jwplayer-5.4.swf',
				'file': 'http://www.youtube.com/watch?v=' + video,
				'image': image,
				'allowfullscreen': false,
				'stretching': 'fill',
				'controlbar': 'none',
				'icons': false,
				'dock': false,
				'volume': 100,
				'height': stage.innerHeight(),
				'width': stage.innerWidth(),
				'modes': [
					{ 'type': 'html5' },
					{ 'type': 'flash', 'src': 'http://static.tjg-dresden.de/media/swf/jwplayer-5.4.swf' },
					{ 'type': 'download' }
				],
				'events': events || {}
			}
		}
		tjg.onloadbegin = function(callback) {
			var target = $('#content');
			var loader = $('#loader');
			var holder = target.children(':not(#loader)').wrapAll('<div />').parent();

				target.addClass('idle').css({
					'height': holder.outerHeight(),
					'overflow': 'hidden'
				});
				loader.fadeIn(300);
				holder.fadeTo(300, 0, function() {
					holder.html('').css('visibility', 'hidden').show();
					(callback || function() {})();
				});
		}
		tjg.onloadfinish = function(response, xhr, callback) {
			var target = $('#content'),
				loader = $('#loader'),
				holder = target.children(':not(#loader)').first();
				holder.html($(response).find('#content').html());
			var height = holder.outerHeight();
				height = height >= 620 ? height : 620;
				$('#navigation').html($(response).find('#navigation').html());
				target.animate({ 'height': height }, 600, function() {
					loader.fadeOut(300);
					holder.hide().css('visibility', 'visible').fadeTo(300, 1, function() {
						target.removeClass('idle').css({
							'height': 'auto',
							'overflow': 'visible'
						});
						(callback || function() {})(response, xhr);
					});
				});
		}
		tjg.setup = function(self, url) {
			self = self || this;
			var idle = false;

			// !defaults, inputDefault, Selects
			$('.noscript').removeClass('noscript');
			$('textarea, input:text, input:password').inputDefault();
			$('select:visible').replaceSelect();
			$('input:radio, input:checkbox:not(input[name="lists[]"])').replaceCheckers();
			$('input[name="lists[]"]').replaceCheckers(function(m, link) {
				$('input:hidden[name="lists"]').val('');
				if ($(link).is('.active'))
					$('input:hidden[name="lists"]').after('<input type="hidden" name="lists[]" value="' + $(link).text() + '" />');
				else $('input:hidden[name="lists[]"][value="' + $(link).text() + '"]').remove();
			});
			$('.nolink').attr('target', '_blank');

			// !top links
			$('.ce_toplink a').click(function(ev) {
				ev.preventDefault();
				$('body').animate({ 'scrollTop': 0 }, 500);
			});

			// !extra print-button in schedule
			$('.schedule .mod_module_tjg_schedule_nav').after($('#header .buttons .bn-print').clone());

			// !forms
			//$('form').unbind('submit').submit(function(ev) {
/*
			$('form:not(#tl_avisota_recipient)').unbind('submit').submit(function(ev) {
				ev.preventDefault();
				var form = $(this);
				var href = form.attr('action').replace(/^\/*#+\//g, '');
				if (href[0] != '#') {
					form.attr({ 'rev': href.replace(self.urlBase, '') });
					form.attr({ 'action': '/#/' + href.replace(self.urlBase, '') });
				}
				if (!self.isIdle()) {
					self.idle();
					//location.href = form.attr('action');
					$.post(form.attr('rev'), form.serialize() + '&ajax=true&REQUEST_TOKEN=' + REQUEST_TOKEN, function(response, status, xhr) {
						if (xhr.getResponseHeader('Request-Token')) {
							REQUEST_TOKEN = xhr.getResponseHeader('Request-Token');
							$('input[name="REQUEST_TOKEN"]').val(REQUEST_TOKEN);
						}

						if ($(response).find('#' + form.attr('id') + ' .error').length) {
							form.replaceWith($(response).find('#' + form.attr('id')));
							self.setup(tjg);
							self.unidle();
						} else {
							self.unidle();
							location.href = '/#/' + xhr.getResponseHeader('Referer').replace(self.urlBase, '');
						}
					});
				}
				return false;
			});
*/

			// !teaser image slide toggle
			$('.ce_teaser_custom .image_container').toggle(
				function() {
					var i = $(this).find('img');
					$(this).stop(true).animate({ 'height': $(i).height() }, {
						'duration': 300,
						'step': function(s, fx) {
							$(i).css('top', ($(i).data('t') - fx.pos * $(i).data('t')) + 'px');
						}
					});
				},
				function() {
					var i = $(this).find('img');
					$(this).stop(true).animate({ 'height': 200 }, {
						'duration': 300,
						'step': function(s, fx) {
							$(i).css('top', fx.pos * $(i).data('t')) + 'px';
						}
					});
				}
			).find('img').load(function() {
				$(this).data('t', (200 - $(this).height()) / 2);
				$(this).css('top', $(this).data('t') + 'px');
			});

			// !listing - sortable
			$('.listing.sortable th:not(.sorter)').each(function() {
				var values = {
						'original': [],
						'ascending': [],
						'descending': []
					},
					affect = $(this).parents('table').find('tr.handle td.' + $(this).attr('title')).each(function(i) {
						var element = $(this).parents('tr.handle').next('tr.content:first').andSelf();
							values.original.push({
								'index': i,
								'element': element,
								'value': $(this).attr('title') || $(this).text()
							});
						$(this).removeAttr('title');
					}),
					sorter = $(this).addClass('sorter').removeAttr('title').attr('unselectable', 'true').click(function(ev) {
						// sort only if more than one item
						if (values.original.length > 1) {
							// build cache if necessary
							if (!values.ascending.length || !values.descending.length) {
								values.ascending = values.original.slice();
								// sort date
								//if ($(this).is(':not(.sort-abc).sort-date') || values.ascending[0].value.match(/^(\d{2}\.\d{2}\.\d{4})+(\s*(\d{2}\:\d{2})+)*/)) {}
								// sort numeric
								if ($(this).is('.sort-123') || values.ascending[0].value.match(/\d+/)) {
									values.ascending.sort(function(a, b) {
										var x = parseInt(a.value.match(/\d+/)),
											x = (!isNaN(x)) ? x : 0;
										var y = parseInt(b.value.match(/\d+/)),
											y = (!isNaN(y)) ? y : 0;
										return x - y;
									});
								}
								// sort abc
								else {
									values.ascending.sort(function(a, b) {
										var x = a.value.toLowerCase(),
											y = b.value.toLowerCase();
										return (x < y) ? -1 : ((x > y) ? 1 : 0);
									});
								}
								values.descending = values.ascending.slice().reverse();
							}

							var sorted = !$(this).is('.asc');
							var parent = $(this).parents('table').find('tbody');
							var copies = values[sorted ? 'ascending' : 'descending'];

							$(this).removeClass(sorted ? 'desc' : 'asc').addClass(sorted ? 'asc' : 'desc');
							$(this).siblings('th').removeClass('asc desc');

							for (var i = 0; i < copies.length; i++) {
								copies[i].element.removeClass('first last even odd').detach();
								if (i == 0)
									copies[i].element.addClass('first');
								if (i == copies.length-1)
									copies[i].element.addClass('last');
								if (i % 2)
									copies[i].element.addClass('even');
								else
									copies[i].element.addClass('odd');
								parent.append(copies[i].element);
							}
						}
					});

				if (sorter.find('span').length < 1)
					sorter.prepend('<span />');
			});

			// !listing - spieler
			var intScope = 0;
			$('.list-spieler .item').each(function() {
				var container = $(this).addClass('idle'),
					imagewrap = container.find('.images').hide(),
					arrCaches = [],
					arrLoaded = [],
					arrImages = imagewrap.find('img');
				if (arrImages.length)
					arrImages.each(function(i) {
						arrCaches[i] = new Image();
						arrCaches[i].onload = function() {
							arrLoaded.push(this.src);
							if (arrLoaded.length == arrImages.length) {
								imagewrap.hide().fadeIn(300, function() {
									container.removeClass('idle');
								});
							}
						}
						arrCaches[i].src = $(this).attr('src');
					});
			}).hover(
				function() {	
					var item = $(this);
					intScope = setInterval(function() {
						var img = item.find('.images img:visible');
						if (img.length > 1) img.filter(':last').hide();
						else item.find('.images img').show();
					}, 500);
				},
				function() {
					if (intScope)
						clearInterval(intScope);
					//$(this).find('.images img').show();
				}
			);

			// !listing - ajax
			$('.listing tr.handle[title]').unbind('click').click(function(ev) {
				ev.preventDefault();
				var handle = $(this),
					parent = handle.next('tr.content'),
					target = parent.find('td').first(),
					holder = target.find('.holder'),
					offset = $('body').scrollTop(),
					req = self.environment.getRequest();
		
					if (holder.is(':visible')) {
						self.idle();

						// link the new content
						if (handle.parents('.mod_module_tjg_schedule').length)
							location.href = '/#/' + self.environment.setRequest([req[0], req[1], req[2]].join('/'));
						else location.href = '/#/' + self.environment.setRequest([req[0]].join('/'));

						// close
						holder.stop(true).css('overflow', 'hidden').animate({ 'height': 0 }, {
							duration: 350,
							complete: function() {
								handle.removeClass('active');
								parent.removeClass('idle');
								holder.hide().find('.cache').remove(); // remove to tweak ie performance
								self.unidle();
							}
						});
					} else {
						handle.addClass('active').siblings('tr.handle.active').find('.title a').click();
						self.idle();
						// implement caching here
						// for preventing the reload
						// of allready loaded contens
						// near ...(true).html('<div />').add...
						holder.stop(true).html('<div class="cache" />').addClass('idle').show().animate({ 'height': 100 }, {
							duration: 350,
							complete: function() {
								var cache = holder.find('> div').css('visibility', 'hidden'),
									href = handle.find('td a').attr('href');

								// prevent history plugin from redirecting
								self.idle();

								// link the new content
								if (handle.parents('.mod_module_tjg_schedule').length)
									location.href = '/#/' + (req.length > 3
													? self.environment.setRequest([req[0], req[1], req[2], handle.attr('rel')].join('/'))
													: self.environment.addToUrl(handle.attr('rel')));
								else location.href = '/#/' + (req.length > 1
													? self.environment.setRequest([req[0], handle.attr('rel')].join('/'))
													: self.environment.addToUrl(handle.attr('rel')));

								// abort previous request
								if (self.request)
									self.request.abort();

								// Request contents
								self.request = $.post(href, 'ajax=true&REQUEST_TOKEN=' + REQUEST_TOKEN, function(response, status, xhr) {
									if (xhr.getResponseHeader('Request-Token')) {
										REQUEST_TOKEN = xhr.getResponseHeader('Request-Token');
										$('input[name="REQUEST_TOKEN"]').val(REQUEST_TOKEN);
									}

									if (holder.is(':visible') && !holder.is(':animated')) {
										cache.html($(response).find('.article-contents').html());
										cache.find('.tickets-' + handle.attr('rel')).addClass('active');
										holder.animate({ 'height': cache.outerHeight() }, {
											duration: 600,
											easing: 'easeInOutBack',
											complete: function() {
												holder.fadeTo(100, 0, function() {
													cache.css('visibility', 'visible');
													holder.removeClass('idle').fadeTo(200, 1, function() {
														if (offset == $('body').scrollTop())
															$('body').animate({ 'scrollTop': target.offset().top - 50 }, 500);
														self.ajaxLinking();
														self.unidle();
														self.setup();
														holder.css({ 'overflow': 'visible', 'height': 'auto' });
														holder.find('.listing-gallery a.thumb.image:first').click();
													});
												});
											}
										});
									}
								});
							}
						});
					}
			});

			// !prepare deeplinks
			$('*[title^="deep:"]').each(function(i, deeplink) {
				$(deeplink).attr('rel', $(deeplink).attr('title').replace(/^deep:/, ''));
				$(deeplink).removeAttr('title');

				//console.log($(deeplink).attr('rel') == self.environment.getCurrent().deep, $(deeplink).attr('rel'),self.environment.getCurrent().deep)
				if ($(deeplink).attr('rel') == self.environment.getCurrent().deep) {
					self.unidle();
					if ($(deeplink).parents('.listing'))
						$('body').animate({ 'scrollTop': $(deeplink).offset().top - 50 }, 500, function() {
							$(deeplink).click();
						});
				}
			});

/*
			// !open latest schedule entry
			if ($('.mod_module_tjg_schedule') && self.environment.getRequest().length < 4) {
				var date = new Date();
				var stamp = parseInt(date.getTime() / 1000);
				$('.listing tr.handle').filter(function(i) {
						var time = /ts-([\d]{10})/gi.exec($(this).attr('className')) || [];
							time = parseInt(time[1]);
						if (time > stamp && new Date(time * 1000).getMonth() == date.getMonth())
							return true;
					}).first().click();
			}
*/

			// !listing - gallery
			$('.listing-gallery').unbind('mouseenter').mouseenter(function(ev) {
				var thumbs = $(this).find('.thumbs:not(:empty)').stop(true, true).slideDown(200),
					thumbw = thumbs.find('.scroll').outerWidth(),
					stagew = $(this).width(),
					offset = $(this).offset(),
					scroll = thumbw - stagew;
				if (scroll > 0) $(this).mousemove(function(ev) {
					thumbs.find('.scroll-wrapper').scrollLeft((ev.pageX - offset.left) / stagew * scroll);
				});
			});
			$('.listing-gallery').unbind('mouseleave').mouseleave(function(ev) {
				$(this).find('.thumbs:visible:not(:empty)').stop(true, true).slideUp(400);
			});
			$('.listing-gallery a.thumb').unbind('click').click(function(ev) {
				ev.preventDefault();
		
				// embedding video and/or image
				if (!$(this).parents('.listing-gallery.idle').size() && !$(this).is('.active')) {
					var thumb = $(this);
						thumb.parents('.listing-gallery').addClass('idle');
						thumb.addClass('active').siblings().removeClass('active');
					var thumbs = thumb.parents('.thumbs:first');
					var tmpid = 'stage-' + Number(new Date());
					var stage = thumb.parents('.listing-gallery').addClass('idle').find('.stage');
					var image = stage.find('img');
						image = image.size() ? image.fadeOut(300) : stage.html('<img id="' + tmpid + '" style="display:none;" />').find('img');
					var cache = new Image();
						cache.id = tmpid;
						cache.onload = function() {
							image.replaceWith(cache);
							image = stage.children().first().hide().fadeIn(300);
							if (thumb.is('.video') && thumb.attr('rel'))
								jwplayer(tmpid).setup(self.jwsetup(stage, thumbs, thumb.attr('rel'), cache.src, {
									'onPlay': function(ev) {
										thumb.find('.icon').removeClass('icon-play').addClass('icon-pause');
										thumbs.find('.pp').removeClass('play').addClass('pause');
										jwplayer('radio').pause(true);
									},
									'onPause': function(ev) {
										thumb.find('.icon').removeClass('icon-pause').addClass('icon-play');
										thumbs.find('.pp').removeClass('pause').addClass('play');
									},
									'onReady': function(ev) {
										thumb.parents('.listing-gallery').removeClass('idle');
										thumbs.find('.pp').addClass('play').unbind('click').click(function() {
											jwplayer(tmpid).play();
										});
									},
									'onTime': function(ev) {
										thumbs.find('.playhead').css('width', (ev.position / ev.duration * 100) + '%');
										// should be onMeta, or if the duration is available, see
										// http://www.longtailvideo.com/support/forums/jw-player/javascript-interaction/18638/onmeta-event-and-getduration-with-youtube-streams
										thumbs.find('.progress').unbind('click').click(function(ev) {
											jwplayer(tmpid).seek((ev.pageX - $(this).find('.playhead').offset().left) / $(this).innerWidth() * jwplayer(tmpid).getDuration());
										});
									},
									'onBufferChange': function(ev) {
										thumbs.find('.loadhead').css('width', ev.bufferPercent + '%');
									}
								})).play();
							else thumbs.find('.jwcontrols').fadeTo(300, 0, function() { $(this).remove(); });

							thumb.parents('.listing-gallery').removeClass('idle');
						}
						cache.src = $(this).attr('href');
				}
		
				// video controls
				else if ($(this).is('.video.active'))
					jwplayer($(this).parents('.listing-gallery').find('.stage > *:first').attr('id')).play();
			});

			// !single videos
			$('.stage-video').each(function() {
				var stage = $(this),
					thumbs = stage.next('.thumbs:first'),
					tmpid = stage.attr('id') ? stage.attr('id') : 'stage-' + Number(new Date()),
					tmpimg = stage.find('img'),
					tmpload = new Image();
					tmpload.onload = function() {
						tmpimg.fadeIn(300, function() {
							jwplayer(tmpid).setup(self.jwsetup(stage, thumbs, tmpimg.attr('alt'), tmpimg.attr('src'), {
								'onPlay': function() {
									thumbs.find('.pp').removeClass('play').addClass('pause');
									jwplayer('radio').pause(true);
								},
								'onPause': function() {
									thumbs.find('.pp').removeClass('pause').addClass('play');
								},
								'onReady': function() {
									thumbs.find('.pp').addClass('play').unbind('click').click(function() {
										console.log(tmpid, jwplayer(tmpid))
										jwplayer(tmpid).play();
									});
								},
								'onTime': function(ev) {
									thumbs.find('.playhead').css('width', (ev.position / ev.duration * 100) + '%');
									// should be onMeta, or if the duration is available, see
									// http://www.longtailvideo.com/support/forums/jw-player/javascript-interaction/18638/onmeta-event-and-getduration-with-youtube-streams
									thumbs.find('.progress').unbind('click').click(function(ev) {
										jwplayer(tmpid).seek((ev.pageX - $(this).find('.playhead').offset().left) / $(this).innerWidth() * jwplayer(tmpid).getDuration());
									});
								},
								'onBufferChange': function(ev) {
									thumbs.find('.loadhead').css('width', ev.bufferPercent + '%');
								}
							}));
						});
					}
					tmpload.src = tmpimg.attr('src');
				$(this).attr('id', tmpid);
			});

			// !listing - tabs
			$('.listing-navigation a,#header .buttons a')
				.unbind('mouseover').mouseover(function(ev) {
					if (!$(this).is('.bn-close')) {
						var button = $(this).find('span');
						if (button.attr('rev'))
							button.text(button.attr('rev'));
					}
					$(this).stop(true).animate({ 'width': $(this).find('span').outerWidth()-1 }, 200);
				})
				.unbind('mouseleave').mouseleave(function(ev) {
					if (!$(this).is('.bn-close')) {
						var button = $(this).find('span');
						if (button.attr('rev'))
							button.text(button.attr('rev'));
						$(this).stop(true).animate({ 'width': 0 }, 200);
					}
				})
				.find('span').css('visibility', 'visible');
			$('.listing-navigation a.tab').unbind('click').click(function(ev) {
				ev.preventDefault();
				if (!idle) {
					idle = true;
					var parent = $(this).parents('.listing-navigation').siblings('.listing-contents'),
						button = $(this).find('span'),
						defcon = parent.find('.default'),
						content = parent.find('.' + this.rel),
						isself = content.is(':visible'),
						fadein = isself ? defcon : content,
						fadeout = isself ? content : content.siblings(':visible');

						parent.css('height', parent.height());
						fadein.css({ 'visibility': 'hidden', 'display': 'block' });
						var newheight = fadein.outerHeight();
						fadein.css({ 'visibility': 'visible', 'display': 'none' })
						fadeout.fadeOut(200, function() {
							parent.animate({ 'height': newheight }, 400, function() {
								fadein.fadeIn(200, function() {
									parent.css('height', 'auto');
									idle = false;
								});
							});
						});

					if (isself) {
						$(this).removeClass('bn-close').animate({ 'width': 0 }, 200, function() {
							button.text(button.attr('rev'));
						});
					} else {
						$(this).addClass('bn-close');
						button.attr('rev', button.text()).text(button.text() + ' schliessen');
						$(this).stop(true).animate({ 'width': button.outerWidth() }, 200);

						$(this).parents('li').siblings().find('.bn-close').removeClass('bn-close').animate({ 'width': 0 }, 200, function() {
							$(this).find('span').text($(this).find('span').attr('rev'));
						});
					}
				}
			});

			// !listing - noticket
			$('.noticket').each(function() {
				if (!$(this).find('.soldout').size())
					$(this).append('<span class="soldout" />').find('.soldout:last').css({ 'bottom': 0, 'opacity': 0 });
				$(this).hover(
					function() {
						$(this).find('.soldout:not(.opened)').addClass('opened').stop(true).animate({ 'bottom': 18, 'opacity': 1 }, 300);
					},
					function() {
						$(this).find('.soldout.opened').stop(true).animate({ 'bottom': 36, 'opacity': 0 }, 300, function() {
							$(this).removeClass('opened').css({ 'bottom': 0, 'opacity': 0 });
						});
					}
				);
			});
		}
		tjg.initialize = function() {
			// !history
			$.history.init(function(hash) {
				tjg.environment.setCurrent(hash);
				if (!tjg.isIdle() && hash) {
					var url = (hash.match(/\/spielplan\//) /*&& tjg.environment.getCurrent().hash.length < 4 */)
							|| hash.match(/\/theaterakademie-anmeldung\//)
							|| hash.match(/\/anmeldung\//)
							|| hash.match(/\/tickets\//)
							|| hash.match(/\/spieler-innen\//)
							? tjg.environment.getCurrentHash()
							: tjg.environment.getCurrentLink();
					if (tjg.request)
						tjg.request.abort();
					tjg.idle();
					tjg.loadContents(url, function(response, xhr) {
						$(response).filter('script').each(function() { $.globalEval($(this).html()); });
						tjg.environment.setCurrent(url);
						tjg.unidle();
					}, { ajax: true, 'REQUEST_TOKEN': REQUEST_TOKEN });
				} else tjg._setup();
			});
		}
		tjg.initialize();
});
