window.addEvent('domready', function() {

// SIDELIST

	var list = $$('.sideMenu li.inactive');
	list.each(function(element) {
		var fx = new Fx.Styles(element, {duration:400, wait:false});
		element.addEvent('mouseenter', function(){
			fx.start({
				'margin-left': 5,
				color: '#464690'
			});
		});
	 	element.addEvent('mouseleave', function(){
			fx.start({
				'margin-left': 0,
				'color': '#000'
			});
		});
	});


// TIMER


	
	now = new Date();
	var t= now.getDate();
	var m = now.getMonth()+1;
	var j = now.getFullYear();
	
	
	weekofyear = function(date) {
		Datum=new Date(j,m-1,t); // Anm. 1
		DoDat=donnerstag(Datum);
		kwjahr=DoDat.getFullYear();
		DoKW1=donnerstag(new Date(kwjahr,0,4)); // Anm. 2
		return Math.floor(1.5+(DoDat.getTime()-DoKW1.getTime())/86400000/7) // Anm. 3, 4
	}
	
	function donnerstag(datum) { // Anm. 5
	  var Do=new Date();
	  Do.setTime(datum.getTime() + (3-((datum.getDay()+6) % 7)) * 86400000); // Anm. 3
	  return Do;
	}
	
	
	
	/*
	
	weekofyear = function(date) {
		var alleTage = 0;
		var heute = new Date();
		var Tage = new Array(12);
		Tage[0] = 31;
		Tage[2] = 31;
		Tage[3] = 30;
		Tage[4] = 31;
		Tage[5] = 30;
		Tage[6] = 31;
		Tage[7] = 31;
		Tage[8] = 30;
		Tage[9] = 31;
		Tage[10] = 30;
		Tage[11] = 31;
		
		if (Math.round(heute.getYear()/4) == heute.getYear()/4) {
			Tage[1] = 29
		}
		else{
			Tage[1] = 28
		}
		
		if (heute.getMonth() == 0) {      
			alleTage = alleTage + heute.getDate();
		 }
		 else{
			var curMonth = heute.getMonth();
			for (var count = 1; count <= curMonth; count++) {
				alleTage = alleTage + Tage[count - 1];
			}
			alleTage = alleTage + heute.getDate();
		}
		return Math.round(alleTage/7);
	}
	*/
	
	
	activeClock = function() {
		now = new Date();
		   
		var day = now.getDate();
		var month = now.getMonth()+1;
		var year = now.getFullYear();
		
		var string = ((day < 10) ? "0" : "") + day;
		string += ((month < 10) ? ".0" : ".") + month;
		string += "." + year;
		
		var h = now.getHours();
		var i = now.getMinutes();
		string += " " + h;
		string += ((i < 10) ? ":0" : ":") + i;
		string += " Uhr, " + weekofyear(now) + ". KW";
		
		$('clock').innerHTML = string;
		
		setTimeout("activeClock()", 1000);
	}
	
	activeClock();
	
	
	
// ACTIVITIES
	
	var active = null;
	
	$$('.cardslide').each(function(slide) {
		var mySlide = new Fx.Slide(slide, {mode: 'vertical', wait: false });
		var par = $('aroundCard' + slide.id.substr(4, slide.id.length));
		
		par.addEvent('click', function(e){
			if(active != null && active != slide) {
				active.hide();
			}
			if(active != slide) {
				slide.show();
				active = slide;
			}
			else if(active == slide) {
				slide.hide();
				active = null;
			}
		});
		slide.show = function() {
			mySlide.slideIn();
			
		}
		slide.hide = function() {
			mySlide.slideOut();
		}
		slide.toggle = function() {
			mySlide.toggle();
		}			
		mySlide.hide();
	});
	
	var activities = $$('.activity');
	$$('.activity h1').setStyle('color', 'white');

	var interval = null;
	var ac = activities.length;
	var cac = -1;
	
	var startInterval = function() {
		interval = window.setInterval(function() {
			window.clearInterval(interval);
			whatIDoChange();	
		}, 12000);
	}
	
	var whatIDoChange = function() {
		if(activities[cac]) {
			if(!Client.Engine.ie) {
				activities[cac].fx.slideOut();
			}
			else {
				activities[cac].setStyle('display', 'none');
			}
		}
		cac++;
		if(cac >= ac) cac = 0;
		if(!Client.Engine.ie) {
			activities[cac].fx.slideIn();
		}
		else {
			activities[cac].setStyle('display', 'inline');
		}
		if(ac > 1) {
			startInterval();
		}
	}
	
	$$('.activityBack').each(function(div) {
		div.setStyles({
			'position': 'absolute',
			'backgroundImage': (!Client.Engine.ie) ? 'url(http://static.materialsgate.de/graphics/header_slide_bg_blue.png)' : '',
			'backgroundColor': (Client.Engine.ie) ? '#201853': '',
			'backgroundPosition': 'bottom left',
			'width': '100%',
			'height': (!Client.Engine.ie) ? '100%' : 80,
			'opacity': 0.5,
			'top': 0,
			'left': 0,
			'zIndex': 1
		}); 
	});
	
	$$('.activityInner').each(function(div) {
		div.setStyles({
			'position': 'relative',
			'padding': (!Client.Engine.ie) ? '5px 30px 20px 10px' : '5px 10px 10px 10px',
			'zIndex': 5,
			'color': 'white'
		});		
	});
	activities.each(function(act) {
		act.addEvent('mouseover', function() {
			window.clearInterval(interval);
		});
		act.addEvent('mouseout', function() {
			startInterval();
		});
		
		act.inject(document.body);
		act.setStyles({
			'position': 'absolute',
			'width': 564,
			'top': 0,
			'left': 210,
			'zIndex': 0
		}); 
		if(!Client.Engine.ie) {
			act.fx = new Fx.Slide(act, {mode: 'vertical', wait: false });
			act.fx.hide();
		}
		else {
			act.setStyles({
				'display': 'none'
			});
		}
	});	
	
	if(ac > 0) {
		whatIDoChange();
	}
	
});


var FISGlossary = new Class({
	
	object: null,
	words: {},
	contents: new Array(),
	contentsIndex: new Array(),
	
	initialize: function(object, words) {
		this.object = $(object);
		this.words = words;
		if(!this.object) {
			return;
		}
		
		for(var wordIndex = 0; this.words[wordIndex]; wordIndex++) {
			var word = this.words[wordIndex];
			
			var expression = '(' + word + ')';
			var expreplace = '<a class="fis_glossary_match" word="' + word + '">$1</a>';
			var expstyle = 'i';
			 
			if(true || word.toUpperCase() == word) {
				expression = '(^|\\s+|-|\\.|\\,|\\(|\\))(' + word + ')($|\\s+|-|\\.|\\,|\\(|\\))';	
				expreplace = '$1<a class="fis_glossary_match" word="' + word + '">$2</a>$3';
				var expstyle = 'i';			
			}
			
			
			this.object.innerHTML = this.object.innerHTML.replace(
				//new RegExp('(^|\\s+)(' + word + ')(\\S*)','gi'), ' <a class="fis_glossary_match" word="' + word + '">$2$3</a>');
				new RegExp(expression, expstyle), expreplace);
		}
		
		this.object.getChildren().each(function(element) {
			if(element.className == 'fis_glossary_match') {
				element.addEvent('mouseover', function() {
					this.initElement(element);
					element.display.show();
				}.bind(this));				
			}			
		}.bind(this));
		
	},
	
	initElement: function(element) {
		
		if(element.display) {
			element.display.s = 0;
			element.display.setStyle('display', 'block');
			return;
		}
		
		var isIE = Client.Engine.ie;
		
		element.setStyle('cursor', 'help');
		//element.setStyle('zIndex', 10);
		
		element.display = new Element('div', {
			styles: {
				position: 'absolute',
				left: element.getPosition().x - 95 + element.getSize().size.x / 2,
				top: element.getPosition().y - 165,
				width: 280,
				zIndex:22000,
				opacity: 0.0001,
				cursor: 'help'
			}
		});
		
		new Element('div', {
			styles: {
				background: 'url(http://static.materialsgate.de/graphics/fis_glossary/fis_glossary_top.' + (isIE ? 'gif' : 'png') + ') no-repeat',
				height:16,
				margin: 0,
				padding: 0
			}
		}).inject(element.display);
		
		element.outerContent = new Element('div', {
			styles: {
				background: 'url(http://static.materialsgate.de/graphics/fis_glossary/fis_glossary_right.' + (isIE ? 'gif' : 'png') + ') repeat-y right',
				margin: 0,
				padding: 0				
			}
		});
		
		element.innerContent = new Element('div', {
			styles: {
				background: 'white',
				borderLeft: '1px solid #211955',
				margin: '0 10px 0 0',
				padding: '0 0 0 10px',
				position: 'relative'
			}
		});
		
		element.innerContent.inject(element.outerContent);
		element.outerContent.inject(element.display);
		
		element.display.inject(document.body);
		
		this.loadGlossaryWord(element.getAttribute('word'), element.innerContent);
		
		new Element('img', {
			src: 'http://static.materialsgate.de/graphics/fis_glossary/fis_glossary_bottom.' + (isIE ? 'gif' : 'png') + '',
			styles: {
				margin: 0,
				padding: 0
			}
		}).inject(element.display);
		
		element.display.inject(document.body);
		
		element.display.s = 0;
		element.display.fxonComplete = function() {
			if(element.display.s == 0) {
				element.display.s = 1;
			}
			else if(element.display.s == 1) {
				element.display.s = 0;				
				element.display.setStyle('display', 'none');					
			}
		}
		
		element.display.fx = new Fx.Styles(element.display, {
			duration: 200, 
			transition: Fx.Transitions.Quad.easeInOut, 
			wait: false,
			onComplete: function() {
				element.display.fxonComplete();
			}
		});
		
		element.display.show = function() {
			element.display.fx.start({
				opacity: 1
			});
		};
		element.display.hide = function() {
			element.display.fx.start({
				opacity: 0.0001
			});
		};
		
		var outer = function(e) {
			new Event(e).stop();
			var vrytarget = e.relatedTarget;
			var target = e.relatedTarget;
			while(target) {
				if(target == element.display || target == element || target == element.innerContent || target == element.outerContent) {
					return;
				}
				target = target.getParent();
				if(target.getTag() == 'body') {
					target = false;
				}
			}
			element.display.hide();			
		};
		
		element.addEvent('mouseout', outer);
		element.display.addEvent('mouseout', outer);
		element.addEvent('click', function() {
			if(element.display.s == 0) {
				element.display.show();
			}
		});
		element.display.addEvent('click', function() {
			if(element.display.s == 1) {
				element.display.hide();
			}
		});
	
	},
	
	loadGlossaryWord: function(word, div) {
		
		for(var i = 0; i < this.contents.length; i++) {
			if(this.contentsIndex[i] == word) {
				div.innerHTML = this.contents[i];
				return;
			}	
		}
		
		new Ajax('/glossary.php?get=' + word, {
			onSuccess: function(response) {
				var length = this.contents.length;
				this.contents[length] = response;
				this.contentsIndex[length] = word;
				this.loadGlossaryWord(word, div);
			}.bind(this)
		}).request();
		
		
	
	},
	
	
	
	levenshtein: function(str1, str2 ) {
	    // http://kevin.vanzonneveld.net
	    // +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
	    // +   bugfixed by: Onno Marsman
	    // *     example 1: levenshtein('Kevin van Zonneveld', 'Kevin van Sommeveld');
	    // *     returns 1: 3
	 
	    var s, l = (s = (str1+'').split("")).length, t = (str2 = (str2+'').split("")).length, i, j, m, n;
	    if(!(l || t)) return Math.max(l, t);
	    for(var a = [], i = l + 1; i; a[--i] = [i]);
	    for(i = t + 1; a[0][--i] = i;);
	    for(i = -1, m = s.length; ++i < m;){
	        for(j = -1, n = str2.length; ++j < n;){
	            a[(i *= 1) + 1][(j *= 1) + 1] = Math.min(a[i][j + 1] + 1, a[i + 1][j] + 1, a[i][j] + (s[i] != str2[j]));
	        }
	    }
	    return a[l][t];
	},
	
	removeHTMLTags: function(strInputCode){
 		strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1){
 		 	return (p1 == "lt")? "<" : ">";
 		});
 		return strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
 	}	

	
});

/*

return;
		
		var content = this.object.innerHTML;
		var splitted = this.removeHTMLTags(content).split(/\s+/);
		for(var i = 0; i < splitted.length; i++) {
			for(var wordIndex = 0; this.words[wordIndex]; wordIndex++) {
				var word = this.words[wordIndex];
				if(splitted[i].match(word)) {
					this.object.innerHTML = this.object.innerHTML.replace(new RegExp('(^|\\s+)(' + splitted[i] + ')($|\\s+)','g'), "$2");
					break;
				}
			}
		}
		
		*/


window.addEvent('domready', function() {

	var car = $('carousel');
	if(!car) return;
	
	car.setStyle('height', 130);
	
	var carTitle = $('carouseltitle');
	
	car.setStyle('position', 'relative');
	
	var maxSize = 80;
	var minSize = 40;
	var maxOpacity = 1;
	var minOpacity = 0.4;
	
	var moveDuration = 1400;
	
		
	var margin = new Object;
	margin.x = maxSize - 40;
	margin.y = minSize - 10;
	
	var inner = new Object;
	inner.x = parseInt(car.getStyle('width')) - 2 * margin.x;
	inner.y = parseInt(car.getStyle('height')) - 2 * margin.y;
	var middle = new Object;
	middle.x = parseInt(car.getStyle('width')) / 2;
	middle.y = parseInt(car.getStyle('height')) / 2;
	
	var maxY = 1 * inner.y / 2 + middle.y;
	var minY = -1 * inner.y / 2 + middle.y;
	
	if(!Client.Engine.ie6) {
		cardmarkFx = new Fx.Styles($('cardmark'), {duration: moveDuration, transition: Fx.Transitions.Circ.easeIn, wait: false });
	}
	$('cardmark').setStyle('opacity', 0.001);
	
	var getImageSize = function(degree) {
		var x = Math.sin(degree / 180 * Math.PI);
		var y = Math.sqrt(1 - x * x);
		if(degree >= 90 && degree < 270) y *= -1;
		y = y * inner.y / 2 + middle.y;
		var diffY = maxY - minY;
		return ;
	}
	
	var circle = function(degree) {
		var result = new Object;
		result.x = middle.x;
		result.y = middle.y;
		
		// Kreis
		while(degree < 0) degree += 360;
		while(degree > 360) degree -= 360;
		if(degree == 360) {
			degree = 0;
		}
		
		var x = Math.sin(degree / 180 * Math.PI);
		var y = Math.sqrt(1 - x * x);
		
		if(degree >= 90 && degree < 270) {
			y *= -1;
		}
		x *= -1
		
		result.x = x * inner.x / 2 + middle.x;
		result.y = y * inner.y / 2 + middle.y; 
		
		result.size = (maxSize - minSize) / (maxY - minY) * (result.y - minY) + minSize;
		
		if(Math.round(degree) == 0) {
			result.opacity = maxOpacity;
		}
		else if(Math.abs(Math.round(degree)) == 180) {
			result.opacity = minOpacity;
		}
		else {
			result.opacity = (maxOpacity - minOpacity) / (maxY - minY) * (result.y - minY) + minOpacity;
		}
		
		result.zIndex = Math.abs(degree - 180);
		
		result.x = Math.round(result.x - result.size / 2 + 0.5);
		result.y -= result.size / 2;
		return result;
	}
	
	var clickEventId = 0;
	var images = car.getElements('img');
	var i = 0;
	
	images.each(function(img) {
		img.setStyle('width', 30);
		img.setStyle('position', 'absolute');
		//img.setStyle('border', '1px solid #211955');
		img.fxLinear = new Fx.Styles(img, {duration:600, transition: Fx.Transitions.Expo.easeIn});
		img.degree = 360 / images.length * i++;
		img.step = 0;
		
		img.clickEventId = clickEventId;
		
		img.moveTo = function(degree) {
			var pos = circle(degree);
			img.fxLinear.start({
				'width': pos.size,
				'opacity': pos.opacity,
				'left': pos.x,
				'top': pos.y,
				'zIndex': pos.zIndex
			});
			img.degree = degree;
		};
		
		img.setTo = function(degree) {
			var pos = circle(degree);
			img.setStyles({
				'width': pos.size,
				'opacity': pos.opacity,
				'left': pos.x,
				'top': pos.y,
				'zIndex': pos.zIndex
			});
			img.degree = degree;
		};
		
		
		var fx = new Fx.Styles(img, {duration: moveDuration, transition: Fx.Transitions.Quad.easeInOut, wait: false });
			
		img.rotateTo = function(degree, distance) {
			
			var from = img.degree;
			
			if(!distance) {
				distance = (from - degree) % 360;
				if(distance > 180) {
					distance -= 360;
				}
				if(distance < -180) {
					distance += 360;
				}
				images.each(function(i2) {
					if(i2 != img) i2.rotateTo(i2.degree - distance, distance);
				});
				
			}
			
			// "Überschreiben" der increase-Methode
			fx.increase = function() {
				img.setTo(from - distance * fx.delta);
				//for (var p in fx.now) fx.element.setStyle(p, Fx.CSS.serve(fx.now[p], fx.options.unit));
			};
			fx.start();
						
		}
		
		img.hide = new Fx.Styles(carTitle, {duration: moveDuration, transition: Fx.Transitions.Circ.easeIn, wait: false });
		img.setTitle = function() {
			img.hide.stop();
			img.hide.options.duration = moveDuration / 10;
			img.hide.start({
				opacity:0.001
			}).chain(function() {
				img.hide.options.duration = moveDuration / 5;
				if(img.getAttribute('special')) {
					url = '/ajax.php?todo=loadInfoData&special';
				}
				else {
					url = '/ajax.php?todo=loadInfoData&cardId=' + img.getAttribute('cardid');
				}
				new Ajax(url, {
					onSuccess: function(result) {
						carTitle.setHTML(result);
						img.hide.start({
							opacity:1
						});
					}
				}).request();
			})
			
			if(!Client.Engine.ie) {
				cardmarkFx.stop();
				cardmarkFx.options.duration = moveDuration / 10;
				cardmarkFx.start({
					opacity:0.001
				}).chain(function() {
					cardmarkFx.options.duration = moveDuration / 5 * 2;
					cardmarkFx.start({
						opacity:1
					});				
				})
			}
		};
		
		img.addEvent('click', function(e) {
			if(e) new Event(e).stop();
			clickEventId++;
			img.rotateTo(0);
			img.setTitle();
		});		
		img.moveTo(img.degree);
		
	});
	
	images[0].setTitle();
	
	
	/*
	Funktionierendes Mouse-Mitlauf-Ding
	
	car.mouseXpos = car.mouseXposLast = -1;
	car.mminterval = null;
	car.addEvent('mousemove', function(e) {
		car.mouseXpos = e.client.x;
		if(car.mminterval == null) {
			car.mminterval = window.setInterval(function() {
				if(car.mouseXposLast != -1) {
					var diff = car.mouseXposLast - car.mouseXpos;
					if(diff != 0) {
						images.each(function(img) {
							img.degree = (img.degree + diff / 3) % 360;		
							var pos = circle(img.degree);
							img.setStyles({
								'width': pos.size,
								'opacity': pos.opacity,
								'left': pos.x,
								'top': pos.y,
								'zIndex': pos.y
							});
						});
					}
				}
				car.mouseXposLast = car.mouseXpos; 				
			}, 10);
		}
	});
	car.addEvent('mouseout', function(e) {
		if(e.target != car) return;
		window.clearInterval(car.mminterval);
		car.mminterval = null;
		car.mouseXpos = car.mouseXposLast = -1;
	});
	*/
	
	
});






// FISFormValidator Version 0.84
// FISolution 
// 3. Januar 2009 14:02:48
// Uses mootools-beta-1.2b1-compatible.js
 

var setUploadDone = function(upload_id, func) {
	$$('form').each(function(form) {
		if(form.uploadId && form.uploadId == upload_id) {
			form.upload_done();
			if(func) func();
			closeCenterBox();
			return;
		}
	});
}
var setValidationError = function(upload_id, valid_id) {
	$$('form').each(function(form) {
		if(form.uploadId && form.uploadId == upload_id) {
			for(var h = 0; h < form.FISFV.fields.length; h++) {
				var field = form.FISFV.fields[h];
				for(var i = 0; i < field.validations.length; i++) {
					for(var j = 0; j < field.validations[i].length; j++) {
						if(field.validations[i][j].id == valid_id) {
							field.validations[i][j].showError(false);
							return;
						}
					}
				}
			}
			return;
		}
	});
}
var resetErrorMessages = function(upload_id) {
	$$('form').each(function(form) {
		if(form.uploadId && form.uploadId == upload_id) {
			var errorField = $(form.id + '_errorfield');
			if(!errorField) return;
			var ul = errorField.getChildren('ul')[0];
			ul.getChildren().each(function(c) { c.remove(); });
			errorField.setStyle('display', 'none');			
		}
	});
}

var setErrorMessage = function(upload_id, message) {
	$$('form').each(function(form) {
		if(form.uploadId && form.uploadId == upload_id) {
			var errorField = $(form.id + '_errorfield');
			if(!errorField) alert(message);
			errorField.setStyle('display', 'block');
			var ul = errorField.getChildren('ul')[0];
			new Element('li').setHTML(message).inject(ul);
		}
		return;
	});
}


var setSuccessfulUpload = function(upload_id, form_name, html) {
	$$('form').each(function(form) {
		if(form.uploadId && form.uploadId == upload_id) {
			for(var h = 0; h < form.FISFV.fields.length; h++) {
				var field = form.FISFV.fields[h];
				if(field.name == form_name) { 
					for(var i = 0; i < field.validations.length; i++) {
						for(var j = 0; j < field.validations[i].length; j++) {
							field.validations[i][j].showError(true);
						}
					}
					var div = new Element('div').setHTML(html).injectAfter(field);
					if(!field.removed) field.remove();
					field.removed = true;
					break;
				}
			}
		}
	});
}


		
var FISFViframecounter = 0;
var FISFV = new Class({
	// Optionen Implementieren
	Implements : [Options],
	
	// Default Optionen setzen
	options : {
		
	},
	form: null,
	fields: null,
	validations: null,
	
	// init
	initialize: function(formId, options) {
		// optionen Ã¼bernehmen
		this.setOptions(options);
		
		this.fields = new Array();
		this.validations = new Array();
		
		this.form = $(formId);
		this.form.FISFV = this;
		this.form.addEvent('submit', function(e) {
			var status = true;
			for(var i = 0; i < this.fields.length; i++) {
				status = this.fields[i].validate() && status;
			}
			if(status) { 
				/*var use_controlled = false;
				for(var i = 0; i < this.fields.length; i++) {
					if(this.fields[i].type && this.fields[i].type == 'file' && this.fields[i].value.trim() != '') {
						use_controlled = true;
						break;
					}	
				}
				if(use_controlled) {
					new Event(e).stop();
					this.form.sendControlled();
				}*/
				return true;
			}
			new Event(e).stop();
		}.bind(this));
		
		FISFViframecounter++;
		this.form.sendControlled = function() {
			var debug = false;
			
			var iframecounter = 0;
			var status = new Element('div', {id: 'progressbar'});
			var progressUrl = '/ajax/uploadprogress.php';
				
			this.form.setAttribute('action', '/upload_receaver.php?anticache=' + Math.round(Math.random() * 10000000)); 
			
			var div = new Element('div');
			var span = new Element('div', {'class': "uploadprogress_caption"}).setHTML('Uploadvorgang wird durchgefÃ¼hrt');
			span.inject(div);
			status.inject(div);
			if(!debug) showCenterBox(div, 500, 60, true);
				
			var started = 0;
			var start = new Date().getTime() / 1000;
			var waitUntil = -1;
			var upload_speed = 0;
			
			this.form.uploadId = Math.round(Math.random() * 10000000);
			this.form.percent = 0;
			
			if(!status.sd) {
				status.sd = new Element('div', {
					'class': 'progressbar_percent',
					'styles': {
						position: 'absolute',
						left: 0,
						top: 0
					}
				});
				status.sd.inject(status);
			}
			status.sd.setStyle('color', 'green');
			status.sd.setHTML('...initialisiere Upload...');
			
			if(!status.si) {
				status.si = new Element('div', {
					'class': 'progressbar_bar',
					'styles': {
						width: 0
					}
				});
				status.si.inject(status);
			}
			status.si.setStyle('width', "0%");
			status.setStyle('display', 'block');
			
			if(!this.form.uploadIframe) {
				this.form.uploadIframe = new Element('iframe', {
					'name': "upload_iframe_" + FISFViframecounter,
					'styles': {
						'width': 300,
						'height': 200,
						'display': (!debug ? 'none' : '')
					},
					'src': ''
				});
				this.form.uploadIframe.injectBefore(this.form);
				this.form.target = this.form.uploadIframe.name;
			}
			
			if(!this.form.uploadField) {
				this.form.uploadField = new Element('input', {
					'name': 'UPLOAD_IDENTIFIER',
					'type': 'hidden'
				});
				this.form.uploadField.injectBefore(this.form.getChildren()[0]);
			}
			this.form.uploadField.value = this.form.uploadId;
			
			this.form.upload_done = function() {
				status.si.setTo(100);
				status.setStyle('display', 'none');
			}
			var ajaxCounter = 0; 
			var last_percent = 0;
			status.si.setTo = function(percent, init) {
				var now = new Date().getTime() / 1000;
				upload_speed = (percent - last_percent) / (now - start);
				start = now;
				last_percent = percent;
					
				if(percent < this.form.percent && !init) {
					if(upload_speed != 0) waitUntil = now + ((this.form.percent - percent) / upload_speed); 
				}
				else if(init) {
					$('status').setStyle('display', 'block');
				}
				else {
					waitUntil = -1;
					this.form.percent = percent;
				}						
			}.bind(this)
			
			this.form.readAjaxStatus = function() {
				
				if(this.form.percent == 100) return;
				new Ajax(progressUrl + '?id=' + this.form.uploadId + '&started=' + started + '&anticache=' + ajaxCounter, {
					method: 'get', 
					evalScripts: false, 
					onSuccess: function(response) {
						var now = new Date();
						if(response == 'DONE') {
							status.sd.setHTML('... Verarbeitung, bitte warten ...');
							status.sd.setStyle('text-decoration', 'blink');
							return;
						}
						else if(response == 'FNE') {
							status.sd.setHTML('... bitte warten ...');
							status.sd.setStyle('text-decoration', 'blink');
						}
						else {
							started = 1;
							var f = parseFloat(response);
							status.si.setTo(f);
						}
						var timeout = (ajaxCounter++) / 10 * 1000 + 1000;
						window.setTimeout(this.form.readAjaxStatus, timeout);
					}.bind(this)
				}).request();
			}.bind(this);
			
			status.si.interval = window.setInterval(function() {
				var now = new Date().getTime() / 1000;
				if(upload_speed > 0 && now >= waitUntil) {
					var speed = upload_speed;
					this.form.percent = this.form.percent + speed / 10;
					if(this.form.percent >= 100) {
						status.sd.setHTML('... Verarbeitung, bitte warten ...');
						status.sd.setStyle('text-decoration', 'blink');
						window.clearInterval(status.si.interval);
					}
					status.si.setStyle('width', this.form.percent + "%");
					status.sd.setStyle('color', this.form.percent < 50 ? 'green' : 'white');
					status.sd.setHTML(Math.round(this.form.percent) + " %");
				}									
			}.bind(this), 100);
			
			window.setTimeout(function() { this.form.submit() }.bind(this), 100);
			window.setTimeout(this.form.readAjaxStatus, 300);
			//this.form.statusIframe.src = '/ajax/uploadprogress.php?id=' + this.form.uploadId;					
		}.bind(this);
		
	},
	registerField: function(id) {
		var field = $(id);
		field.validations = new Array();
		field.addValidations = function(validationsArray) {
			field.validations[field.validations.length] = validationsArray;
		}
		field.validate = function() {
			if(!field.setEvents) {
				var tag = field.tagName.toString().toLowerCase().trim();
				if(tag == 'input' && (field.type == 'radio' || field.type == 'checkbox')) {
					field.addEvent('click', function() { field.validate(); });
					field.addEvent('change', function() { field.validate(); });		
				}
				else {
					field.addEvent('keyup', function() { field.validate(); });
					field.addEvent('change', function() { field.validate(); });	
				}
				field.setEvents = true;
			}
			var err_i = -1;
			var err_j = -1;
			for(var i = 0; i < field.validations.length; i++) {
				// DIESE HIER ALLE "UND"-VERKNÃœPFT
				var or_res = false;
				var tmp_err_j = -1;
				for(var j = 0; j < field.validations[i].length; j++) {
					// DIE HIER ALLE "ODER"-VERKNÃœPFT
					var tmp_res = field.validations[i][j].validate(field);
					if(!tmp_res && tmp_err_j == -1) tmp_err_j = j;
					or_res = or_res || tmp_res;
				}
				if(err_i == -1 && !or_res && tmp_err_j != -1) {
					err_i = i;
					err_j = tmp_err_j;
				}
			}
			for(var i = 0; i < field.validations.length; i++) {
				for(var j = 0; j < field.validations[i].length; j++) {
					field.validations[i][j].showError(true);
				}
			}
			if(err_i > -1) {
				field.validations[err_i][err_j].showError(false);
			}
			return err_i == -1;
			
		}.bind(this);
		field.errorDiv = false;
		field.pendingErrors = new Array();
		field.setMessage = function(validation, valid) {
			if(valid) {
				if(this.errorDiv && this.errorDiv.validatorId == validation.id) {
					this.errorDiv.remove();
					this.errorDiv = false;
					
					if(this.pendingErrors.length > 0) {
						var tmp = this.pendingErrors;
						var err = this.pendingErrors[0];
						this.pendingErrors = new Array();
						for(var i = 1; i < tmp.length; i++) {
							this.pendingErrors[i - 1] = tmp[i];
						}
						this.setMessage(err, false);
					}
				}
				return;
			}
			if(!this.errorDiv) {
				var behind = field;
				var tag = field.tagName.toString().toLowerCase().trim();
				if(tag == 'input' && (field.type == 'checkbox' || field.type == 'radio')) {
					$$('label').each(function(label) {
						if(label.getAttribute('for') == field.id) {
							behind = label;
						}
					});
				}
				var pos = behind.getPosition();
				this.errorDiv = new Element('div', {
					'class': 'FV_error_display_top',
					'styles': {
						position: 'absolute',
						left: pos.x + behind.offsetWidth + 5,
						top: pos.y
					}
				});
				this.errorDiv.validatorId = validation.id;
				var inner = new Element('div' , {
					'class': 'FV_error_display',
					'styles': {
						overflow: 'hidden'
					}
				});
				inner.setHTML(validation.errorMsg).inject(this.errorDiv);
				this.errorDiv.injectAfter(behind);
				return;
			}
			else if(this.errorDiv.validatorId != validation.id) {
				for(var i = 0; i < this.pendingErrors.length; i++) {
					if(this.pendingErrors[i] == validation) {
						return;
					}
				}
				this.pendingErrors[this.pendingErrors.length] = validation;			
			}
			
		}
		this.fields[this.fields.length] = field;
	},
	addValidation: function(id, validationArray) {
		var field = $(id);
		field.addValidations(validationArray);
	}
});

var FISFValidation = new Class({
	id: 0,
	errorMsg: null, 
	expects: null,
	option: null,
	displayAt: null,
	field: null,
	initialize: function(id, field_id, expects, option, errorMsg, displayAt) {
		this.field = $(field_id);
		this.id = id;
		this.expects = expects;
		this.option = option;
		this.errorMsg = errorMsg;
		if(this.errorMsg.trim() == '') this.errorMsg = 'expects ' + expects
		this.displayAt = displayAt;
		
		if(expects == 'zip') {
			if($(option)) {
				var setZipLength = function() {
					var state = $(option).getValue();
					var maxLength = 5;
					if(false) maxLength = 5;
					else if(state == "A") maxLength = 4;
					else if(state == "B") maxLength = 4;
					else if(state == "CH") maxLength = 4;
					else if(state == "CZ") maxLength = 5;
					else if(state == "D") maxLength = 5;
					else if(state == "DK") maxLength = 4;
					else if(state == "F") maxLength = 5;
					else if(state == "I") maxLength = 5;
					else if(state == "GB") maxLength = 8;
					else if(state == "L") maxLength = 4;
					else if(state == "NL") maxLength = 7;
					else if(state == "PL") maxLength = 6;
					else if(state == "SK") maxLength = 5;
					this.field.maxLength = maxLength;
					this.field.value = this.field.value.substr(0, maxLength);					
				}.bind(this);
				$(option).addEvent('change', function() {
					setZipLength();
				});
				setZipLength();
			}
			else {
				this.field.maxLength = 5;
			}
		}
		
	},
	showError: function(valid) {
		var obj = this.displayAt ? this.displayAt : this.field;
		obj.setMessage(this, valid);
	},
	validate: function() {
		var field = this.field;
		var tag = field.tagName.toString().toLowerCase().trim();
		var value = field.getValue().toString().trim();
		if(tag == 'input' && field.type == 'file') {
			value = field.value.trim();
		}
		if(tag == 'input' && field.type == 'checkbox') {
			if(this.expects != 'checked') {
				return false;	
			}
			else {
				return field.checked;
			}
		}
		else if(tag == 'input' && field.type == 'radio') {
			value = field.value.trim();
			if(this.expects == 'value' && value == this.option) {
				return field.checked;
			}
			else {
				return false;
			}		
		}
		
		
		switch(this.expects) {
			case 'url':
				return value.test(/^((https?|ftp):\/\/|www\.)[a-z0-9_\.ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½-]+\.[a-z]{2,4}$/i);
			case 'email':
				return value.test(/^.+@.+\.[a-z]{2,6}$/i);
			
			case 'integer':
				return value.test(/^\d+$/);
			case 'float':
				return value.test(/^(-?)\d+(\.\d+)?$/);
			case 'germanfloat':
				return value.test(/^(-?)\d+((,|\.)\d+)?$/);
			
			case 'notnull':
				return value.test(/./);
			case 'null':
				return value.test(/^$/);
			
			case 'preg':
				return value.test(this.option);
			
			case 'zip':
				var state = $(this.option);
				if(state) state = state.getValue();
				
				if(!state || state == 'D' || state == 'CZ' || state == 'F' || state == 'SK' || state == 'I') {
					return value.test(/^\d{5}$/);
				}
				else if(state == 'A' || state == 'B' || state == 'CH' || state == 'DK' || state == 'L') {
					return value.test(/^\d{4}$/);
				}
				else if(state == 'PL') {
					return value.test(/^\d{2}\-\d{3}$/);
				}
				else if(state == 'NL') {
					return value.test(/^\d{4} [A-Z]{2}$/g);
				}
				else if(state == 'GB') {
					return value.test(/^[A-Z](\d|\d{2}|\d[A-Z]|[A-Z]\d{1,2}|[A-Z]\d[A-Z]) \d[A-Z]{2}$/g);
				}
				else {
					return true;
				}
				
			case 'same':
				var other = $(this.option);
				if(!other) return true;
				if(other.validate && !other.validate()) return true;
				var otherValue = other.getValue().toString().trim();
				return (value == otherValue);
			
			case 'greater':
				if(!value.test(/^(-?)\d+(\.\d+)?$/)) return false;
				return (parseFloat(value) > this.option);
			case 'greater_equal':
				if(!value.test(/^(-?)\d+(\.\d+)?$/)) return false;
				return (parseFloat(value) >= this.option);
			case 'smaller':
				if(!value.test(/^(-?)\d+(\.\d+)?$/)) return false;
				return (parseFloat(value) < this.option);
			case 'smaller_equal':
				if(!value.test(/^(-?)\d+(\.\d+)?$/)) return false;
				return (parseFloat(value) < this.option);
			case 'minlength':
				return (value.length >= this.option);
			case 'maxlength':
				return (value.length <= this.option);
			case 'value':
				return (value == this.option);
			
			case 'file':
				return value.test(/./);
			case 'image':
				return value.test(/\.(jpe?g|png|gif)$/i);
			case 'imageswf':
				return value.test(/\.(jpe?g|png|gif|swf)$/i);
			case 'pdf':
				return value.test(/\.(pdf)$/i);
			case 'filesizemax':
				return true;
			
			case 'germandate':
				var s = value.split(/\./);
				if(s.length != 3) return false;
				var d = s[0];
				var m = s[1];
				var y = s[2];
				if(!d.test(/^\d+$/)) return false;
				if(!m.test(/^\d+$/)) return false;
				if(!y.test(/^\d+$/)) return false;
				if(y < 1000) return false;
				var date = new Date();
				date.setFullYear(y);
				date.setMonth(m-1, d);
				var d2 = parseInt(date.getDate());
				var m2 = parseInt(date.getMonth() + 1);
				var y2 = parseInt(date.getYear());
				if(y2 < 200) y2 += 1900;
				return (d2 == d && m2 == m && y2 == y);
			
			case 'function': 
				if(this.option) {
					return this.option(value, this);	
				}
				alert("FNF");
				return false;
		}
		return false;
	}
});


var onload = new Array();
var showResponse = false;


clearUp = function(obj) {
	while(obj.hasChildNodes()) {
		obj.removeChild(obj.firstChild);
	}
}
					
					


function sendform(theForm, values, onSuccess) {
	
	FX = new Fx.Style('saving', 'top', {duration:500});
	FX.set(5);

	/* var myCall = new Element('input');
    myCall.setProperties({'type': 'hidden', 'id': 'formhidden', 'name': 'jscall', 'value': 'ajax_' + phpfunc});
    $(theForm).adopt(myCall); */
  	
	var myCall = new Array();
	for (i = 0; i < values.length; i++) {
		myCall[i] = new Element('input');
	    myCall[i].setProperties({'type': 'hidden', 'name': 'arg[' + i + ']', 'value': values[i]});
		$(theForm).adopt(myCall[i]);
	}
	var now = new Date();
  	var additional = "&tc=" + now.getSeconds() + "." + now.getMilliseconds();
  	theForm.action = "/ajax.php?action=save" + additional;
    theForm.send({	method: 'post', 
    				evalScripts: true, 
    				onSuccess: function(response) { performActions(true, response); if(onSuccess) window[onSuccess](); }, 
    				onFailure: function(response) { performActions(false, response);}
    			});	
  	return false;
}

function refresh(form) {
	var docs = document.getElementsByClassName('FVerrorhappened');
	for(i = 0; i < docs.length; i++) docs[i].style.display = 'none'; 
	form.reset();
	return false;
}



function success(result) {
	alert(result);
}

	
function load(targetId, values, onSuccess) {
	
	FX = new Fx.Style('loading', 'top', {duration:500});
	FX.set(5);
	target = $(targetId);
	if(!target && targetId != null) {
		//$('statusMsgs').innerHTML = '<div style="color:red;"><b>ERROR: </b> Target ' + targetId + ' existiert nicht</div>' + $('statusMsgs').innerHTML;
		return;
 	}
 	
	var additional = 'action=load';
	if(values) {
		for (i = 0; i < values.length; i++) {
			additional += "&arg[]=" + values[i];
		}	
	}
	var now = new Date();
	additional += "&tc=" + now.getSeconds() + "." + now.getMilliseconds();
	
	var jsLoadSuccess = new Function('response', 'performActions(true, response, onSuccess);');
	var jsLoadError = new Function('response', 'performActions(false, response, onSuccess);');
	
	var myAjax = new Ajax('/ajax.php?' + additional, {
							method: 'get', 
							evalScripts: true, 
							onSuccess: function(response) { performActions(true, response, targetId); if(onSuccess) window[onSuccess](); }   
							});
	myAjax.request();
	
}

function performActions(status, response, targetId) {
	var statusMsg = response.match(/^\s*Status: (ERROR )?(.*?)(\n|$)/i);
	if(statusMsg) {
		response = response.replace(/^\s*Status: (ERROR )?(.*?)(\n|$)/i, '');
		if(statusMsg[1]) {
			status = false;
		}
		statusMsg = statusMsg[2];
	}
	else {
		statusMsg = '<i>no StatusMsg</i>';
	}
	
	if(showResponse) {
		$('response').innerHTML = response;	
	
		$('statusMsgs').innerHTML = 	'<div style="' + (status == true ? 'color:green;' : 'color:red;') + '">' 
								+ (status == true ? '<b>OK: </b> ' : '<b>ERROR: </b> ') + statusMsg + '</div>' 
								+ $('statusMsgs').innerHTML;
	}
	FX.stop();
	FX.start(-15);
	
	if(targetId != null) {	
		target = $(targetId);
		if(target instanceof HTMLInputElement) {
	 		target.value = response;
	 	}
	 	else {
	 		target.innerHTML = response;
	 	}
	}
}


String.prototype.trim = function () {
    var str = (this.replace(/\s+$/,""));
	return str.replace(/^\s+/,"");
  };


    	

/**
 * ReMoozHTML - Image Zoombox
 * 
 * 
 * Inspired by so many boxes and zooms
 * 
 * @version		1.0rc1
 * 
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 */

var allReMooz = new Array();

var ReMoozHTML = new Class({

	Implements: [Events, Options],

	options: {
		url: null,
		type: 'image',
		className: null,
		positionToCenter: false,
		dragging: true,
		shadow: true,
		resize: true,
		margin: 20,
		resizeFactor: 0.8,
		resizeLimit: false, //{x: 640, y: 640},
		hideSource: true,
		addClick: true,
		resizeOptions: {},
		resizeOpacity: 1,
		fxsOptions: {},
		generateTitle: null,
		showTitle: null,
		onBuild: $empty,
		onLoad: $empty,
		onOpen: $empty,
		onOpenEnd: $empty,
		onClose: $empty,
		onCloseEnd: $empty,
		evalScripts: false,
		width: 600,
		height: 400,
		dragButton: true,
		closeOthers: false
	},

	initialize: function(element, options) {
		this.element = $(element);
		this.setOptions(options);
		this.url = this.options.url || this.element.href || this.element.src;

		this.addEvent('onBlur', function() {
			this.focussed = false;
			this.box.removeClass('remo-box-focus').setStyle('z-index', ReMoozHTML.options.zIndex);
		}.bind(this));
		this.addEvent('onFocus', function() {
			this.focussed = true;
			this.box.addClass('remo-box-focus').setStyle('z-index', ReMoozHTML.options.zIndexFocus);
		}.bind(this));

		this.element.addClass('remo-zoom-in').addEvent('trash', this.destroy.bind(this));

		this.clickEvent = function(e) {
			this.open.delay(1, this);
			return false;
		}.bind(this);
		if(this.options.addClick) this.bindToElement();
	},

	destroy: function(unload) {
		if (this.box && !unload) this.box.destroy();
		this.box = this.boxFx = this.content = null;
		return null;
	},

	bindToElement: function(el) {
		($(el) || this.element).addEvent('click', this.clickEvent);
		return this;
	},

	getSourceCoordinates: function() {
		var coords = this.element.getCoordinates();
		if(!Client.Engine.ie) coords.left -= 9;
		else coords.left += 1;
		delete coords.right;
		delete coords.bottom;
		return coords;
	},

	open: function(e) {
		if(this.options.closeOthers) {
			for(i = 0; i < allReMooz.length; i++) {
				allReMooz[i].fireEvent('click');
			}
			allReMooz = new Array();
		}
		if (this.opened) return (e) ? this.close() : this;
		this.opened = true;
		if (!this.box) this.build();
		this.coords = this.getSourceCoordinates();
		this.coords.opacity = 0.7;
		this.boxFx.set(this.coords);
		this.box.setStyle('display', '').addClass('remo-loading');
		this.boxDrag = this.boxDrag || new Drag.Move(this.box, { // inits here because of safari
			'snap': 15,
			'onStart': function() {
				if (!this.focussed && !this.loading) {
					ReMoozHTML.focus(this);
					this.focusEvent = true;
				}
			}.bind(this),
			'onSnap': function() {
				this.dragging = true;
				this.box.addClass('remo-box-dragging');
			}.bind(this),
			'onComplete': function() {
				if (!this.dragging && !this.focusEvent) this.close();
				this.dragging = this.focusEvent = false;
				this.box.removeClass('remo-box-dragging');
			}.bind(this)
		}).detach();
		
		this.fireEvent('onLoad');
		this.loadImage();
		return this;
	},

	openEnd: function() {
		ReMoozHTML.open(this);
		this.zoomed = true;
		if (this.options.dragging) this.boxDrag.attach();
		this.fxs.start(0, 1);
		this.fireEvent('onOpenEnd');
	},

	close: function() {
		if (!this.opened) return this;
		this.fireEvent('onClose');
		this.opened = this.zoomed = false;
		ReMoozHTML.close(this);
		if (this.loading) {
			this.box.setStyle('display', 'none');
			return this;
		}
		this.boxDrag.detach();
		this.fxs.set(0);
		if (this.boxFx.timer) this.boxFx.clearChain();
		var vars = this.getSourceCoordinates();
		if (this.options.resizeOpacity != 1) vars.opacity = this.options.resizeOpacity;
		this.boxFx.start(vars).chain(this.closeEnd.bind(this));
		this.htmlContent.remove();
		return this;
	},

	closeEnd: function() {
		this.element.setStyle('visibility', 'visible');
		this.box.setStyle('display', 'none');
		this.fireEvent('onCloseEnd');
	},
	
	loadImage: function() {
		var thiss = this;
		var myAjax = new Ajax(this.url, {
							method: 'get', 
							evalScripts: this.options.evalScripts, 
							onSuccess: function(response) { thiss.setResult(response); },  
							onFailure: function(response) { thiss.setResult(""); }   
							});
		myAjax.request();
		
		
		return;
		this.loading = true;
		var loader = new Image();
		loader.onload = loader.onabort = loader.onerror = function(fast) {
			this.loading = loader.onload = loader.onabort = loader.onerror = null;
			if (!loader.width || !this.opened) {
				this.close();
				return;
			}
			var to = {x: loader.width, y: loader.height};
			if (!this.image)
			{
				 this.image = (Client.Engine.webkit419) ? new Element('img', {'src': loader.src}) : $(loader);
				 this.image.addClass('remo-img').inject(this.content);
			} else loader = null;
			this.openImage.create({
				'delay': (loader && fast !== true) ? 1 : null,
				'arguments': [to],
				'bind': this
			})();
		}.bind(this);
		loader.src = this.url;
		if (loader && loader.complete && loader.onload) loader.onload(true);
	},
	
	setResult: function(response) {
		this.loading = true;
		this.htmlContent = new Element('div');
		this.htmlContent.onload = this.htmlContent.onabort = this.htmlContent.onerror = function(fast) {
			this.loading = this.htmlContent.onload = this.htmlContent.onabort = this.htmlContent.onerror = null;
			var to = {x: this.options.width, y: this.options.height};
			this.image = (Client.Engine.webkit419) ? new Element('img', {'src': this.htmlContent.src}) : $(this.htmlContent);
			this.image.addClass('remo-img remo-txt').inject(this.content);
			this.openImage.create({
				'delay': (this.htmlContent && fast !== true) ? 1 : null,
				'arguments': [to],
				'bind': this
			})();
		}.bind(this);
		this.htmlContent.innerHTML = response.replace(/<script.*?>/gi, '<xscript><!--').replace(/<\/script.*?>/gi, "//--></xscript>");
		this.htmlContent.onload(true);
	},
	
	
	openImage: function(size) {
		if (this.options.hideSource) this.element.setStyle('visibility', 'hidden');
		this[(this.options.resize) ? 'zoomRelativeTo' : 'zoomTo'](size);
	},

	zoomRelativeTo: function(to) {
		var max = this.options.resizeLimit || {
			x: Client.getWidth() * this.options.resizeFactor,
			y: Client.getHeight() * this.options.resizeFactor
		};
		for (var i = 2; i--;) {
			if (to.x > max.x) {
				to.y *= max.x / to.x;
				to.x = max.x;
			} else if (to.y > max.y) {
				to.x *= max.y / to.y;
				to.y = max.y;
			}
		}
		return this.zoomTo({'x': to.x.toInt(), 'y': to.y.toInt()});
	},

	zoomTo: function(to) {
		var box = window.getSize();
		var pos = (!this.options.positionToCenter) ? {
			x: (this.coords.left + (this.coords.width / 2) - to.x / 2).toInt()
				.limit(box.scroll.x + this.options.margin, box.scroll.x + box.size.x - this.options.margin - to.x),
			y: (this.coords.top + (this.coords.height / 2) - to.y / 2).toInt()
				.limit(box.scroll.y + this.options.margin, box.scroll.y + box.size.y - this.options.margin - to.y)
		} :  {
			x: box.scroll.x + ((box.size.x - to.x) / 2).toInt(),
			y: box.scroll.y + ((box.size.y - to.y) / 2).toInt()
		};
		this.box.removeClass('remo-loading');
		this.fireEvent('onOpen');
		var vars = {'left': pos.x, 'top': pos.y, 'width': to.x, 'height': to.y};
		if (this.options.resizeOpacity != 1) vars.opacity = [this.options.resizeOpacity, 1];
		else this.box.setStyle('opacity', 1);
		this.boxFx.start(vars).chain(this.openEnd.bind(this));
	},

	generateTitle: function() {
		/*var title = this.options.title || this.element.getProperty('title');
		if (!title) return false;
		title = title.split(' :: ');
		var ret = [new Element('h4').setHTML(title[0])];
		if (title[1]) ret.push(new Element('p').setHTML(title[1]));
		return ret;*/
	},

	build: function() {
		this.box = new Element('div', {
			'class': 'remo-box',
			styles: {
				display: 'none',
				zIndex: ReMoozHTML.options.zIndex
			},
			events: {
				click: function() {
					if (this.zoomed) return true;
					this.close();
					return false;
				}.bind(this)
			}
		});
		if (this.options.className) this.box.addClass(this.options.className);
		this.boxFx = new Fx.Styles(this.box, $merge({
			duration: 400,
			unit: 'px',
			transition: Fx.Transitions.Quart.easeOut,
			wait: false
		}, this.options.resizeOptions));

		if (this.options.shadow) {
			var shadow = new Element('div', {'class': 'remo-bg-wrap'}).inject(this.box);
			['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'].each(function(dir) {
				new Element('div', {'class': 'remo-bg remo-bg-' + dir}).inject(shadow);
			});
			var shadowFx = new Fx.Style(shadow, 'opacity', {wait: false}).hide();
			this.addEvent('onOpen', shadowFx.start.pass(1, shadowFx))
				.addEvent('onClose', shadowFx.hide.bind(shadowFx));
		}
		this.content = new Element('div', {'class': 'remo-content remo-content-html'}).inject(this.box);

		var btn = new Element('a', {
			'class': 'remo-btn-close',
			events: {'click': this.close.bind(this)}
		}).inject(this.box);
		
		allReMooz.push(btn);
		
		if(this.dragging) {
			var btnM = new Element('a', {
				'class': 'remo-btn-move'			
			}).inject(this.box);
		}
		this.fxs = new Fx.Style(btn, 'opacity', $merge({
			duration: 300,
			wait: false
		}, this.options.fxsOptions));
		var title = (this.options.generateTitle || this.generateTitle).call(this);
		if (title) {
			this.title = new Element('div', {'class': 'remo-title'})
				.inject(new Element('div', {'class': 'remo-title-wrap'}).inject(this.box));
			new Element('div', {'class': 'remo-title-bg'}).setOpacity(0.8).inject(this.title);
			new Element('div', {'class': 'remo-title-txt'})
				[$type(title) == 'string' ? 'setHTML' : 'adopt'](title).inject(this.title);
		}
		this.fxs.element = $$(btn, this.title, this.dragging ? btnM : null);
		this.fxs.set(0);
		
		
		if(this.dragging) {
			new Drag.Move(this.box, { 'handle': btnM});
		}
		
		
		this.box.inject(document.body);
		
		
	}

});

ReMoozHTML.factory = $extend;

ReMoozHTML.factory({

	options: {
		zIndex: 41,
		zIndexFocus: 42,
		query: 'a.remooz',
		optionsField: 'rel',
		classOptions: {}
	},

	initialize: function(elements, options) {
		this.setOptions(options);
		return $$(elements || this.options.query).map(function(el) {
			var obj = el.getProperty(this.options.optionsField);
			if (obj && (obj = Json.decode(obj, true))) obj = $merge(obj, this.options.classOptions);
			return (el.$attributes.remooz = new ReMoozHTML(el, obj || this.options.classOptions));
		}, this);
	},

	stack: [],

	open: function(obj) {
		this.focus(obj);
	},

	close: function(obj) {
		var last = this.stack.length - 1;
		if (this.stack.indexOf(obj) == last) this.focus(this.stack[last - 1]);
		this.stack.remove(obj);
	},

	focus: function(obj) {
		var last = this.stack.getLast();
		if (!obj || last == obj) return;
		if (last) last.fireEvent('onBlur', [last], 10);
		obj.fireEvent('onFocus', [obj], 10);
		this.stack.remove(obj).push(obj);
	}

});

ReMoozHTML.factory(new Options);


function popup(filename, breite, hoehe, titel, windowname, scrolls) {
	oh = hoehe;
	ow = breite;
	
	var ret = screencenter(breite, hoehe);
	var breite = ret[0];
	var hoehe = ret[1];
	var l = ret[2];
	var t = ret[3];
	var scrolls = ret[4];
	
	newwindow = window.open(filename, windowname,"width="+breite+",height=" +hoehe+",screenX="+l+",screenY="+t+",left=" +l+",top="+t+",location=false,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");
	newwindow.focus();
	return false;
}

function screencenter(breite, hoehe) {
	if (navigator.userAgent.indexOf("Opera") != -1) 
	{
		var t = (screen.availHeight - hoehe) / 2 - 100;
		var yabstand = 200;
	}
	else {
		var t = (screen.availHeight - hoehe) / 2;
		var yabstand = 50;
	}
	var scrolls;
	if(breite > screen.availWidth - 50) 
	{
		scrolls = "yes";
		breite = screen.availWidth - 50;
	}
	if(hoehe > screen.availHeight - yabstand) 
	{
		scrolls = "yes";
		hoehe = screen.availHeight - yabstand;
		breite = breite / 1 + 20;
		t = 10;
	}
	var l = (screen.availWidth - breite) / 2;
	
	return new Array(breite, hoehe, l, t, scrolls);
}


/**
 * SqueezeBox - Expandable Lightbox
 * 
 * Allows to open various content as modal,
 * centered and animated box.
 * 
 * Dependencies: MooTools 1.2+ (09/2007)
 * 
 * Inspired by 
 *  ... Lokesh Dhakar	- The original Lightbox v2
 * 
 * @version		1.0rc2
 * 
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 */
var SqueezeBox = {

	presets: {
		size: {x: 600, y: 450},
		sizeLoading: {x: 200, y: 150},
		marginInner: {x: 20, y: 20},
		marginImage: {x: 150, y: 200},
		handler: false,
		target: null,
		closeWithOverlay: true,
		zIndex: 65555,
		overlayOpacity: 0.7,
		classWindow: '',
		classOverlay: '',
		disableFx: false,
		onOpen: $empty,
		onClose: $empty,
		onUpdate: $empty,
		onResize: $empty,
		onMove: $empty,
		onShow: $empty,
		onHide: $empty,
		fxOverlayDuration: 250,
		fxResizeDuration: 750,
		fxResizeTransition: Fx.Transitions.Quint.easeOut,
		fxContentDuration: 250,
		ajaxOptions: {}
	},

	initialize: function(options) {
		if (this.options) return this;
		this.presets = $merge(this.presets, options);
		this.setOptions(this.presets).build();
		this.listeners = {
			window: this.reposition.bind(this, [null]),
			close: this.close.bind(this),
			key: this.onKey.bind(this)
		};
		this.isOpen = this.isLoading = false;
		return this;
	},

	build: function() {
		this.content = new Element('div', {id: 'sbox-content'});
		this.btnClose = new Element('a', {id: 'sbox-btn-close', href: '#'});
		this.overlay = new Element('div', {
			id: 'sbox-overlay',
			styles: {display: 'none', zIndex: this.options.zIndex}
		}).inject(document.body);
		this.win = new Element('div', {
			id: 'sbox-window',
			styles: {display: 'none', zIndex: this.options.zIndex + 2}
		}).adopt(this.btnClose, this.content).inject(document.body);
		this.fx = {
			overlay: new Fx.Style(this.overlay, 'opacity', {
				duration: this.options.fxOverlayDuration,
				wait: false
			}).set(0),
			win: new Fx.Styles(this.win, {
				duration: this.options.fxResizeDuration,
				transition: this.options.fxResizeTransition,
				wait: false,
				unit: 'px'
			}),
			content: new Fx.Style(this.content, 'opacity', {
				duration: this.options.fxContentDuration,
				wait: false
			}).set(0)
		};
	},

	addClick: function(el) {
		return el.addEvent('click', function() {
			return !SqueezeBox.fromElement(this);
		});
	},

	fromElement: function(el, options) {
		this.initialize();
		this.element = $(el);
		this.setOptions($merge(this.presets, options || {}, (this.element && this.element.rel) ? Json.evaluate(this.element.rel) : {}));
		this.assignOptions();
		this.url = ((this.element) ? (this.options.url || this.element.getProperty('href')) : el) || '';
		if (this.options.handler) {
			var handler = this.options.handler;
			return this.setContent(handler, this.parsers[handler].call(this, true));
		}
		var res;
		for (var key in this.parsers) {
			if ((res = this.parsers[key].call(this))) return this.setContent(key, res);
		}
		return false;
	},

	assignOptions: function() {
		this.overlay.setProperty('class', this.options.classOverlay);
		this.win.setProperty('class', this.options.classWindow);
		if (Client.Engine.ie6) this.win.addClass('sbox-window-ie6');
	},

	close: function(e) {
		if (e) new Event(e).stop();
		if (!this.isOpen) return this;
		this.fx.overlay.start(0).chain(this.toggleOverlay.bind(this));
		this.win.setStyle('display', 'none');
		this.trashImage();
		this.toggleListeners();
		this.isOpen = null;
		this.fireEvent('onClose', [this.content]).removeEvents();
		this.options = {};
		this.setOptions(this.presets).callChain();
		return this;
	},

	onError: function() {
		if (this.image) this.trashImage();
		this.setContent('Error during loading');
	},

	trashImage: function() {
		if (this.image) this.image = this.image.onload = this.image.onerror = this.image.onabort = null;
	},

	setContent: function(handler, content) {
		if (!this.handlers[handler]) return false;
		this.content.setProperty('class', 'sbox-content-' + handler);
		this.applyTimer = this.applyContent.delay(this.fx.overlay.options.duration, this, this.handlers[handler].call(this, content));
		if (this.overlay.$attributes.opacity) return this;
		this.toggleOverlay(true);
		this.fx.overlay.start(this.options.overlayOpacity);
		this.reposition();
		return this;
	},

	applyContent: function(content, size) {
		this.applyTimer = $clear(this.applyTimer);
		this.hideContent();
		if (!content) this.toggleLoading(true);
		else {
			if (this.isLoading) this.toggleLoading(false);
			this.fireEvent('onUpdate', [this.content], 20);
		}
		this.content.empty()[['string', 'array', false].contains($type(content)) ? 'setHTML' : 'adopt'](content || '');
		this.callChain();
		if (!this.isOpen) {
			this.toggleListeners(true);
			this.resize(size, true);
			this.isOpen = true;
			this.fireEvent('onOpen', [this.content]);
		} else this.resize(size);
	},

	resize: function(size, instantly) {
		var sizes = window.getSize();
		this.size = $merge(this.isLoading ? this.options.sizeLoading : this.options.size, size);
		var to = {
			width: this.size.x, height: this.size.y,
			left: (sizes.scroll.x + (sizes.size.x - this.size.x - this.options.marginInner.x) / 2).toInt(),
			top: (sizes.scroll.y + (sizes.size.y - this.size.y - this.options.marginInner.y) / 2).toInt()
		};
		$clear(this.showTimer || null);
		this.hideContent();
		if (!instantly) {
			this.fx.win.start(to).chain(this.showContent.bind(this));
		} else {
			this.win.setStyles(to).setStyle('display', '');
			this.showTimer = this.showContent.delay(50, this);
		}
		return this.reposition(sizes);
	},

	toggleListeners: function(state) {
		var task = state ? 'addEvent' : 'removeEvent';
		this.btnClose[task]('click', this.listeners.close);
		if (this.options.closeWithOverlay) this.overlay[task]('click', this.listeners.close);
		document[task]('keydown', this.listeners.key);
		window[task]('resize', this.listeners.window);
		window[task]('scroll', this.listeners.window);
	},

	toggleLoading: function(state) {
		this.isLoading = state;
		this.win[state ? 'addClass' : 'removeClass']('sbox-loading');
		if (state) this.fireEvent('onLoading', [this.win]);
	},

	toggleOverlay: function(state) {
		this.overlay.setStyle('display', state ? '' : 'none');
		document.body[state ? 'addClass' : 'removeClass']('body-overlayed');
	},

	showContent: function() {
		if (this.content.$attributes.opacity) this.fireEvent('onShow', [this.win]);
		this.fx.content.start(1);
	},

	hideContent: function() {
		if (!this.content.$attributes.opacity) this.fireEvent('onHide', [this.win]);
		this.fx.content.set(0);
	},

	onKey: function(e) {
		switch (e.key) {
			case 'esc':
				this.close();
				break;
		}
	},

	reposition: function(sizes) {
		sizes = sizes || window.getSize();
		this.overlay.setStyles({
			left: sizes.scroll.x, top: sizes.scroll.y,
			width: sizes.size.x, height: sizes.size.y
		});
		this.win.setStyles({
			left: (sizes.scroll.x + (sizes.size.x - this.win.offsetWidth) / 2).toInt(),
			top: (sizes.scroll.y + (sizes.size.y - this.win.offsetHeight) / 2).toInt()
		});
		return this.fireEvent('onMove', [this.overlay, this.win, sizes]);
	},

	removeEvents: function(type){
		if (!this.$events) return this;
		if (!type) this.$events = null;
		else if (this.$events[type]) this.$events[type] = null;
		return this;
	},

	parsers: {
		'image': function(preset) {
			return (preset || this.url.test(/\.(jpg|jpeg|png|gif|bmp)$/i)) ? this.url : false;
		},
		'clone': function(preset) {
			if ($(this.options.target)) return $(this.options.target);
			if (preset || (this.element && !this.element.parentNode)) return this.element;
			var bits = this.url.match(/#([\w-]+)$/);
			return (bits) ? $(bits[1]) : false;
		},
		'url': function(preset) {
			return (preset || (this.url && !this.url.test(/^javascript:/i))) ? this.url: false;
		},
		'iframe': function(preset) {
			return (preset || this.url) ? this.url : false;
		},
		'string': function(preset) {
			return true;
		}
	},

	handlers: {
		'image': function(url) {
			var size, tmp = new Image();
			this.image = null;
			tmp.onload = tmp.onabort = tmp.onerror = (function() {
				tmp.onload = tmp.onabort = tmp.onerror = null;
				if (!tmp.width) {
					this.onError.delay(10, this);
					return;
				}
				
				var win = {x: window.getWidth() - this.options.marginImage.x, y: window.getHeight() - this.options.marginImage.y};
				size = {x: tmp.width, y: tmp.height};
				for (var i = 2; i--;) {
					if (size.x > win.x) {
						size.y *= win.x / size.x;
						size.x = win.x;
					} else if (size.y > win.y) {
						size.x *= win.y / size.y;
						size.y = win.y;
					}
				}
				size.x = size.x.toInt();
				size.y = size.y.toInt();
				this.image = $(tmp);
				this.image.setProperties({width: size.x, height: size.y});
				if(size.x) this.applyContent(this.image, size);
			}).bind(this);
			tmp.src = url;
			if (tmp && tmp.complete) tmp.onload();
			return (this.image) ? [this.image, size] : null;
		},
		'clone': function(el) {
			return el.clone();
		},
		'adopt': function(el) {
			return el;
		},
		'url': function(url) {
			this.ajax = new Ajax(url, this.options.ajaxOptions);
			this.ajax.addEvents({
				'onSuccess': function(resp) {
					this.applyContent(resp);
					this.ajax = null;
				}.bind(this),
				'onFailure': this.onError.bind(this)
			}).request.delay(10, this.ajax);
		},
		'iframe': function(url) {
			return new Element('iframe', {
				src: url,
				frameBorder: 0,
				width: this.options.size.x,
				height: this.options.size.y
			});
		},
		'string': function(str) {
			return str;
		}
	},

	extend: $extend
};

SqueezeBox.parsers.adopt = SqueezeBox.parsers.clone;

SqueezeBox.extend(Events.prototype).extend(Options.prototype).extend(Chain.prototype);

