$(document).ready(function() {

	// Replacing the first nav-level with a nice font
	Cufon.replace('ul#navMain>li>a',{textShadow:'#666 1px 1px',hover:true});
	
	Cufon.replace('ul#navBaby>li>a, ul#navBabySub>li>a, .mediathek h1, .mediathek .item h2',{hover:true});
	
	// Getting the crazy main-navigation to work
	$('ul#navMain').navMain();

	// Sliding images and teaser-navigation for home
	$('div.home').masterSlider();

	// Expandable teaser on home
	$('div.home #teaser').hover(function() {
		$(this).animate({top: '-105px', height: '195px'}, 'normal');
	},function() {
		$(this).animate({top: '0px', height: '71'}, 'normal');
	});

	// Sliding images and teaser-navigation for productOverview
	// Added hook-function to change the infoboxes
	// Added scrollableApi for auto & continuous
	$('div.productOverview').masterSlider({hook:$.fn.productOverviewInfoBox,auto:false,continuous:false,navScrollable:true,directNav:false});

	// Merkzettel (userfunctions_mf.js)
	Welle.Merkzettel.init();

	// Testing slider for productDetails
	$('div.productDetails').masterSlider({hook:$.fn.productDetailsCaption,auto:false,continuous:false,navScrollable:true,directNav:false});

	// Slider-Bar for productDetails
	/* BEN: The slider goes out again...
	$('div.productDetails div.slider').slider({
		animate: true,
		change: function(e,ui) {
			$.log(ui.value);
			// BEN: One item is 90px wide, visible items are 4, ui.value represents percentage...
			var t = -1*Math.ceil(($('ul#navImageArray li').length*90-360)/100*ui.value);
			t=t>0?t=0:t;
			//var max = -1*($('ul#navImageArray li').length-4)*90
			//if(t<max){t=max;}
			$('ul#navImageArray').animate({
				left: t
			},{ queue:false, duration:900, easing:'easeInOutQuint' });
		},
		max: 100
	});
	/* :NEB */

	// Testing hover for productDetails, finishes
	$('div.productDetails .finishes a').hover(function() {
		$(this).parent().find('.hover').fadeIn(150);
	},function() {
		$(this).parent().find('.hover').fadeOut(150);
	});


	// Layer&Hotspots for productOverview
	$('div.productOverview ul#imageArray>li').each(function(){
		var masterObj = $(this);
		// TEMP :-)

		// Prepare layers
		$('div.hsContent',masterObj).each(function() {
			var spaceW = 970;
			var mediaW = $(this).find('.media').css('width');
			var mediaH = $(this).find('.media').css('height');
			//$.log(mediaW);

			//Fix for strange IE7 behaviour </michi>
			if(mediaW == 'auto') return true;

			var left;
			var file = $(this).find('a.file').attr('href');
			if($(this).find('div.media').hasClass('isFlash')){
				//$.log('isFlash!');
				//$.log(file);

				$(this).find('div.media').flvPlayer(file,{width:parseInt(mediaW),height:parseInt(mediaH)});
			}
			if (mediaW>mediaH) {
				$(this).css('width',mediaW);
				$(this).css('height','auto');
				$(this).find('.media').css('marginBottom','10px');
				left = (spaceW/2)-(parseInt(mediaW)/2)-10;
				left = left+'px';
				//$.log(left);
				$(this).css('left',left);
			} else {
				$(this).find('.media').css('float','left');
				$(this).find('.media').css('marginRight','10px');
				$(this).find('.media').css('marginBottom','0');
				$(this).css('width',(parseInt(mediaW)*2+'px'));
				left = (spaceW/2)-(parseInt(mediaW))-10;
				left = left+'px';
				//$.log(left);
				$(this).css('left',left);
			}
			$(this).css('top',85);
			$(this).css('zIndex',5);
			$(this).find('a').click(function(){
				$(this).parent().fadeOut(600);
			});
		});

		$('a.hotspot',masterObj).each(function(i) {
			// BEN: This depends on custom function (which was extended)
			// THIS MUST ONLY BE CALLED FROM SLIDER. RIGHT NOW ALL HS FROM ALL LIS ARE PULASATING -> AMOK
			//$(this).pulse({speed:1800,times:99,from:0.4,to:1});
			$(this).click(function(e) {
				//$.log('hotspot clicked: '+i);
				$('div.hsContent',masterObj).each(function(j) {
					//$.log(i+':'+j);
					if(i==j) {
						//$.log('hotspot: '+i);
						//$.log('dialog: '+j);
						//$(this).dialog('open');
						$(this).fadeIn(600);
						//$.log('dialog'+i+' opened');
					} else {
						$(this).fadeOut(600);
					}
				});
			});
		});
	});

	// TEMP: Everything for history
	$('div.history #intro').click(function(){
		$(this).fadeOut(900);
	});
	$('div.history .scrollPane').jScrollPane({scrollbarWidth:8,scrollbarMargin:60,showArrows:true});
	$('div.history').historySlider({auto:false});
	$('div.history a.colorbox').colorbox();
	Cufon.replace('div.history h1');
	Cufon.replace('div.history .text h3');

	// TEMP: Everything for finishes
	$('div#finishes .scrollPane').jScrollPane({scrollbarWidth:8,scrollbarMargin:20,showArrows:true});
	Cufon.replace('div#finishes h1');


	/* BEN: Manipulating contact-form */
	$('form#contact select#youare').bind('focus change',function() {
		//$.log($(this).val());
		if($(this).val()=='Händler'){
			$('form#contact select#reason option').each(function(){
				$(this).removeAttr('disabled');
				$(this).removeAttr('style');
				//$.log($(this).text());
				if($(this).text()=='Anfrage an die Personalabteilung'){
					$(this).attr('disabled','disabled');
					$(this).css('display','none');
				}
			});
		} else {
			$('form#contact select#reason option').each(function(){
				$(this).removeAttr('disabled');
				$(this).removeAttr('style');
				//$.log($(this).text());
				if($(this).text()=='Anforderung von Prospekten' || $(this).text()=='Wie werde ich Händler?' || $(this).text()=='Anfrage zum Seminarangebot'){
					$(this).attr('disabled','disabled');
					$(this).css('display','none');
				}
			});
		}
	});
});



// BEN: Helpful wrapper for logging, prevents IEs from throwing errors
jQuery.log = function(s) {
	if(window.console) {
		/* BEN: Disable logging */
		//console.log(s);
	} else {
		// Only if really needed. It's quite annoying without a console...
		//alert(s);
	}
};

(function($) {
	/* BEN: Global vars and objects */
	// Preparing the overlay for navMain & merkzettel
	var overlay = '<div class="overlay"></div>';
	$('div#contentArea').prepend(overlay);
	$('div.overlay').height($('div#contentArea').height());
	$('div.overlay').css('opacity','0');

	/* BEN: wait() */
	// Helper function for navMain() at least...
	$.fn.wait = function(time, type) {
		time = time || 0;
		type = type || 'fx';
		return this.queue(type, function() {
			var self = this;
			setTimeout(function() {
				$(self).dequeue();
			}, time);
		});
	};



	/* BEN: productOverviewInfoBox() */
	// Additional functionality for productOverview
	$.fn.productOverviewInfoBox = function(item,speed) {
		$('ul#imageArray>li').each(function(i){
			if(!isIE6()) {
				if(item==i){
					$(this).find('a.hotspot').pulse({speed:750,times:9,from:0.4,to:1.0});
				}
			}
		});
		//$.log('productOverviewInfoBox('+item+','+speed+')');
		$('div.productOverview #infobox .item').each(function(j){
			if(item==j) {
				$(this).wait(speed/2).fadeIn(speed);
			} else {
				$(this).fadeOut(speed/2);
			}
		});
	};


	/* BEN: productDetailsCaption() */
	// Additional functionality for productDetails
	$.fn.productDetailsCaption = function(item,speed) {
		//$.log('productDetailsCaption('+item+','+speed+')');
		$('div.productDetails .typesContainer p.imgCaption').each(function(j){
			count = j+1;
			$(this).addClass('item'+count);
			if(item==j) {
				$(this).wait(speed/2).fadeIn(speed);
			} else {
				$(this).fadeOut(speed/2);
			}
		});
	};


	/* BEN: pulse() */
	// Extended core-functionality for pulsating hotspots as i like it
	// Note that IE <= 8 is buggy on changing the opacity of an element containing a semi-transparent
	// png. You'll have dark "borders" around your pngs then...
	$.fn.pulse = function (options){
		var defaults = {
			speed: 'fast',
			times: 5,
			from:0.1,
			to:1
		}
		var options = $.extend(defaults, options);
		for (i = 0; i < options.times; ++i){
			this.animate({opacity: options.from}, options.speed).animate({opacity: options.to}, options.speed);
		}
		return this;
	};



	/* BEN: navMain() */
	// Everything in here is VERY dependent of the existing HTML-structure and the corresponding CSS. Be careful!
	$.fn.navMain = function(options){
		// These are the default configuration properties
		// Can be overridden by options
		var defaults = {
			speed: 450,
			// Depends on plugin 'jquery.animation.easing.js'
			//easing1: 'elasticEaseOut',
			easing1: 'easeOutQuint',
			easing2: 'easeInQuint',
			easing3: 'easeInOutQuint',
			//easing4: 'elasticEaseIn'
			easing4: 'easeInQuint'
		};
		var options = $.extend(defaults, options);
		var masterObj = $(this);
		var timeout = 0;
		var s = options.speed;
		var e1 = options.easing1;
		var e2 = options.easing2;
		var e3 = options.easing3;
		var e4 = options.easing4;
		var uiReady = true;

		// BEN: Initialize!
		init();

		function closeAnyOpenLevel(){
			//$.log('closeAnyOpenLevel()');
			// If any list-item with class="act" is present sth. is opened and we have to close it
			var subOpen = masterObj.find('ul.l2>li.act>ul.l3:visible').length!=0 ? true:false;
			//$.log('subOpen&visible: '+subOpen);
			var imgOpen = masterObj.find('ul.l2>li.act>img:visible').length!=0 ? true:false;
			//$.log('imgOpen&visible: '+imgOpen);

			if (subOpen && imgOpen) {
				//$.log('closing complex level');
				masterObj.find('ul.l2>li.act>ul.l3').animate({width:'toggle'},s,e3);
				masterObj.find('ul.l2>li.act>img').wait(s).animate({height:'toggle'},s,e4,function(){$(this).parent().removeClass('act');});
				// Setting the timeout for opening a new level. This can only happen after closing is done.
				timeout = s*2;
			} else if (subOpen && !imgOpen) {
				//$.log('closing weirdo level');
				masterObj.find('ul.l2>li.act>ul.l3').animate({width:'toggle'},s,e3,function(){$(this).parent().removeClass('act');});
				// Setting the timeout for opening a new level. This can only happen after closing is done.
				timeout = s;
			} else if (!subOpen && imgOpen) {
				//$.log('closing normal level');
				masterObj.find('ul.l2>li.act>img').wait(s).animate({height:'toggle'},s,e4,function(){$(this).parent().removeClass('act');});
				// Setting the timeout for opening a new level. This can only happen after closing is done.
				timeout = s;
			} else {
				//$.log('closing simple || invisible level');
				masterObj.find('ul.l2>li.act>ul.l3').hide();
				masterObj.find('ul.l2>li.act>img').hide();
				masterObj.find('ul.l2>li.act').removeClass('act');
				timeout = 0;
			}
		};

		function openLevel(trigger,timeout,type,load){
			//$.log('openLevel('+trigger.text()+','+timeout+','+type+')');
			trigger.addClass('act');
			var t = timeout;
			//$.log(t);
			var href = trigger.find('>a').attr('href');
			href = '/'+href;
			//$.log(href);
			switch (type) {
				case 'simple':
					uiReady = true;
					if(load){location.href = href;}
					break;
				case 'normal':
					trigger.find('>img').wait(t).animate({height:'toggle'},s,e1,function(){
						uiReady = true;
						if(load){location.href = href;}
					});
					break;
				case 'complex':
					trigger.find('>img').wait(t).animate({height:'toggle'},s,e1);
					trigger.find('>ul.l3').wait(t+s).animate({width:'toggle'},s,e2,function(){uiReady = true;});
					break;
				default:
					uiReady = true;
					if(load){location.href = href;}
					break;
			}
		};

		// Initialize
		function init(){
			//$.log('navMain()->init()');
			// BEN: Ported from suckerfish
			if ($.browser.msie && $.browser.version*1 < 7) {
				masterObj.find('li').hover(function() {
					$(this).addClass('over');
				},function() {
					$(this).removeClass('over');
				});
			}
			// Attach click event to first level (only preventing default)
			$('>li>a',masterObj).each(function(){
				$(this).click(function(e) {
					e.preventDefault();
				});
			});

			// Controlling the overlay
			$('>li',masterObj).each(function(){
				$(this).hover(function() {
					// Hide selects for bloody IE. Otherwise menu doesn't overlay them
					if($.browser.msie){$('select').addClass('hidden');}

					// Only blend in the overlay if we do see an open third level
					// IEs don't understand selector ":visible"...
					// var showOverlay = $(this).find('ul.l2>li.act>ul.l3:visible').length!=0 ? true:false;
					var showOverlay = $(this).find('ul.l2>li.act>ul.l3').length!=0 ? true:false;
					if(showOverlay) {
						$('div.overlay').stop().show().animate({opacity:'0.6'},s);
					}
				},function() {
					// Show selects again for bloody IE. Otherwise menu doesn't overlay them
					if($.browser.msie){$('select').removeClass('hidden');}

					$('div.overlay').stop().show().animate({opacity:'0'},s,function(){
						$('div.overlay').hide();
					});
				});
			});

			// Attach click event to all links of second level
			$('ul.l2>li>a',masterObj).each(function(){
				// The element for controlling the third level is actually the list-item
				var trigger = $(this).parent();
				// Is there a third level?
				var hasSub = trigger.find('>ul.l3').length!=0 ? true:false;
				// Is there an image?
				var hasImage = trigger.find('>img').length!=0 ? true:false;
				// Determine the complexity of each item
				if(hasImage && hasSub){$(this).attr('rel','complex');}
				if(hasImage && !hasSub){$(this).attr('rel','normal');}
				if(!hasImage && !hasSub){$(this).attr('rel','simple');}
				// Attach click
				$(this).click(function(e) {
					e.preventDefault();
					//$.log('my parent <li> is: '+$(this).attr('rel'));
					// Already open?
					var isOpen = trigger.hasClass('act') ? true:false;
					//$.log('isOpen: '+isOpen);

					// Introduce the overlay on first click and if there's a third level
					if(hasSub){
						$('div.overlay').show().animate({opacity:'0.6'},s);
					}
					// If there's nothing already opened and we are ready for another click...
					if(!isOpen && uiReady){
						// Blocking further user interaction
						uiReady = false;
						closeAnyOpenLevel();
						// We need to pass the actual list-item, the timeout (which is possibly altered in closeAnyOpenLevel()), the complexity (for calculating the delays) and if we should load the location.href
						openLevel(trigger,timeout,$(this).attr('rel'),true);
					// Simple & normal levels follow their links even if they're already opened
					} else if (isOpen && $(this).attr('rel')!='complex') {
						location.href = '/'+$(this).attr('href');
					}
				});
			});

			// Attach click event to the whole list-item of level3 to function as the link itself
			$('ul.l3 li',masterObj).click(function() {
				var href = $(this).find('>a').attr('href');
				href = '/'+href;
				//$.log(href);
				location.href = href;
			});

			// Setting the height of all level2-lists to fill whole height
			$('ul.l2',masterObj).each(function(){
				$(this).height($('div#contentArea').height()-masterObj.height());
			});

			// Setting the height of all level3-lists to a fitting height depending on number of li's in them
			$('ul.l3',masterObj).each(function(){
				// Count the rows (five items per row)
				var countRows = Math.ceil(($(this).find('li').length)/5);
				//$.log('countRows: '+countRows);
				// One item is 106px high (a:20px+img:83px+padding-bottom:2px+margin-bottom:1px)
				var space = 106*countRows;
				//$.log('space: '+space);
				$(this).height(space);
			});

			// If the user has already interacted with navMain we need to reflect the actual page
			// If any list-item with class="act" is present sth. has to be opened initially
			var anyAct = masterObj.find('ul.l2>li.act').length!=0 ? true:false;
			if (anyAct) {
				//$.log ('there is sth. active already');
				var origin = masterObj.find('ul.l2>li.act');
				openLevel(origin,timeout,origin.find('a').attr('rel'),false);
			}
		};
	};



	/* BEN: masterSlider */
	// Everything in here is VERY dependent of the existing HTML-structure and the corresponding CSS. Be careful!
	// The default options are set for home
	$.fn.masterSlider = function(options){
		// These are the default configuration properties
		// Can be overridden by options
		var defaults = {
			hook: function(){},
			speed: 900,
			auto: true,
			pause: 3600,
			continuous: true,
			// Depends on plugin 'scollable' (tools) and needs a div.scrollable around ul#navImageArray
			// BEN: Could be created on the fly but then overflow:hidden works at document.ready only -> does not look good!
			navScrollable: false,
			// How many *visible* nav-items are there?
			visNavItems: 4,
			// Do we want the big prev/next-arrows on the image?
			directNav: true,
			// Depends on plugin 'jquery.animation.easing.js'
			easing:	'easeInOutQuint'
		};
		var options = $.extend(defaults, options);
		// BEN: Do this for every element this function is called upon
		// Right now not needed but who knows?
		this.each(function() {
			var masterObj = $(this);
			// Scrollable nav (needs div.scrollable around ul#navImageArray obviously)
			var scrollableApi;
			if (options.navScrollable || true) {
				scrollableApi = $('div.scrollable').scrollable({
					// Define settings for jQuery.tools.scrollable
					size: options.visNavItems,
					easing: options.easing,
					speed: options.speed,
					api:true
				});
			}
			var s = $('ul#imageArray>li', masterObj).length;
			var w = $('ul#imageArray>li', masterObj).width();
			var uiReady = true;
			var ts = s-1;
			var t = 0;
			var timeout;
			$('ul#imageArray', masterObj).css('width',s*w);
			// Create duplicates of imageArray-items for seamless animation
			if(options.continuous){
				$('ul#imageArray', masterObj).prepend($('ul#imageArray li:last-child', masterObj).clone().css('margin-left','-'+ w +'px'));
				$('ul#imageArray', masterObj).append($('ul#imageArray li:nth-child(2)', masterObj).clone());
				$('ul#imageArray', masterObj).css('width',(s+1)*w);
			};

			// BEN: Initialize!
			init();

			function setCurrent(t){
				//$.log('current slide: '+t);
				t = parseInt(t);
				// Set act-status to actual slide in thumbnail-navigation
				$('ul#navImageArray>li', masterObj).each(function(i){
					if(i==t){
						$(this).find('div.act').fadeIn(options.speed);
					} else {
						$(this).find('div.act').fadeOut(options.speed/2);
					}
				});
			};

			function adjust(){
				if(t>ts) t=0;
				if(t<0) t=ts;
				$('ul#imageArray',masterObj).css('margin-left',(t*w*-1));
				// After this func has been processed we are ready for new user-input
				uiReady = true;
				// BEN: This was moved to slide() to avoid delay
				// setCurrent(t);
			};

			var slide = function (dir,clicked){
				if (uiReady){
					uiReady = false;
					var ot = t;
					switch(dir){
						case 'next':
							t = (ot>=ts) ? (options.continuous ? t+1 : ts) : t+1;
							break;
						case 'prev':
							t = (t<=0) ? (options.continuous ? t-1 : 0) : t-1;
							break;
						case 'first':
							t = 0;
							break;
						case 'last':
							t = ts;
							break;
						default:
							t = dir;
							break;
					};
					var diff = Math.abs(ot-t);
					// BEN: Same absolute speed regardless of distance
					// var s = diff*options.speed;
					var s = options.speed;
					// Where to go
					p = (t*w*-1);
					$('ul#imageArray',masterObj).animate(
						{ marginLeft: p },
						{ queue:false, duration:s, easing:options.easing, complete:adjust }
					);
					if(t>ts) t=0;
					if(t<0) t=ts;
					setCurrent(t);
					// Calling the optional hook-function with actual item and configured speed
					options.hook(t,options.speed);
					// User clicked on any nav-item
					if(clicked) {
						clearTimeout(timeout);
						//$.log('user interruption');
					}
					// Automatic start, no interruption
					if(options.auto && dir=='next' && !clicked){
						//$.log('nothing clicked, autoslide to next item');
						timeout = setTimeout(function(){
							//slide('next',false);
							slide.call(this,'next',false);
							// Update navScrollable if present (needs the scripting API of scrollable
							if(typeof scrollableApi != 'undefined') {
								scrollableApi.click(t);
							}
						},diff*s+options.pause);
					}
				// Current animation has not finished yet
				} else {
					//$.log('ui is not ready yet');
				}
			}

			// Initialize
			function init(){
				// Attach hover and click events to our thumbnail-navigation
				$('ul#navImageArray>li', masterObj).each(function(i){
					$(this).click(function(){
						//$.log('ul#navImageArray>li'+i+':click');
						slide(i,true);
					});
					$(this).hover(function(){
						//$.log('ul#navImageArray>li'+i+':hover:in');
						$(this).find('div.hover').fadeIn(options.speed/5);
					},function() {
						//$.log('ul#navImageArray>li'+i+':hover:out');
						$(this).find('div.hover').fadeOut(options.speed/10);
					});

				});
				// Create left/right-arrows and attach click event to them
				if (options.directNav) {
					$('ul#imageArray').before('<a id="prev"></a>');
					$('a#prev', masterObj).click(function(){
						slide('prev',true);
						//$.log('a#prev:click');
					});
					$('ul#imageArray').after('<a id="next"></a>');
					$('a#next', masterObj).click(function(e){
						slide('next',true);
						//$.log('a#next:click');
					});
				}
				// We need to know where we are right from the start
				setCurrent(0);
				// Calling the optional hook-function with startitem instantly
				options.hook(0,0);
				// If slides should start automatically
				if(options.auto){
					//$.log('autostart, autoslide to next item');
					//$.log(scrollableApi);
					timeout = setTimeout(function(){
						//slide('next',false);
						slide.call(this,'next',false);
					},options.pause);
				}
				// BEN: Testing specific start item. For testing EXT:page_php_content needs to be included BEFORE static template (produktuebersicht.htm)
				// Would work!
				/*
				if (milieuId != null) {
					$.log(milieuId);
					slide(milieuId,false);
					setCurrent(milieuId);
				}
				*/
			};
		});
	};

	/* BEN: historySlider */
	// Everything in here is VERY dependent of the existing HTML-structure and the corresponding CSS. Be careful!
	// The default options are set for home
	$.fn.historySlider = function(options){
		// These are the default configuration properties
		// Can be overridden by options
		var defaults = {
			hook: function(){},
			speed: 900,
			auto: true,
			pause: 3600,
			continuous: false,
			// Depends on plugin 'scollable' (tools) and needs a div.scrollable around ul#navItemArray
			// BEN: Could be created on the fly but then overflow:hidden works at document.ready only -> does not look good!
			navScrollable: true,
			// How many *visible* nav-items are there?
			visNavItems: 5,
			// Do we want the big prev/next-arrows on the image?
			directNav: false,
			// Depends on plugin 'jquery.animation.easing.js'
			easing:	'easeInOutQuint'
		};
		var options = $.extend(defaults, options);
		// BEN: Do this for every element this function is called upon
		// Right now not needed but who knows?
		this.each(function() {
			var masterObj = $(this);
			// Scrollable nav (needs div.scrollable around ul#navItemArray obviously)
			if (options.navScrollable) {
				var scrollableApi = $('div.scrollable', masterObj).scrollable({
					// Define settings for jQuery.tools.scrollable
					size: options.visNavItems,
					easing: options.easing,
					speed: options.speed,
					api: true,
					clickable: false,
					item: 'li:not(.chapter)'
				});
			}
			var chapterItems = new Array();
			var s = $('ul#itemArray>li', masterObj).length;
			var w = $('ul#itemArray>li', masterObj).width();
			var uiReady = true;
			var ts = s-1;
			var t = 0;
			var timeout;
			var currentOffset;
			var offsetToScroll;
			var lastValue = 0;

			$('ul#itemArray', masterObj).css('width',s*w);
			// Create duplicates of imageArray-items for seamless animation
			if(options.continuous){
				$('ul#itemArray', masterObj).prepend($('ul#itemArray li:last-child', masterObj).clone().css('margin-left','-'+ w +'px'));
				$('ul#itemArray', masterObj).append($('ul#itemArray li:nth-child(2)', masterObj).clone());
				$('ul#itemArray', masterObj).css('width',(s+1)*w);
			};

			// BEN: Initialize!
			init();

			function setCurrent(t){
				//$.log('current slide: '+t);
				t = parseInt(t);
				// Set act-status to actual slide in thumbnail-navigation
				$('ul#navItemArray>li:not(.chapter)', masterObj).each(function(i){
					if(i==t){
						$(this).find('div.act').fadeIn(options.speed);
					} else {
						$(this).find('div.act').fadeOut(options.speed/2);
					}
				});
			};

			function adjust(){
				if(t>ts) t=0;
				if(t<0) t=ts;
				$('ul#itemArray',masterObj).css('margin-left',(t*w*-1));
				$('ul#itemArray',masterObj).fadeIn(200);
				// After this func has been processed we are ready for new user-input
				uiReady = true;
				// BEN: This was moved to slide() to avoid delay
				// setCurrent(t);

				// BEN: Amok to find out new size for scrollable
				var offset = $('#navItemArray').css('left');
				offset = Math.abs(Math.ceil(parseInt(offset)));
				var firstVisible = offset/131;
				firstVisible = Math.ceil(firstVisible);
				firstVisible++;
				//$.log('offset: '+offset);
				//$.log('firstVisible: '+firstVisible);
				var size = 0;
				for (i=firstVisible;i<7+firstVisible;++i) {
					var z = $('#navItemArray li:nth-child('+i+'):not(.chapter)').length;
					//$.log(z);
					size += z;
					//size += $('#navItemArray li:nth-child('+i+'):not(.chapter)').length;

				}
				//$.log('size: '+size);
				scrollableApi.getConf().size = size;
				scrollableApi.reload();
				// :NEB
			};

			function slide (dir,clicked){
				if (uiReady){
					uiReady = false;
					var ot = t;
					switch(dir){
						case 'next':
							t = (ot>=ts) ? (options.continuous ? t+1 : ts) : t+1;
							break;
						case 'prev':
							t = (t<=0) ? (options.continuous ? t-1 : 0) : t-1;
							break;
						case 'first':
							t = 0;
							break;
						case 'last':
							t = ts;
							break;
						default:
							t = dir;
							break;
					};
					var diff = Math.abs(ot-t);
					// BEN: Same absolute speed regardless of distance
					// var s = diff*options.speed;
					var s = options.speed;
					// Where to go
					p = (t*w*-1);

					/*$('ul#itemArray',masterObj).animate(
						{ marginLeft: p },
						{ queue:false, duration:s, easing:options.easing, complete:adjust }
					);*/
					$('ul#itemArray',masterObj).fadeOut(200,adjust);
					if(t>ts) t=0;
					if(t<0) t=ts;
					setCurrent(t);
					// Calling the optional hook-function with actual item and configured speed
					options.hook(t,options.speed);
					// User clicked on any nav-item
					if(clicked) {
						clearTimeout(timeout);
						//$.log('user interruption');
					}
					// Automatic start, no interruption
					if(options.auto && dir=='next' && !clicked){
						//$.log('nothing clicked, autoslide to next item');
						timeout = setTimeout(function(){
							slide('next',false);
							// Update navScrollable if present (needs the scripting API of scrollable
							scrollableApi.click(t);
						},diff*s+options.pause);
					}
				// Current animation has not finished yet
				} else {
					//$.log('ui is not ready yet');
				}
			}

			function getOffsetToScrollTo(value) {
				var chapterSize = 100/(chapterItems.length-1);
				var sliderOffsetPercent = value/10;
				var sliderWidth = 808;
				var itemWidth = 131;

				var chapterToShow = Math.ceil(sliderOffsetPercent/chapterSize);
				chapterToShow = (chapterToShow == 0) ? 1 : chapterToShow;
				//$.log('chapterToShow: '+chapterToShow);
				var relativeValue = ((sliderOffsetPercent/chapterSize)-(chapterToShow-1))*100;
				//$.log('relativeValue: '+relativeValue);
				var relativeChapterSize = 100 / ((chapterItems[chapterToShow-1].length));
				//$.log('relativeChapterSize: '+relativeChapterSize);
				var itemToShow = Math.ceil(relativeValue/relativeChapterSize);
				itemToShow = (itemToShow == 0) ? 1 : itemToShow;
				//$.log('chapterToShow: '+chapterToShow+', itemToShow: '+itemToShow);
				//$.log('scrollToIndex: ' + chapterItems[chapterToShow-1][itemToShow-1].navIndex);
				var seekIndex = chapterItems[chapterToShow-1][itemToShow-1].navIndex;
				//scrollableApi.seekTo(seekIndex);
				//$.log(scrollableApi.getIndex());


				// Getting px-value
				var preChapters = 0;
				//$.log('preChapters: '+preChapters);
				// Wrong: Takin two times chapter 2 instead adding 1+2
				for (var i=0;i<chapterToShow-1;i++) {
					preChapters += chapterItems[(chapterToShow-2)-i].length*itemWidth;
					//$.log('preChapters('+i+'): '+preChapters);
				}
				//$.log('preChapters: '+preChapters);
				preChapters += (chapterToShow-1)*itemWidth;
				//$.log('preChapters: '+preChapters);
				var chapterOffset = ((relativeValue/100)*(chapterItems[chapterToShow-1].length+1)*itemWidth);


				//$.log('preChapters: '+preChapters);
				//$.log('chapterOffset: '+chapterOffset);
				
				offsetToScroll = Math.round(preChapters + chapterOffset);
				var listLength = ($('ul#navItemArray>li').length-7)*131;
				if( listLength < offsetToScroll ) {
					return listLength;
				}
				return offsetToScroll;
			}



			// Initialize
			function init(){

				var currentChapter = -1;
				var realIndex = 0;
				$('ul#navItemArray>li', masterObj).each(function(i){
					var $obj = $(this);
					if ($obj.hasClass('chapter')) {
						//$.log(currentChapter+','+i);
						currentChapter++;
					} else {
						if (typeof chapterItems[currentChapter]=='undefined'){
							chapterItems[currentChapter] = [];
						}
						chapterItems[currentChapter].push({
							navIndex: realIndex++,
							listIndex: i
						});
					}
				});
				$.log(chapterItems);

				$('div.slider', masterObj).slider({
					animate: true,
					change: function(e,ui) {
						$('ul#navItemArray',masterObj).animate({
							left: (-1)*getOffsetToScrollTo(ui.value)
						},{ queue:false, duration:options.speed, easing:options.easing });
					},
					slide: function(e,ui) {

						var offsetToGo = (-1)*getOffsetToScrollTo(ui.value);
						if(e.originalEvent.type == 'mousedown') {
							//return false;
							//$('ul#navItemArray',masterObj).animate({left: offsetToGo});
						} else {
							$('ul#navItemArray',masterObj).css('left',offsetToGo);
						}
						//console.log('slideEvent',e,ui);
					},
					//stop: function() {console.log('stopEvent')},
					max: 1000
				});

				// Attach hover and click events to our thumbnail-navigation
				$('ul#navItemArray>li:not(.chapter)', masterObj).each(function(i){
					$(this).click(function(){
										   
						// BEN: Hiding intro if still visisble				   
						$('#intro:visible').trigger('click');
						//$.log('ul#navItemArray>li'+i+':click');
						slide(i,true);
					});
					$(this).hover(function(){
						//$.log('ul#navItemArray>li'+i+':hover:in');
						$(this).find('div.hover').fadeIn(options.speed/5);
					},function() {
						//$.log('ul#navItemArray>li'+i+':hover:out');
						$(this).find('div.hover').fadeOut(options.speed/10);
					});

				});
				// Create left/right-arrows and attach click event to them
				if (options.directNav) {
					$('ul#itemArray').before('<a id="prev"></a>');
					$('a#prev', masterObj).click(function(){
						slide('prev',true);
						//$.log('a#prev:click');
					});
					$('ul#itemArray').after('<a id="next"></a>');
					$('a#next', masterObj).click(function(e){
						slide('next',true);
						//$.log('a#next:click');
					});
				}
				// We need to know where we are right from the start
				setCurrent(0);
				// Calling the optional hook-function with startitem instantly
				options.hook(0,0);
				// If slides should start automatically
				if(options.auto){
					//$.log('autostart, autoslide to next item');
					timeout = setTimeout(function(){
						slide('next',false);
					},options.pause);
				}



				var chapterCount = $('div.slider span', masterObj).length;
				//$.log(chapterCount);
				$('div.slider span', masterObj).each(function(i){
					var spanWidth = $(this).outerWidth({margin:true});
					//$.log(spanWidth);
					var spanMiddle = Math.ceil(spanWidth/2);
					$(this).css('left',(i*(808/(chapterCount-1)))-spanMiddle+'px');

					// BEN: Dirty hack for starting at 1970
					var seventies = $(this).text();
					if ($(this).text() == '1970er'){
						var startItem = getOffsetToScrollTo(500)/131;
						startItem = Math.round(startItem)-i;
						//$.log(startItem);
						$('div.slider', masterObj).slider('value', 500);
						slide(startItem,false);
					}
				});
			};
		});
	};
})(jQuery);
		
		
		
function printMerkzettel(){
	var baseUrl = window.location.host;
	var url = 'http://'+baseUrl+'/merkzettel.html?print=2';
	window.open(url,'Merkzettel','width=680,height=500,left=100,top=200,scrollbars=yes');
}
