/************************************************************************************
* Copyright Meisterbetrieb Tobias Wimmer
* Erstellt von Bernd Lutz Websolutions (http://berndlutz.com)
* Letzte Änderung: 03.10.2009
*************************************************************************************/



/* Slideshow Objekt
**********************/

var slideshow = {

	init: function(t, d)
	{
		slideshow.num = $$('#slideshow li').length;
		slideshow.i = 0;
		slideshow.fade_speed = d;
		slideshow.rotation_speed = t;
		slideshow.items = $$('#slideshow li');
		slideshow.zindex = 100;
		
		if ( slideshow.num > 1 )
		{
			slideshow.items.invoke('hide');
			slideshow.items[0].show();
			window.onload = function() { slideshow.items.invoke('show'); }
			slideshow.items[0].setStyle({zIndex: 100});
			window.setInterval('slideshow.next_image()', slideshow.rotation_speed*1000);
		}
		
	},
	
	next_image: function()
	{
		slideshow.zindex++;
		var current_img = slideshow.items[slideshow.i];
		slideshow.i++;
		if ( slideshow.i == slideshow.num ) slideshow.i = 0;
		var next_img = slideshow.items[slideshow.i];
		next_img.setOpacity(0);
		next_img.setStyle({zIndex: slideshow.zindex});
		next_img.visualEffect('Opacity', {
				duration: slideshow.fade_speed,
				from: 0,
				to: 1.0
			});
	}
};


/* Galerie
*************/


var gallery = {
	
	data: false,
	current: false,
	height: 0,
	allowNextContent: true,
	firstContent: true,
	diashow: false,
	
	init: function()
	{
		$$("#content a").each(function(elt)
		{
			if ( elt.readAttribute("href").match(/^[\w-]+$/) )
				elt.observe("click", gallery.load);
		});
		
		if ( document.viewport.getHeight() < 700 )
			this.maxImageHeight = document.viewport.getHeight() - 200;
		
		if ( this.maxImageHeight < 400 )
			this.maxImageHeight = 400;
	},
	
	
	// öffenen und schließen
	
	
	open: function()
	{
		$$('#gallery', '#gallery-layer').invoke('remove');
		
		var wrapper = $('wrapper');
		wrapper.insert({after: '<div id="gallery"><div id="gallery-content-active"><em>Lade Galerie</em></div><a href="#" id="gallery-close">schließen</a><div id="gallery-thumbnails"></div><div id="gallery-nav"><a href="#" id="gallery-previous">vorherige</a><a href="#" id="diashow" class="play">Start/Stopp</a><a href="#" id="gallery-next">nächste</a></div></div>'});

		gallery.elt = $('gallery');
		this.setDimensions();
		gallery.elt.setOpacity(0);
		gallery.elt.fade({ duration: 2, from: 0, to: 1});
		$("gallery-nav").setOpacity(0);
		wrapper.insert({after: '<div id="gallery-layer">&nbsp;</div>'});
		this.setLayerDimensions();
		$('gallery-layer').setOpacity(0);
		$("gallery-layer").fade({ duration: 1, from: 0, to: 0.5 });

		var thumbnailsBox = $("gallery-thumbnails");
		thumbnailsBox.setOpacity(0);
		for ( var i = 0; i < gallery.data.content.length; i++ )
		{
			if ( gallery.data.content[i].name.match(/\.(jpg|png|gif)$/i) )
				thumbnailsBox.insert({bottom: '<a href="'+gallery.data.url+'/'+gallery.data.content[i].name+'" rel="'+i+'"><img src="'+gallery.data.url+'/thumbnails/'+gallery.data.content[i].name+'" alt="'+gallery.data.content[i].title+'" /></a>'});
			else if ( gallery.data.content[i].name.match(/\.flv$/i) )
				thumbnailsBox.insert({bottom: '<a href="'+gallery.data.url+'/'+gallery.data.content[i].name+'" rel="'+i+'"><img src="/css/img/gallery_video_thumbnail.gif" alt="'+gallery.data.content[i].title+'" /></a>'});
		}

		gallery.setContent(0);
		
		$('gallery-close').observe('click', gallery.close);
		thumbnailsBox.select("a").invoke("observe", "click", gallery.selectContent);
		$("gallery-previous").observe("click", gallery.previousContent);
		$("gallery-next").observe("click", gallery.nextContent);
		
		$("diashow").observe("click", function(e)
		{
			Event.stop(e);
			
			if ( gallery.diashow == false )
				gallery.startDiashow();
			else
				gallery.stopDiashow();
		});
	},
	
	
	close: function(e)
	{
		gallery.stopDiashow();
		gallery.firstContent = gallery.allowNextContent = true;
		
		gallery.elt.fade({
			duration: 1,
			from: 1,
			to: 0
		});
		
		$("gallery-layer").fade({
			duration: 2,
			from: 0.5,
			to: 0,
			afterFinish: function()
			{
				$$('#gallery', '#gallery-layer').invoke('remove');
			}
		});
	},
	
	
	// Navigation
	
	
	selectContent: function(e)
	{
		Event.stop(e);
		
		var elt = Event.element(e).up('a');
		gallery.setContent(parseInt(elt.readAttribute('rel')));
	},
	
	nextContent: function(e)
	{
		Event.stop(e);
		
		if ( gallery.current + 1 < gallery.data.content.length )
			gallery.setContent(gallery.current + 1);
	},
	
	previousContent: function(e)
	{
		Event.stop(e);
		
		if ( gallery.current > 0 )
			gallery.setContent(gallery.current - 1);
	},
	
	
	setActiveThumbnail: function()
	{
		$$("#gallery-thumbnails a[rel]").invoke("hide");
		$$("#gallery-thumbnails a").invoke("removeClassName", "active");
		
		var d = 2;
		
		var thumbs = $$("#gallery-thumbnails a[rel]");
		var start = gallery.current >= thumbs.length - d ? gallery.current - 2*d + (thumbs.length - 1 - gallery.current) : gallery.current - d;
		var end = gallery.current < d ? gallery.current + d + (d - gallery.current) : gallery.current + d;
		
		start = start < 0 ? 0 : start;
		end = end > thumbs.length - 1 ? thumbs.length - 1 : end;
		
		for ( var i = start; i <= end; i++ )
		{
			thumbs[i].show();
			
			if ( thumbs[i].readAttribute("rel") == gallery.current )
				thumbs[i].addClassName("active");
		}
	},
	
	
	// Inhalt laden und anzeigen
	
	
	load: function(e)
	{
		Event.stop(e);
		
		new Ajax.Request("/ajax_gallery.php",
		{
			parameters: {
				url: Event.element(e).readAttribute("href")	
			},
			
			onComplete: function()
			{
				if ( gallery.data )
					gallery.open();
			}
		});
	},
	
	getHeight: function()
	{
		return $("gallery-content").getHeight() + 130;
	},
	
	setDimensions: function()
	{
		// max. 750x690
		
		var d = document.viewport.getDimensions();
		this.dimensions = {};
		
		for ( var i = 0; i <= 300; i++ )
		{
			if ( (d.width > (850 - i) && d.height > (690 - i)) || 850 - i <= 550 )
			{
				this.dimensions.width = 750 - i;
				this.dimensions.height = 690 - i;
				this.dimensions.contentWidth = this.dimensions.width - 50;
				this.dimensions.contentHeight = this.dimensions.height - 165;
				
				this.elt.setStyle({
					width: this.dimensions.width+"px",
					height: this.dimensions.height+"px",
					left: Math.round((d.width - gallery.dimensions.width)/2)+"px",
					top: Math.round((d.height - gallery.dimensions.height)/2)+"px",
					margin: 0
				});
				
				break;
			}
		}
	},
	
	setImageDimensions: function()
	{
		if ( $("gallery-content-loaded").match("embed") )
			return false;
		
		var d = $("gallery-content-loaded").getDimensions();
		d.ratio = Math.round(d.height/d.width*1000)/1000;
		
		// ratio <= 1 - crop a strip at the top and bottom
		
		if ( d.ratio <= 1 )
		{
			var height = Math.round(this.dimensions.contentWidth * d.ratio);
			
			$("gallery-content-loaded").setStyle({
				width: this.dimensions.contentWidth+"px",
				height: height+"px",
				top: (-1 * Math.round((height-this.dimensions.contentHeight)/2))+"px",
				left: 0
			});
		}
		
		// ratio > 1 - expand it as much as possible
		
		else
		{
			for ( var i = 0; i < 1000; i++ )
			{
				if ( this.dimensions.contentHeight >= d.height - i )
				{
					var height = d.height - i;
					var width = Math.round(height/d.ratio);
					
					$("gallery-content-loaded").setStyle({
						width: width+"px",
						height: height+"px",
						top: 0,
						left: Math.round((this.dimensions.contentWidth-width)/2)+"px"
					});
					
					break;
				}
			}
		}
	},
	
	
	
	setContent: function(i)
	{
		if ( gallery.allowNextContent == false )
			return false;
		gallery.allowNextContent = false;
		
		gallery.current = i;

		gallery.elt.insert({ bottom: '<div id="gallery-content" class="content"><span>'+gallery.data.content[i].title.escapeHTML()+'</span></div>' });
		$("gallery-content").setOpacity(0).hide();
		gallery.setActiveThumbnail();
		
		$("gallery-content").setStyle({
			width: this.dimensions.contentWidth+"px",
			height: this.dimensions.contentHeight+"px"
		});

		if ( gallery.data.content[i].name.match(/\.(jpg|png|gif)$/i) )
		{
			$("gallery-content").insert({ top: '<img src="'+gallery.data.url+'/'+gallery.data.content[i].name+'" alt="..." id="gallery-content-loaded" />' });
			$("gallery-content-loaded").observe("load", gallery.animateContentView);
		}
		else if ( gallery.data.content[i].name.match(/\.flv$/i) )
		{
			$("gallery-content").insert({ top: '<embed id="gallery-content-loaded" width="320" height="240" flashvars="width=320&height=240&showdigits=false&searchbar=false&file='+gallery.data.url+'/'+gallery.data.content[i].name+'" allowfullscreen="true" quality="high" src="/player.swf" type="application/x-shockwave-flash"/>' });
			gallery.animateContentView();
		}
	},
	
	animateContentView: function(e)
	{
		$("gallery-content").show();
		
		gallery.setImageDimensions();
		gallery.setLayerDimensions();
		
		$("gallery-content-active").fade({
			duration: 0.5,
			from: 1,
			to: 0,
			afterFinish: function(elt)
			{
				$("gallery-content-active").remove();
		
				$("gallery-content").fade({
					duration: 1.5,
					from: 0,
					to: 1,
					afterFinish: function(elt)
					{
						$("gallery-content").writeAttribute("id", "gallery-content-active");
						$("gallery-content-loaded").removeAttribute("id");
						gallery.allowNextContent = true;
						
						if ( gallery.firstContent == true )
						{
							$("gallery-thumbnails").fade({ duration: 1, from: 0, to: 1 });
							$("gallery-nav").fade({ duration: 1, from: 0, to: 1 });
							gallery.firstContent = false;
						}
					}
				});
			}
		});
	},
	
	setLayerDimensions: function(e)
	{
		var max = gallery.elt.viewportOffset().top + gallery.elt.getHeight();

		var height = document.body.scrollHeight;
		height = height < max ? max : height;
		height = height < document.viewport.getHeight() ? document.viewport.getHeight() : height;

		$("gallery-layer").setStyle({
			width: document.viewport.getWidth()+"px",
			height: height+"px"
		});
	},
	
	
	// diashow
	
	
	startDiashow: function()
	{
		gallery.nextDiashowContent();
		gallery.diashow = window.setInterval("gallery.nextDiashowContent();", 7000);
		$("diashow").writeAttribute("class", "pause");
	},
	
	stopDiashow: function()
	{
		if ( gallery.diashow )
			window.clearInterval(gallery.diashow);
		
		gallery.diashow = false;
		$("diashow").writeAttribute("class", "play");
	},
	
	nextDiashowContent: function()
	{
		if ( gallery.current + 1 < gallery.data.content.length )
			gallery.setContent(gallery.current + 1);
		else
			gallery.setContent(0);
	}
};


/* Inhalt falten
*******************/

var helper = {
	
	init: function()
	{
		helper.prev = false;
		$$('h3.fold').each(function (e)
		{
			helper.toggle_next_elements(e);
			e.observe('click', function(event)
			{
				var elt = Event.element(event);
				helper.toggle_next_elements(elt);

				if ( helper.prev != elt && helper.prev != false )
				{
					helper.hide_next_elements(helper.prev);
				}
				
				helper.prev = elt;
			});
		});
	},
	
	toggle_next_elements: function(e)
	{
		var next_elt = e.next();
		for ( var i = 0; next_elt != null && !next_elt.hasClassName('fold') && i < 20; i++ )
		{
			next_elt.toggle();
			next_elt = e.next(i+1);
		}
	},
	
	hide_next_elements: function(e)
	{
		var next_elt = e.next();
		for ( var i = 0; next_elt != null && !next_elt.hasClassName('fold') && i < 20; i++ )
		{
			next_elt.hide();
			next_elt = e.next(i+1);
		}
	}
};

/* Navigation: Unterpunkte mit AJAX laden
********************************************/

var subnav = {

	init: function ()
	{
		// Unterpunkt mit AJAX-Funktionalität ausstatten
		$$('#subnav li a.load').each(function(e)
		{
			e.observe('click', function(event)
			{
				Event.stop(event);
				// laden
				var elt = Event.element(event);
				var mr_url = subnav.getURL(elt);
				subnav.load(mr_url[1], elt);
			});
		});
		
		// Ersten Unterpunkt laden, falls kein Hauptext vergeben ist
		subnav.loadFirstEntry();
		
		// Hauptuntereintrag zwischenspeichern und bei Klick anzeigen
		if ( $$('#col-2 a.default').length == 1 )
		{
			subnav.default_entry = $('col-1').innerHTML;
			$$('#col-2 a.default')[0].observe('click', function(event)
			{
				Event.stop(event);
				var elt = Event.element(event);
				$('col-1').innerHTML = subnav.default_entry;
				$$('#subnav li').invoke('removeClassName', 'active');
				elt.up('li').addClassName('active');
				window.location.href = elt.href + '#uebersicht';
			});
		}
	},
	
	load: function(mr_url, elt)
	{
		elt.up('li').addClassName('loading');
		var section = $$('body')[0].readAttribute('id').toUpperCase();
		new Ajax.Request('/ajax_entry.php?section='+section+'&entry='+mr_url, {
			onComplete: function(rt)
			{
				var rt = rt.responseText;
				if ( rt != 'ERROR' )
				{
					$('col-1').innerHTML = rt;
					elt.up('li').removeClassName('loading');
					subnav.setActiveItem(mr_url);
					var url = elt.up('ul').previous('a').href;
					window.location.href = url + '#' + mr_url;
					gallery.init();
				} else
				{
					elt.up('li').removeClassName('loading');
				}
			}
		});
	},
	
	loadFirstEntry: function()
	{
		var elt = $$('#subnav ul a.load')[0];
		
		// Vorauswahl bei gesetztem Anker
		if ( window.location.href.indexOf('#') != -1 && !window.location.href.match(/#uebersicht$/) )
			var mr_url = window.location.href.substr(window.location.href.indexOf('#')+1);
		
		// kein Eintrag ausgewählt, oberster Unterpunkt (ohne else if werden Anker nicht richtig initiiert)
		else if ( $$('#col-1 .empty').length == 1 )
			var mr_url = subnav.getURL(elt)[1];
		
		if ( mr_url )
			subnav.load(mr_url, elt);
	},
	
	getURL: function(elt)
	{
		var url = elt.readAttribute('href');
		return url.match(/\/([a-z0-9_-]{1,40})\/?$/i);
	},
	
	setActiveItem: function(mr_url)
	{
		$$('#subnav li').invoke('removeClassName', 'active');
		$$('#subnav ul a').each(function(elt)
		{
			if ( elt.href.indexOf('/'+mr_url) != -1 )
				elt.up('li').addClassName('active');
		});
	}
};


/* Dokument geladen
**********************/

document.observe('dom:loaded', function()
{
	// Slideshow
	slideshow.init(14, 4);
	
	// Falten hinzufügen
	helper.init();
	
	// bei max. Bildbreite kein Rand
	$$('#content img').each(function(e)
	{
		if ( e.getDimensions().width > 540 )
			e.setStyle({margin: 0, float: 'none'});
	});
	
	// Untermenü
	if ( document.getElementById('subnav') )
		subnav.init();
	
	// Galerie
	gallery.init();
});
