jQuery.noConflict();

if (!console) var console = {};
if (!console.error) console.error = function(){};


var setClickableTeaser = function(teaser, url){
	teaser.setStyle({cursor:'pointer'});

	teaser.observe('click', function(){ location.href = url; });
	teaser.select('a').each(function(b){
		b.observe('click', function (e) {
			window.location = this.href;
			e.stop();
		}.bindAsEventListener(b));
		b.observe('mouseover', function(e){ e.stop(); teaser.removeClassName('hover'); });
	});

	teaser.observe('mouseover', function(){ teaser.addClassName('hover'); });
	teaser.observe('mouseout', function(){ teaser.removeClassName('hover'); });
};


document.observe('dom:loaded', function(){
	/**
	 * To encapsulate errors we first define an array with all initiation functions
	 * and then we execute them seperately in a try catch syntax.
	 */
	[
		/*** initiate search field ***/
		function(){
			var searchfield = $$('#header .searchform .searchfield')[0];
			var changehandler = function(event){
				var focus = (event && event.type == 'focus' ? true : false);
				if (this.value == '' || this.value == this.defaultValue) {
					if (!focus) this.removeClassName('filled');
					this.value = (focus ? '' : this.defaultValue);
				}
				if (focus) this.addClassName('filled');
			}.bind(searchfield);

			searchfield.observe('focus', changehandler);
			searchfield.observe('blur', changehandler);

			changehandler({type:'focus'});
			changehandler();
		},


		/*** initiate title gallery ***/
		function(){
			var titlegallery = $('titlegallery'),
			    contents = titlegallery.select('.content'),
			    current,
			    nav = new Element('ul'),
			    navitems,
			    tweenings,
			    TweenDuration = 1000,
			    breakDuration = 4000,
			    goto,
			    intervalHandler,
			    interval,
			    stopInterval,
			    startInterval,
			    breakInterval,
			    a;

			if (contents.length <= 1) return;

		// define change handler
			goto = function(to, abortTweening) {
				tweenings = [];

				if (to == current || !contents[to]) return;

				for (a = 0; contents[a]; a++) {
					if (a == to) {
						contents[a].setStyle({zIndex:2,opacity:0});
						navitems[a].addClassName('active');
						tweenings.push([contents[a], {opacity:1}, {duration:TweenDuration}]);
					} else if (a == current) {
						contents[a].setStyle({zIndex:1});
						navitems[a].removeClassName('active');
					} else {
						contents[a].setStyle({zIndex:0});
						tweenings.push([contents[a], {opacity:0}, {duration:TweenDuration}]);
					}
				}

				current = to;

				if (abortTweening) {
					for (a = 0; tweenings[a]; a++) {
						tweenings[a][0].setStyle(tweenings[a][1]);
					}
				}
				else {
					Timeline.addTweenings(tweenings);
				}
			};

		// define interval handler
			intervalHandler = function(){
				if (breakInterval && interval) {
					clearInterval(interval);
					interval = null;
				} else {
					goto(contents[current + 1] ? current + 1 : 0);
				}
			}.bind(this);

		// define stopInterval handler
			stopInterval = function() {
				breakInterval = true;
			};

		// define startInterval handler
			startInterval = function() {
				breakInterval = false;

				if (!interval)
					interval = setInterval(intervalHandler, breakDuration + TweenDuration);
			};

		// initiate navigation
			contents.each(function(content, i) {
				var navitem = new Element('li').update(i + 1);
				navitem.observe('click', function(){
					goto(i);
				});
				navitem.observe('mousedown', function(e){
					e.stop();
				});
				nav.appendChild(navitem);
			});
			navitems = nav.select('li');
			nav.addClassName('nav');
			titlegallery.down('.container').appendChild(nav);

		// abort interval on mouseover
			contents.each(function(content, i) {
				content.observe('mouseover', stopInterval);
				content.observe('mouseout', startInterval);
			});
			nav.observe('mouseover', stopInterval);
			nav.observe('mouseout', startInterval);

		// abort interval if the focus is not on the document
			document.observe('blur', stopInterval);
			document.observe('focus', startInterval);

		// set first item as current
			goto(0, true);

		// start interval
			startInterval();
		},


		/*** initiate newsOverview ***/
		function(){
			var newsOverview = $$('.newsOverview'),
			    olderNewsPanel,
			    olderNewsButton;
			if (newsOverview.length == 0) return;

			/*newsOverview = newsOverview[newsOverview.length - 1];

			olderNewsPanel = new Element('div');
			olderNewsPanel.addClassName('col3');

			olderNewsButton = new Element('span').update('<span>Ältere News</span>');
			olderNewsButton.addClassName('button');

			olderNewsPanel.appendChild(olderNewsButton);

			if (newsOverview.nextSibling)
				newsOverview.parentNode.insertBefore(olderNewsPanel, newsOverview.nextSibling);
			else
				newsOverview.parentNode.appendChild(olderNewsPanel);*/
		},


		/*** initiate ensembleOverview mouseover ***/
		function(){
			var allLi = $$('.ensembleOverview li');

			allLi.each(function(li){
				var i = li.down('img'),
				    a = li.down('a'),
				    s = li.select('script')[0];

				if (!i || !a || !s) return;

				var data = (s.innerHTML),
				    out = i.src,
				    cache = new Image();

				if (!data || !out || !cache) return;

				eval('var over = '+data+'.hoverImage;');
				cache.src = over;

				if (!over) return;

				li.setStyle({cursor:'pointer'});

				li.observe('click', function(){ location.href = a.href; });
				li.observe('mouseover', function(){ li.addClassName('hover'); i.src = over; });
				li.observe('mouseout', function(){ li.removeClassName('hover'); i.src = out; });
			});
		},

		/*** initiate clickable teaser for feature "aktuell" ***/
		function(){
			$$('.feature.aktuell li').each(function(li){
				setClickableTeaser(li,li.down('a').href);
			});
		},

		/*** initiate clickable teaser for "play" ***/
		function(){
			$$('.play').each(function(play){
				setClickableTeaser(play, play.select('h3 a')[0].href);
			});
		},

		/*** initiate clickable teaser for news ***/
		function(){
			$$('.newsOverview > .col1').each(function(col){
				setClickableTeaser(col, col.select('.more')[0].href);
			});
		},

		/*** initiate clickable teaser ***/
		function(){
			$$('#content .teaser').each(function(col){
				if (col.select('.more')[0]) setClickableTeaser(col, col.select('.more')[0].href);
			});
		},

		/*** initiate tab-navigation ***/
		function(){
			$$('.tabnavigation').each(function(nav){
				var items = nav.select('a'),
				    tweenings = [],
				    tabclick;

				tabclick = function(event, noTweening){
					var a,
					    e = this.retrieve('e');

					tweenings = [];
					for (a = 0; items[a]; a++) {

						if (items[a] == this) {
							items[a].addClassName('active');
							tweenings.push([items[a].retrieve('e'),{opacity:1,zIndex:1}]);
						} else {
							items[a].removeClassName('active');
							tweenings.push([items[a].retrieve('e'),{opacity:0,zIndex:0}]);
						}
					}
					tweenings.push([e.parentNode,{height:this.retrieve('h')+'px'}]);

					if (noTweening)
						tweenings.each(function(t){
							if (!t[0].setStyle)
								Element.extend(t[0]);
							t[0].setStyle(t[1]);
						});
					else
						Timeline.addTweenings(tweenings);

					//if ((navigator.userAgent).search(/MSIE [78]\.0/) === -1) e.focus();
					e.setStyle({outline:0});

					if (event) event.stop();
				};

				items.each(function(a){
					var e = $((a.href).replace(/^[^\#]*\#/, ''));

					e.setStyle({position:'absolute',left:0,top:0});
					e.setAttribute('tabindex', '0');
					e.select('h2').each(function(h2){ h2.addClassName('jsNav'); });

					a.store('e', e);
					a.store('h', e.offsetHeight);
					a.observe('click', tabclick);
				});
				tabclick.bind(items[0])(null, true);
			});
		},

		/*** initiate mouseover zoom for feature bilder ***/
		function(){
			$$('.feature.bilder').each(function(featurebox){
				//featurebox.setStyle({position:'relative'});

				var div = new Element('div');
				div.setStyle({position:'relative',height:0,width:'100%'});
				var innerDiv = new Element('div');
				innerDiv.addClassName('bigImage');
				//div.update(innerDiv);

				featurebox.insertBefore(div, featurebox.down('.thumbnails'));

				(featurebox.select('a > img')).each(function(img){
					var a = img.parentNode;
					var bigimg = new Image();
					bigimg.src = a.href;

					if ((a.href).search(/\.(jpe?g|png|gif)$/)) {
						a.observe('mouseover', function(){ div.update(innerDiv); innerDiv.update(bigimg); });
						a.observe('mouseout', function(){ innerDiv.remove(); innerDiv.update(''); });
						a.observe('click', function(e){ e.stop(); });
					}
				});
			});
		},

		/*** initiate image zoom ***/
		function(){
			$$('a[href$=".jpg"] img,a[href$=".png"] img,a[href$=".gif"] img').each(function(i){
				var a = i.up('a');
				imagezoom(a);
			});
		},

		/*** initiate feature termine ***/
		function(){
			var itemsPerPage = 5;

			$$('.feature.termine > ul').each(function(ul){
				var li = ul.select(' > li'),
				    currentPage = 0,
				    minPage = 1,
				    maxPage = Math.ceil(li.length / itemsPerPage),
				    pageWidth = ul.offsetWidth,
				    pageHeight = 0,
				    top,
				    tweenings,
				    oldItemsIndex,
				    newItemsIndex,
				    go,
				    pageNav,
				    prev,
				    next,
				    a;

				if (li.length <= itemsPerPage) return;

				ul.setStyle({overflow:'hidden',position:'relative'});

			// define page navigation handler
				go = function(change, noTweening){
					var to = currentPage + change;
					if (to < minPage || to > maxPage) return;

					tweenings = [];
					pageHeight = 0;

					oldItemsIndex = currentPage * itemsPerPage - itemsPerPage;
					newItemsIndex = to * itemsPerPage - itemsPerPage;

					li.each(function(l,i){
						// old items
						if (i >= oldItemsIndex && i < oldItemsIndex + itemsPerPage) {
							tweenings.push([l,{left:(change > 0 ? '-' : '') + pageWidth + 'px'}]);
						}
						// new items
						else if (i >= newItemsIndex && i < newItemsIndex + itemsPerPage) {
							l.setStyle({left:(change > 0 ? '' : '-') + pageWidth + 'px'});
							tweenings.push([l,{left:'0px'}]);
							pageHeight += l.offsetHeight;
						}
						// others
						else {
							l.setStyle({left:pageWidth + 'px'});
						}
					});
					tweenings.push([ul,{height:pageHeight+'px'}]);

					if (to <= minPage) prev.addClassName('disabled'); else prev.removeClassName('disabled');
					if (to >= maxPage) next.addClassName('disabled'); else next.removeClassName('disabled');

					if (noTweening)
						tweenings.each(function(t){ t[0].setStyle(t[1]); });
					else
						Timeline.addTweenings(tweenings);

					currentPage = to;
				};

			// create page navigation buttons
				pageNav = new Element('div');
				pageNav.addClassName('pageNav');
				prev = new Element('a',{href:'javascript:;'}).update('zurück');
				next = new Element('a',{href:'javascript:;'}).update('vorwärts');
				prev.addClassName('arrowbutton prev icon disabled');
				next.addClassName('arrowbutton next icon disabled');
				pageNav.appendChild(prev);
				pageNav.appendChild(next);

			// insert page navigation buttons
				if (ul.nextSibling)
					ul.parentNode.insertBefore(pageNav, ul.nextSibling);
				else
					ul.parentNode.appendChild(pageNav);

				for (a = 0; li[a]; a++) {
					if (a % itemsPerPage == 0) top = 0;
					li[a].setStyle({position:'absolute',top:top+'px'});
					top += li[a].offsetHeight;
				}

			// reset page status
				prev.observe('click', function(){ go(-1); });
				next.observe('click', function(){ go(1); });
				go(1, true);
			});
		},

		/*** make black footer endless ***/
		function(){
			$$('body')[0].setStyle({background:'#000'});
		}

	].each(function(f){
		try {
			f();
		} catch(e) {
			console.error(e);
		}
	});
});


jQuery(document).ready(function($) {
	replaceVideos();
	$('.ajax').live('click',function(e) {
		var a = $(this);
		var href = a.attr('href');
		a.replaceWith('Wird geladen ...');
		$('.colContainer3:first').load(href+' .colContainer3:first',function() {
			replaceVideos();
		});
		e.preventDefault();
	});
	$('a.top').click(function(e) {
		$(document).scrollTop(0);
		e.preventDefault();
	});
	$('a.external').click(function(e) {
		$(this).attr("target","_blank");
	});
	$('.gallery').each(function() {
		var gallery = $(this);
		var pics = gallery.find('.pics');
		var prev = gallery.find('.prev');
		var next = gallery.find('.next');
		pics.cycle({
			fx: 'fade',
			speed: '400',
			prev: prev,
			next: next
		});
	});
	labelit();
	$('.newsletter').click(function(e) {
		e.preventDefault();
		if($('.nl_subscription').is(':hidden')) {
			$('.nl_subscription').slideDown('fast');
		}
		else {
			$('.nl_subscription').slideUp('fast');
		}
	});
	$('.nl_subscription').submit(function(e) {
		var form = $(this);
		var anrede = form.find('input[name=anrede]').filter(':checked').length;
		var vorname = form.find('input[name=vorname]').val();
		var nachname = form.find('input[name=nachname]').val();
		var email = form.find('input[name=email]').val();

		if(!anrede) {
			alert('Sie müssen eine Anrede auswählen!');
			e.preventDefault();
			return;
		}
		if(!checkMail(email)) {
			alert('Sie müssen eine gültige Email eintragen!');
			e.preventDefault();
			return;
		}
		if(nachname=='' || nachname=='Nachname') {
			alert('Sie müssen einen Nachnamen eintragen!');
			e.preventDefault();
			return;
		}
		if(vorname=='' || vorname=='Vorname') {
			alert('Sie müssen einen Vornamen eintragen!');
			e.preventDefault();
			return;
		}

	});
	if(window.location.href.indexOf('nl_success=1')!=-1) {
		var nl_subscription = $('.nl_subscription');
		var newsletter = $('.newsletter');
		nl_subscription.empty().html('<p><strong>Vielen Dank für die Anmeldung zum Newsletter.</strong></p>');
		newsletter.click();
	}
	if(window.location.href.indexOf('control=1')!=-1) {
		if($('.abo_form').length)
			$(document).scrollTop($('.abo_form').offset().top);
		if($('.form').length)
			$(document).scrollTop($('.form').offset().top);
	}
	if($('.abo_form').length) {
		if($('.abo_form').find('input[name=bezahlung]').filter(':checked').length==0) {
			$('.abo_form').find('input[name=bezahlung]').filter(':first').attr("checked","checked");
		}
	}
});

function replaceVideos() {
	var $ = jQuery;
	$('.video-embed').each(function() {
		var video = $(this);
		var width = parseInt(video.css('width'));
		var height = parseInt(video.css('height'));
		var file = video.text();
		video.flash({
			src: '/typo3conf/ext/tdj/res/swf/player.swf',
			width: width,
			height: height,
			wmode: 'transparent',
			allowFullScreen : true,
			flashvars : {
				file : '/'+file,
				stretching : 'fill'
			}
		});
		video.find(".alt").remove();
	});
}

function labelit() {
	var $ = jQuery;
	$('.labelit').each(function(){
		var label = $(this);
		var span = label.find('span:first');
		var input = label.find('input:first');
		var label_text = span.text();
		var input_text = input.val();
		span.hide();
		if(input_text=='') {
			input.val(label_text);
		}
		input.unbind('blur').blur(function() {
			var label_text = span.text();
			var input_text = input.val();
			if(input_text=='') {
				input.val(label_text);
			}
		});
		input.unbind('focus').focus(function() {
			var label_text = span.text();
			var input_text = input.val();
			if(input_text==label_text) {
				input.val('');
			}
		});
	});
}

function checkMail(mail) {
	return mail.search("@") != -1 && mail.substring(mail.search("@"), mail.length).indexOf('.') != -1;
}

