

/**
 * Slideshow Fader
 */
var Fader = {
	
	items: [],
	current: 0,
	balken: null,
	duration: 3000,
	nav: [],
	to: null,
	first: null,
	tags: [],
	atags: [],
	options: {},
	sls: [],
	
	init: function(options) {
		this.sls[options.id] = {};
		this.sls[options.id].container = $(options.container);
		this.sls[options.id].w = options.width.toInt();
		this.sls[options.id].h = options.height.toInt();
		this.sls[options.id].tags = [];
		this.sls[options.id].atags = [];
		this.sls[options.id].items = [];
		this.sls[options.id].current = 0;
		
		
		this.sls[options.id].container.getChildren().each(function(item, index) {

			if (item.getTag() != 'img') return;
			//if (typeof this.sls[options.id].current == "undefined") this.sls[options.id].current = index;
			
			
			this.sls[options.id].tags[index] = new Element(
				'div',
				{
					//href:  item.getProperty('alt'),
					//target: '_top',
					styles: {
						position: 'absolute',
						left: 0,
						top: 0,
						height: this.sls[options.id].h,
						width: this.sls[options.id].w,
						backgroundPosition: 'center center',
						backgroundRepeat: 'no-repeat',
						backgroundImage: 'url(' + item.getProperty('src') + ')',
						zIndex: 900
					}
				}
			).injectInside(this.sls[options.id].container);
			
			this.sls[options.id].atags[index] = new Element('span', {
				'class': 'slideshow-big',
				events: {
					click: function(e) {
						Slimbox.open(item.getProperty("id"));
						
					}
				}
			}).injectInside(this.sls[options.id].tags[index]);

			// Erstelle Bild
			
			this.sls[options.id].items.push( new Fx.Style(
				this.sls[options.id].tags[index],
				'opacity',
				{ duration: 800 }
			).set(0));

			item.remove();

		}, this);
			
		this.sls[options.id].items[ this.sls[options.id].current ].set(1);
		this.slide.periodical(this.duration, this, options.id);
		
	},
	

	slide: function(id) {
		//console.log(id);
		
		if (this.sls[id].current+1 >= this.sls[id].items.length) this.sls[id].current = 0;
		else this.sls[id].current++;

		//console.log("Slideshow: %s; To: %s", this.options.id, this.current);

		this.set(id);
	},


	set: function(id) {
		
		this.sls[id].items.each(function(item, i) {
			this.sls[id].items[i].stop();
			if(this.sls[id].items[i].now > 0 && i != this.sls[id].current) this.sls[id].items[i].start(0);
		}, this);
		this.sls[id].items[this.sls[id].current].stop().start(1);
		
	}
	
};

/**
 * Menu
 * 
 * shows submenus on mouse over of nested ul - type menus
 */
var Mainmenu = new Class({
	
	mainitems: [],
	subitems: [],
	currentMain: 0,
	subItems: [],
	
	initialize: function(options) {
		this.options = $merge({
			delay: 300,
			container: ''
		}, options || {});
		
		
		
		/**
		 * Some basic initialisation
		 */
		
		this.container = $(this.options.container);

		
		
		/**
		 * Events for first sublevel
		 */
		this.container.getChildren().each(this.assignFirstSublevel, this);
	},
	
	
	assignFirstSublevel: function(item, index) {

		subs = item.getChildren();
		
		subs[0].addEvent('mouseenter', function() { this.hideOthers().hideOthers(); item.addClass(this.options.hoverClass);  }.bind(this));
		item.addEvent('mouseleave', function() { this.to = (function() { item.removeClass(this.options.hoverClass); }).delay(this.options.delay, this) }.bind(this));
		
		this.mainitems.push(item);		
		
		if (subs.length == 2) {	// A link and a sublist
			subs[1].addEvent('mouseenter', function() { $clear(this.to); }.bind(this));
			subs[1].getChildren().each(this.assignSecondSublevel, this);
		}
	},
	
	assignSecondSublevel: function(item) {
		subs = item.getChildren();
		
		subs[0].addEvent('mouseenter', function() { this.hideOtherSubs(); item.addClass(this.options.hoverClass);  }.bind(this));
		item.addEvent('mouseleave', function() { this.tosub = (function() {item.removeClass(this.options.hoverClass);}).delay(this.options.delay, this) }.bind(this));
		
		this.subItems.push(item);
		
		if (subs.length == 2) { // A link and a sublist
			subs[1].addEvent('mouseenter', function() { $clear(this.tosub); }.bind(this));
		}
	}, 
	 
	hideOthers: function() {
		$clear(this.to);
		this.mainitems.each(function(item) { item.removeClass(this.options.hoverClass); }, this);
		return this;
	},
	
	hideOtherSubs: function() {
		$clear(this.tosub);
		this.subItems.each(function(item) { item.removeClass(this.options.hoverClass); }, this);
		return this;
	}
});


var Tabs = new Class({

	items: [],
	active: 0,

	initialize: function(options) {

		this.options = $merge({
			container: 'tabs_container',
			active: 0,
			tabContainer: 'tabs',
			id: 'test',
			activeClass: 'active',
			tabsDivider: new Element('span'),
			disableClass: 'disable_element',
			afterClass: "after-active",
			beforeClass: "before-active"			
		}, options || {});


		options = this.options;
		this.tabs = $(options.tabContainer);
		var store = new Hash.Cookie('tabs_status');
		if (!store.get(options.id)) {
			store.set(options.id, this.active);
		} else {
			this.active = store.get(options.id);
		}
		this.store = store;
		this.scroller = new Fx.Scroll($(window));


		var items = $(options.container).getChildren();
		if (items.length % 2 != 0) return;



			// Assign Tabs
		var counter = 0;
		var all = items.length / 2;
		var divider = this.options.tabsDivider;
		divider.clone().addClass(this.active == 0 ? options.beforeClass : '').setProperty('id', 'first-tab-divider').injectInside(this.tabs);
		
		for(var i=0; i < items.length; i+=2) {

			this.items[ counter ] = {
				tab: this.makeTab(items[ i ], counter, all),
				content: this.makeContent(items[ i+1 ], counter)
			};

			counter++;
		}
		divider.clone().addClass(this.active == items.length-1 ? options.afterClass : '').setProperty('id', 'last-tab-divider').injectInside(this.tabs);
		
		
		// Make navigation buttons at the bottom of a tab
		this.navButtons();
		
		//this.allItems = this.tabs.getChildren();
		this.dividers = this.tabs.getChildren().filter(this.isDivider, this);		
		this.setTab(this.active);
	},
	
	navButtons: function() {
		var max = this.items.length-1;
	
		this.items.each(function(tab, index) {
			
			if (index >= max) return;
			
			var tabContent = tab.content;
			var nextIndex = index+1;
			
			var tabTitle = this.items[nextIndex].tab.getText();
			
				// The inner span Element
			new Element("span").setText(tabTitle).injectInside( // The outer A Tag
				new Element("a", {
					"class": "button blau",
					"href": "javascript:void(0)",
					"events": {
						"click": function() {
							this.setTab(nextIndex);
							this.scroller.toTop();
						}.bind(this)
					}
				}).injectInside(	// The wrapper div
					new Element("div", {
						"class": "tab-bottom-nav"
					}).injectInside(tabContent.getElements("div.column").getLast())
				)			
			);
			
			
		}, this);
	},
	
	/*
	setParentWidth: function() {
		allItems = this.allItems;
		width = 0;
		
		for (var i=0; i<allItems.length; i++) {
			width += allItems[i].getSize().size.x;
		}
		
		allItems[0].getParent().setStyle('width', width);
	},
	*/
	isDivider: function(item) {
		return (item.getTag() == this.options.tabsDivider.getTag());
	},
	
	makeTab: function(item, counter, allCount) {
		
		var el = new Element('a', {
			'class': this.tabClass,
			'href': 'javascript:void(0);',
			'events': {
				'click': this.setTab.bind(this, counter)
			}
		}).setText(item.getText()).injectInside(this.tabs);
		
		var div = this.options.tabsDivider;
		
		if (counter < allCount-1 && $type(div) == "element") {
		//	addklass = '';
		//	if (counter==this.active) addklass = this.options.afterClass;
			//if (this.active == counter+1) addklass = this.options.beforeClass;
		
		
		//	console.log("%s: No=%s, active=%s >> class = %s", item.getText(), counter, counter==this.active, addklass);
			div.clone().injectInside(this.tabs);
		}



		item.remove();
		return el;
	},
	
	makeContent: function(item, counter) {
		if (!counter == this.active)
			item.addClass(this.options.disableClass);
		return item;
	},
	
	setTab: function(active) {

		this.dividers.each(function(item) {
			item.removeClass(this.options.beforeClass).removeClass(this.options.afterClass);
		}, this);

		this.items.each(function(item, index) {
			var klass = this.options.activeClass;
			var disable = this.options.disableClass;
			if (index == active) {
				//if (!item.tab.hasClass(klass)) {
					item.content.removeClass(disable);
					
					var tab = item.tab;
					tab.addClass(klass);
										
					tab.getPrevious().addClass(this.options.beforeClass);
					tab.getNext().addClass(this.options.afterClass);
					
					this.active = index;
					this.store.set(this.options.id, index);
				//}
			} else {
				if (!item.content.hasClass(disable))
					item.content.addClass(disable);
				item.tab.removeClass(klass);
			}
		}, this);
	}
});


var ImageMenuHeight = new Class({
	
	initialize: function(myElements,options){
		options = Object.extend({
			onClick: Class.empty,
			start: -1,
			openHeight: 0,
			smallHeight: 0,
			itemHeight: 0,
			selected: -1,
			open: -1,
			transition: Fx.Transitions.sineOut,
			duration: 600
		}, options || {});
		
		this.myElements = myElements;
		this.options = options;
		
		options.itemHeight = myElements[0].getStyle('height').toInt();
		options.smallHeight = Math.round(((options.itemHeight*myElements.length)-options.openHeight)/(myElements.length-1));
		
		var fx = new Fx.Elements(myElements, {wait: false, duration: this.options.duration, transition: options.transition});
		
		myElements.each(function(el, i){
			el.addEvent('mouseover', function(e){
				e = new Event(e).stop();
				el.show();
			});
			/*
			el.addEvent('click', function(e){
				el.select();
			});
			
			el.addEvent('mouseout', function(e){
				e = new Event(e).stop();
				el.hide();
			});
			*/
			el.show = function(){
				var obj = {};
				obj[i] = {'height': [el.getStyle('height').toInt(), options.openHeight]};
				myElements.each(function(other, j){
					if (other != el){
						var w = other.getStyle('height').toInt();
						if (w != options.smallHeight) obj[j] = {'height': [w, options.smallHeight]};
					}
				});
				fx.start(obj);
			};
			
			el.hide = function(){
				var obj = {};
				if(options.selected == -1){
					myElements.each(function(el,i){
						obj[i] = {'height': [el.getStyle('height').toInt(), options.itemHeight]};	
					});
				}else{
					myElements.each(function(el,i){
						if(i != options.selected){
							var w = el.getStyle('height').toInt();
							if(w != options.smallHeight){obj[i] = {'height': [w, options.smallHeight]}};
						}else{
							obj[i] = {'height': [el.getStyle('height').toInt(), options.openHeight]};
						}
					});
				}
				fx.start(obj);
			};
			
			el.select = function(){
				if(options.selected == i){options.selected = -1}else{options.selected = i}
				options.onClick(options.selected,options.open);
				options.open = options.selected;
			};
		});
		
		if(myElements[options.start]){
			myElements[options.start].show();
			myElements[options.start].select();
		}
	},
	
	reset: function(){
		this.options.selected = -1;
		this.options.open = -1;
		this.myElements.each(function(el, i){
			el.hide();
		});
	}
	
});




var Slimbox;

(function() {

	// Global variables, accessible to Slimbox only
	var state = 0, options, images, activeImage, prevImage, nextImage, top, eventKeyDown, fx, preload, preloadPrev = new Image(), preloadNext = new Image(),
	// State values: 0 (closed or closing), 1 (open and ready), 2+ (open and busy with animation)

	// DOM elements
	overlay, center, image, prevLink, nextLink, bottomContainer, bottom, caption, number;

	/*
		Initialization
	*/

	window.addEvent("domready", function() {
		eventKeyDown = keyDown.bindWithEvent();

		// Append the Slimbox HTML code at the bottom of the document
		$(document.body).adopt(
			$$([
				overlay = new Element("div", {id: "lbOverlay"}),
				center = new Element("div", {id: "lbCenter"}),
				bottomContainer = new Element("div", {id: "lbBottomContainer"})
			]).setStyle("display", "none")
		);

		image = new Element("div", {id: "lbImage"}).injectInside(center).adopt(
			prevLink = new Element("a", {id: "lbPrevLink", href: "#"}),
			nextLink = new Element("a", {id: "lbNextLink", href: "#"})
		);
		prevLink.onclick = previous;
		nextLink.onclick = next;

		var closeLink;
		bottom = new Element("div", {id: "lbBottom"}).injectInside(bottomContainer).adopt(
			closeLink = new Element("a", {id: "lbCloseLink", href: "#"}),
			printLink = new Element("div", {id: "lbPrintlink"}),
			caption = new Element("div", {id: "lbCaption"}),
			number = new Element("div", {id: "lbNumber"}),
			new Element("div", {styles: {clear: "both"}})
		);
		closeLink.onclick = overlay.onclick = close;

		fx = {
			overlay: overlay.effect("opacity", {duration: 500}).set(0),
			image: image.effect("opacity", {duration: 500, onComplete: nextEffect}),
			bottom: bottom.effect("margin-top", {duration: 400})
		};
	});


	/*
		API
	*/

	Slimbox = {
		open: function(_images, startImage, _options) {
			options = $extend({
				loop: false,				// Allows to navigate between first and last images
				overlayOpacity: 0.8,			// 1 is opaque, 0 is completely transparent (change the color in the CSS file)
				resizeDuration: 400,			// Duration of each of the box resize animations (in milliseconds)
				resizeTransition: false,		// Default transition in mootools
				initialWidth: 250,			// Initial width of the box (in pixels)
				initialHeight: 250,			// Initial height of the box (in pixels)
				animateCaption: true,
				showCounter: true,			// If true, a counter will only be shown if there is more than 1 image to display
				counterText: "Image {x} of {y}"		// Translate or change as you wish
			}, _options || {});

			// The function is called for a single image, with URL and Title as first two arguments
			if (typeof _images == "string") {
				_images = [[_images,startImage]];
				startImage = 0;
			}

			images = _images;
			options.loop = options.loop && (images.length > 1);
			position();
			setup(true);
			top = window.getScrollTop() + (window.getHeight() / 15);
			fx.resize = center.effects($extend({duration: options.resizeDuration, onComplete: nextEffect}, options.resizeTransition ? {transition: options.resizeTransition} : {}));
			center.setStyles({top: top, width: options.initialWidth, height: options.initialHeight, marginLeft: -(options.initialWidth/2), display: ""});
			fx.overlay.start(options.overlayOpacity);
			state = 1;
			return changeImage(startImage);
		}
	};

	Element.extend({
		slimbox: function(_options, linkMapper) {
			// The processing of a single element is similar to the processing of a collection with a single element
			$$(this).slimbox(_options, linkMapper);

			return this;
		}
	});

	Elements.extend({
		/*
			options:	Optional options object, see Slimbox.open()
			linkMapper:	Optional function taking a link DOM element and an index as arguments and returning an array containing 2 elements:
					the image URL and the image caption (may contain HTML)
			linksFilter:	Optional function taking a link DOM element and an index as arguments and returning true if the element is part of
					the image collection that will be shown on click, false if not. "this" refers to the element that was clicked.
					This function must always return true when the DOM element argument is "this".
		*/
		slimbox: function(_options, linkMapper, linksFilter) {
			linkMapper = linkMapper || function(el) {
				return [el.href, el.title];
			};

			linksFilter = linksFilter || function() {
				return true;
			};

			var links = this;

			links.forEach(function(link) {
				link.onclick = function() {
					// Build the list of images that will be displayed
					var filteredLinks = links.filter(linksFilter, this);
					return Slimbox.open(filteredLinks.map(linkMapper), filteredLinks.indexOf(this), _options);
				};
			});

			return links;
		}
	});


	/*
		Internal functions
	*/

	function position() {
		overlay.setStyles({top: window.getScrollTop(), height: window.getHeight()});
	}

	function setup(open) {
		["object", window.ie ? "select" : "embed"].forEach(function(tag) {
			$each(document.getElementsByTagName(tag), function(el) {
				if (open) el._slimbox = el.style.visibility;
				el.style.visibility = open ? "hidden" : el._slimbox;
			});
		});

		overlay.style.display = open ? "" : "none";

		var fn = open ? "addEvent" : "removeEvent";
		window[fn]("scroll", position)[fn]("resize", position);
		document[fn]("keydown", eventKeyDown);
	}

	function keyDown(event) {
		switch(event.code) {
			case 27:	// Esc
			case 88:	// 'x'
			case 67:	// 'c'
				close();
				break;
			case 37:	// Left arrow
			case 80:	// 'p'
				previous();
				break;	
			case 39:	// Right arrow
			case 78:	// 'n'
				next();
		}
		// Prevent default keyboard action (like navigating inside the page)
		event.preventDefault();
	}

	function previous() {
		return changeImage(prevImage);
	}

	function next() {
		return changeImage(nextImage);
	}

	function changeImage(imageIndex) {
		if ((state == 1) && (imageIndex >= 0)) {
			state = 2;
			activeImage = imageIndex;
			prevImage = ((activeImage || !options.loop) ? activeImage : images.length) - 1;
			nextImage = activeImage + 1;
			if (nextImage == images.length) nextImage = options.loop ? 0 : -1;

			$$(prevLink, nextLink, image, bottomContainer).setStyle("display", "none");
			fx.bottom.stop().set(0);
			fx.image.set(0);
			center.className = "lbLoading";

			preload = new Image();
			preload.onload = nextEffect;
			preload.src = images[imageIndex][0];
		}

		return false;
	}

	function nextEffect() {
		switch (state++) {
			case 2:
				center.className = "";
				image.setStyles({backgroundImage: "url(" + images[activeImage][0] + ")", display: ""});
				$$(image, bottom).setStyle("width", preload.width);
				$$(image, prevLink, nextLink).setStyle("height", preload.height);

				caption.setHTML(images[activeImage][1] || "");
				number.setHTML((options.showCounter && (images.length > 1)) ? options.counterText.replace(/{x}/, activeImage + 1).replace(/{y}/, images.length) : "");
				printLink.removeEvents("click").addEvent("click", function() {
					window.open("index.php?eID=printImage&image=" + images[activeImage][0], "newPrintWindow");
				});
				
				if (prevImage >= 0) preloadPrev.src = images[prevImage][0];
				if (nextImage >= 0) preloadNext.src = images[nextImage][0];

				if (center.clientHeight != image.offsetHeight) {
					fx.resize.start({height: image.offsetHeight});
					break;
				}
				state++;
			case 3:
				if (center.clientWidth != image.offsetWidth) {
					fx.resize.start({width: image.offsetWidth, marginLeft: -image.offsetWidth/2});
					break;
				}
				state++;
			case 4:
				bottomContainer.setStyles({top: top + center.clientHeight, marginLeft: center.style.marginLeft, visibility: "hidden", display: ""});
				fx.image.start(1);
				break;
			case 5:
				if (prevImage >= 0) prevLink.style.display = "";
				if (nextImage >= 0) nextLink.style.display = "";
				if (options.animateCaption) {
					fx.bottom.set(-bottom.offsetHeight).start(0);
				}
				bottomContainer.style.visibility = "";
				state = 1;
		}
	}

	function close() {
		if (state) {
			state = 0;
			preload.onload = Class.empty;
			for (var f in fx) fx[f].stop();
			$$(center, bottomContainer).setStyle("display", "none");
			fx.overlay.chain(setup).start(0);
		}

		return false;
	}

})();

/**
 * Simple Gallery script for doringer.at
 */

var Page_Gallery = new Class({

	next_active: true,
	back_active: false,
	fx: [],
	page: 0,
	sizes: [-560, 0, 560],
	str : "{x} / {y}",
	
	el: {
		back: null,
		next: null,
		pages: null
	},
	
	initialize: function(options) {
	
		this.pages 	   = $('page-select');
		this.el.back   = $('gallery-back').addEvent('click', this.back.bind(this));
		this.next.back = $('gallery-next').addEvent('click', this.next.bind(this));
		$(options.container).getChildren().each(function(item, index) {
			this.fx[index] = new Fx.Style(item, 'marginLeft', {duration: 800}).set(this.sizes[2]);
		}, this);
		this.fx[0].set(this.sizes[1]);

		this.makePager();
	},
	
	makePager: function() {
		this.pages.setText( this.str.replace('{x}', this.page+1).replace('{y}', this.fx.length) );
		
	/*
		this.pages.empty();
		
		for (var i=0; i<this.fx.length; i++) {
			if (this.page == i) {
				new Element('img', {
					src: 'typo3conf/ext/gallery/res/gallery_hell.gif'
				}).injectInside(this.pages);
			} else if (this.page > i) {
				
				new Element('img', {
					src: 'typo3conf/ext/gallery/res/gallery_dunkel.gif',
					'class': 'clickable',
					events: {
						mouseover: this.hover,
						mouseout:  this.dehover,
						click:     this.gotoPage.bind(this, [i, false])
					}
				}).injectInside(this.pages);
				
			} else {			

				new Element('img', {
					src: 'typo3conf/ext/gallery/res/gallery_dunkel.gif',
					'class': 'clickable',
					events: {
						mouseover: this.hover,
						mouseout:  this.dehover,
						click:     this.gotoPage.bind(this, [i, true])
					}
				}).injectInside(this.pages);

			}
		}
		*/
		this.checkDisable();
	},
	
	hover: function()   { this.src = 'typo3conf/ext/gallery/res/gallery_hell.gif' },
	dehover: function() { this.src = 'typo3conf/ext/gallery/res/gallery_dunkel.gif' },
	
	checkDisable: function() {
		notactive = {
			cursor: 'default',
			opacity: 0.5
		};
		active = {
			cursor: 'pointer',
			opacity: 1
		};
		
		if (this.page == 0) {
			this.el.back.setStyles(notactive);	
			this.back_active = false;
		} else {
			this.el.back.setStyles(active);	
			this.back_active = true;
		}
		
		
		if (this.page == this.fx.length-1) {
			this.next.back.setStyles(notactive);	
			this.next_active = false;
		} else {
			this.next.back.setStyles(active);	
			this.next_active = true;
		}
	},
	
	gotoPage: function(page, next) {
//		next = p.n;
//		page = p.p;
		
		if (next) {
	
			this.fx[ this.page ].stop().start(this.sizes[1], this.sizes[0]);
			this.fx[ page ].stop().start(this.sizes[2], this.sizes[1]);
			this.page = page;
			
		} else {
			this.fx[ this.page ].stop().start(this.sizes[1], this.sizes[2]);
			this.fx[ page ].stop().start(this.sizes[0], this.sizes[1]);
			this.page = page;
		}
		this.makePager();
	},
	
	next: function(e) {
		//e = new Event().stop();
		if (!this.next_active) return;
		old = this.page;
		
		if (!this.fx[ this.page+1 ])
			this.page = 0;
		else
			this.page++;
			
		this.fx[ old ].stop().start(this.sizes[1], this.sizes[0]);
		this.fx[ this.page ].stop().start(this.sizes[2], this.sizes[1]);
		this.makePager();
	},
	
	
	back: function(e) {
		//e = new Event().stop();
		if (!this.back_active) return;
		old = this.page;
		
		if (!this.fx[ this.page-1 ])
			this.page = this.fx.length-1;
		else
			this.page--;
			
		this.fx[ old ].stop().start(this.sizes[1], this.sizes[2]);
		this.fx[ this.page ].stop().start(this.sizes[0], this.sizes[1]);
		this.makePager();
		
	}
});



/**
 * Simple Validator
 * Replaces the text of an element with an error message if the given validation fails and adds and class to this element.
 * When an Element is focused again, the class is removed and the wrong value (if there was one) is restored
 */
var Validator = new Class({
	
	fields:    [],
	backups:   [],
	form:      null,
	error:     false,
	lastValue: '',
	
	
	regexp : {
		alpha : /^[a-z ._-]+$/i,
		alphanum : /^[a-z0-9 ._-]+$/i,
		digit : /^[-+]?[0-9]+$/,
		nodigit : /^[^0-9]+$/,
		number : /^[-+]?\d*\.?\d+$/,
		email : /^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i,
		phone : /^[\d\s \/().-]+$/
		//url : /^(http|https|ftp)\:\/\/[a-z0-9\-\.]+\.[a-z]{2,3}(:[a-z0-9]*)?\/?([a-z0-9\-\._\?\,\'\/\\\+&amp;%\$#\=~])*$/i
	},
	
	initialize: function(options) {

		this.options = $merge({
			text: { // Text of the Error Message; The key must be the ID of an element with class="validate[xy]"
				name: "Name fehlt",
				first_name: "Vorname fehlt",
				last_name: "Nachname fehlt",
				firma: "Firma fehlt",
				adresse: "Adresse fehlt",
				plz: "PLZ fehlt",
				ort: "Stadt fehlt",
				telefon: "Telefon fehlt",
				fax: "Telefax fehlt",
				email: "eMail Adresse fehlt"
			},
			selector: "error",
			form: "",
			event: "submit" // Valid are "submit" and "blur"
		}, options || {});
		
		this.form = $(this.options.form);

		if ($type(this.form) != "element") return;

			// Push all Elements
		form = '#' + this.options.form + ' ';
		$$(form + 'input', form + 'textarea').each(function(element) {
			if (element.className.test(/validate\[(.+)\]$/i)) { // Is a form
				this.fields.push({
					"el": element,
					"tests": element.className.match(/validate\[(.+)\]$/i)[1].split(",")
				});
			}
		}, this);
	
			// Bind validation to form
		this.form.addEvent("submit", this.validate.bind(this));
		
			// Remove Messages on exit
		window.addEvent('unload', this.removeAllErrors.bind(this));
	},
	
	validate: function(e) {
		
		this.error = false;
		
		this.fields.each(function(field) {
			
			if (!this.form.getElements('input').contains(field.el)) return;
			
			field.tests.each(function(test) {
				this.validateSingeItem(test, field);
			}, this);
			
		}, this);
		

		if (this.error) {
			e = new Event(e).stop();
			return false;
		} else {
			return true;
		}
	},
	
	validateSingeItem: function(test, field) {
		test = test.split('-');
		this.currentElement = field;
		valid = true;
		
		switch(test[0]) {
				
			case 'email':
			case 'mail':
				valid = this._regexp(this.regexp.email);
				break;
				
			case 'number':
			case 'zahl':
				valid = this._regexp(this.regexp.number);
				break;
				
			case 'zip':
			case 'plz': // Contains 4, 5, or 6 numeric characters
				valid = (this._regexp(this.regexp.number) && this._length(4, 6));
				break;
						
			case 'length':
				valid = this._length(test[1], test[2]);
				break;
						
			case 'phone':
			case 'tel':
			case 'telefon':
				valid = this._regexp(this.regexp.phone);
				break;
		}
			
			// Test fails, or value is the error message -> throw an error	
		if (!valid || this.lastValue == this.options.text[this.currentElement.el.id]) this.setError();
			
	},
	
	setError: function() {
		el = this.currentElement.el;
		options = this.options;
		
		if (options.text[el.id] != this.lastValue.clean()) this.backups[ el.id ] = this.lastValue;
		el.setProperty('value', options.text[el.id]).addClass(options.selector).addEvent("focus", this.removeError.bind(this));
		this.error = true;
	},
	
	removeAllErrors: function() {
		this.fields.each(function(item) {
			options = this.options;		
			if (item.el.hasClass(options.selector)) {
				item.el.removeClass(options.selector).value = "";
			}
		}, this);
	},
	
	removeError: function(e) {
	
		var currentEl = this.currentElement = new Event(e).target;
		
		this.fields.each(function(field) {
			
			if (currentEl == field.el && currentEl.hasClass(this.options.selector)) {
				currentEl.removeClass(this.options.selector).setProperty("value", (this.backups[ currentEl.id ] ? this.backups[ currentEl.id ] : ''));
			}
			
		}.bind(this));
	
	},
	
	_regexp: function(exp) {	
		return (this.last().search(exp) != -1);
	},
	
	
	_length: function(min, max) {
		min = min.toInt();		
		max = (max == 'x') ? 999999 : max.toInt();
		val = this.last();	
		
		return (val.length >= min && val.length <= max);
	},
	
	last: function() {
		this.lastValue = (" " + this.currentElement.el.getProperty('value')).trim();	
		return this.lastValue;
	}
	
});

/*
 * This script was developed by the Einfach für Alle web site (http://www.einfach-fuer-alle.de/artikel/fontsize/).
 *
 * $Id: cookies.js 3579 2007-12-10 19:35:13Z fsuter $
 */

function Cookiemanager() {
	this.name = 'cookieManager';
	this.defaultExpiration = this.getExpiration();
	this.defaultDomain = window.location.host.replace(/((^\w+:\/\/[\w-]+\.)|\/)/, '');
	this.defaultPath = '/';
	this.cookies = new Object();
	this.expiration = new Object();
	this.domain = new Object();
	this.path = new Object();
	window.onunload = new Function (this.name+'.setDocumentCookies();');
	this.getDocumentCookies();
}

Cookiemanager.prototype.getExpiration = function() {
	var date = new Date();
    date.setTime(date.getTime()+(7*24*60*60*1000));
	return date.toGMTString();
}

Cookiemanager.prototype.getDocumentCookies = function() {
	var cookie,pair;
	var cookies = document.cookie.split(';');
	var len = cookies.length;
	for(var i=0;i < len;i++) {
		cookie = cookies[i];
		while (cookie.charAt(0)==' ') cookie = cookie.substring(1,cookie.length);
		pair = cookie.split('=');
		this.cookies[pair[0]] = pair[1];
	}
}

Cookiemanager.prototype.setDocumentCookies = function() {
	var expires = '';
	var cookies = '';
	var domain = '';
	var path = '';
	for(var name in this.cookies) {
		expires = (this.expiration[name])?this.expiration[name]:this.defaultExpiration;
		path = this.defaultPath;
		domain = this.defaultDomain;
        if(name) {
		    var cookies = name + '=' + this.cookies[name] + '; expires=' + expires + '; path=' + path + '; domain=' + domain;
            if(cookies != '') {
                document.cookie = cookies;
            }
        }
	}
	return true;
}

Cookiemanager.prototype.getCookie = function() {  
	return (this.cookies['fontSize'])?this.cookies['fontSize']:false;
}

Cookiemanager.prototype.setCookie = function(cookieValue) {
    if(!isNaN(cookieValue)) {
    	this.cookies['fontSize'] = parseInt(cookieValue);
    	this.expiration['fontSize'] = this.getExpiration();
    	this.domain['fontSize'] = window.location.host.replace(/^[\w-]+\./, '');
    	this.path['fontSize'] = this.defaultPath;
    	return true;
    }
}

var cookieManager = new Cookiemanager();


/*
 * This script was developed by the Einfach für Alle web site (http://www.einfach-fuer-alle.de/artikel/fontsize/).
 * The version below was slightly modified to include a reset button (original script has only bigger and smaller)
 * It was also modified to move some parts to the TYPO3 plugin so that they could be written dynamically
 * (for example the control buttons can be created using IMAGE content objects)
 *
 * $Id: efa_fontsize.js 3579 2007-12-10 19:35:13Z fsuter $
 */
function Efa_Fontsize06(increment,bigger,reset,smaller,def) {
	this.w3c = (document.getElementById);
	this.ms = (document.all);
	this.userAgent = navigator.userAgent.toLowerCase();
	this.isMacIE = ((this.userAgent.indexOf('msie') != -1) && (this.userAgent.indexOf('mac') != -1) && (this.userAgent.indexOf('opera') == -1));
	this.isOldOp = ((this.userAgent.indexOf('opera') != -1)&&(parseFloat(this.userAgent.substr(this.userAgent.indexOf('opera')+5)) <= 7));

	if ((this.w3c || this.ms) && !this.isOldOp && !this.isMacIE) {
		this.name = "efa_fontSize06";
		this.cookieName = 'fontSize';
		this.increment = increment;
		this.def = def;
		this.defPx = Math.round(16*(def/100))
		this.base = 1;
		this.pref = this.getPref();
		this.testHTML = '<div id="efaTest" style="position:absolute;visibility:hidden;line-height:1em;">&nbsp;</div>';
		this.biggerLink = this.getLinkHtml(1,bigger);
		this.resetLink = this.getLinkHtml(0,reset);
		this.smallerLink = this.getLinkHtml(-1,smaller);
	} else {
		this.biggerLink = '';
		this.resetLink = '';
		this.smallerLink = '';
		this.efaInit = new Function('return true;');
	}

	this.allLinks = this.biggerLink + this.resetLink + this.smallerLink;
}

Efa_Fontsize06.prototype.efaInit = function() {
		document.writeln(this.testHTML);
		this.body = (this.w3c)?document.getElementsByTagName('body')[0].style:document.all.tags('body')[0].style;
		this.efaTest = (this.w3c)?document.getElementById('efaTest'):document.all['efaTest'];
		var h = (this.efaTest.clientHeight)?parseInt(this.efaTest.clientHeight):(this.efaTest.offsetHeight)?parseInt(this.efaTest.offsetHeight):999;
		if (h < this.defPx) this.base = this.defPx/h;
		this.body.fontSize = Math.round(this.pref*this.base) + '%';
}

Efa_Fontsize06.prototype.getLinkHtml = function(direction,properties) {
	var html = properties[0] + '<a href="#" onclick="efa_fontSize06.setSize(' + direction + '); return false;"';
	html += (properties[2])?'title="' + properties[2] + '"':'';
	html += (properties[3])?'class="' + properties[3] + '"':'';
	html += (properties[4])?'id="' + properties[4] + '"':'';
	html += (properties[5])?'name="' + properties[5] + '"':'';
	html += (properties[6])?'accesskey="' + properties[6] + '"':'';
	html += (properties[7])?'onmouseover="' + properties[7] + '"':'';
	html += (properties[8])?'onmouseout="' + properties[8] + '"':'';
	html += (properties[9])?'onfocus="' + properties[9] + '"':'';
	return html += '>'+ properties[1] + '<' + '/a>' + properties[10];
}

Efa_Fontsize06.prototype.getPref = function() {
	var pref = this.getCookie();
	if (pref) return parseInt(pref);
	else return this.def;
}

Efa_Fontsize06.prototype.setSize = function(direction) {
	this.pref = (direction)?this.pref+(direction*this.increment):this.def;
	this.setCookie(this.pref);
	this.body.fontSize = Math.round(this.pref*this.base) + '%';
}

Efa_Fontsize06.prototype.getCookie = function() {
	var cookie = cookieManager.getCookie();
	return (cookie)?cookie:false;
}

Efa_Fontsize06.prototype.setCookie = function(cookieValue) {
	return cookieManager.setCookie(cookieValue);
}

var Ticker = (function() {

	var items = [], fx = [], current = 0, minLeft = [];
	
	function startSlide(i) {
		current++;
		if (current >= fx.length) {
			current = 0;
		}
		fx[i].element.style.display = "block";
//		console.log(fx[i]);
//		console.log(fx[i].element.style.display);

	var	itemsN = $("ticker").getElements(".item");
//		console.log(itemsN.length); 
		
		fx[i].start(416, -minLeft[i]).chain(function(currentI, lastI) { 
		//	console.log("Current %s, last: %s, i: %s", currentI, lastI, i); 
			
			startSlide(currentI);
			if(itemsN.length > 1) {
				fx[lastI].element.style.display = "none";
			}
		}.pass([current, i]) );
	}

	return function() {
		items = $("ticker").getElements(".item");
		//console.log(items);
		items.each(function(item, index) {
			minLeft[index] = item.getSize().size.x;
			item.setStyle("width", minLeft[index]);
			fx[index] = new Fx.Style(item, "marginLeft", {duration: minLeft[index] * 30, transition: Fx.Transitions.linear});
			item.style.display = "none";
		});
	/*	console.log(fx[index]);
		console.log(minLeft[index]);
		console.log(index);
		console.log(minLeft); */
		startSlide(0);
	}

})();


window.addEvent("domready", function(e) {

		// Hautpmenü oben
	var menu = new Mainmenu({container: "mainnav", hoverClass: "hover"});

		// Imagemenü Startseite
	if ($('image-menu-h')) {
		var imgMenu = new ImageMenuHeight($$('#image-menu-h .image-h'), {openHeight:179, start: 0, duration: 180});
	}
	
	if ($("ticker")) {
		Ticker();	
	}

		// Slimbox
	$$($$("a").filter(function(el) {
		return el.rel && el.rel.test(/^lightbox/i);
	})).slimbox({resizeDuration: 200, counterText: "{x} / {y}"}, null, function(el) {
		return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
	});
	
	if ($('print')) {
		$('print').addEvent('click', function(e) { window.print(); new Event(e).stop(); });
	}
		
	
});