////////////////////////////
dynamicNews = function(){
	try {
		var news_content = $$("div.news_content");
	} 
	catch(e) { return; }
	if (news_content==undefined) 
		return;
	var str = '<a href="#" class="icon back"><span>&laquo;</span></a>';
	for(var i=1, l=news_content.length;i<=l;i++){
		str += '<a href="#" '+((i==1)?'class="act"':'')+'>'+i+'</a>';
	}
	$$("div.news_navi")[0].innerHTML = str+'<a href="#" class="icon forward"><span>&raquo;</span></a>';
	
}
Event.observe(window, "load", function(){
	//dynamicNews();
});


function getBrowser() {
	if (!window.RegExp) return false;
	var ret={ name:'', version: 0 };
	var AGENTS = ["opera","msie","safari","firefox","netscape","mozilla"];
	var agent = navigator.userAgent.toLowerCase();
	for (var i = 0; i < AGENTS.length; i++) {
		var agentStr = AGENTS[i];
		if (agent.indexOf(agentStr) != -1) {
			var versionExpr = new RegExp(agentStr + "[ \/]?([0-9]+(\.[0-9]+)?)");
			var version = 0;
			if (versionExpr.exec(agent) != null) {
				ret.version = parseFloat(RegExp.$1);
				ret.name=agentStr;
				return ret;
			}
		}
	}
	return ret;
}

//////////////////////////////////////////////////
/////////       Cookiemanager      //////////////
CookieManager = Class.create();
CookieManager.prototype = {
	BROWSER_IS_IE: (document.all && window.ActiveXObject && navigator.userAgent.toLowerCase().indexOf("msie") > -1 && navigator.userAgent.toLowerCase().indexOf("opera") == -1),
	BROWSER_IS_OPERA: (navigator.userAgent.toLowerCase().indexOf("opera") != -1),
	initialize: function(options) {
		this.options = Object.extend({shelfLife: 600, userData: false}, options || {});
		this.cookieShelfLife = options.shelfLife;
		this.userDataForIE = options.userData;

		if (this.BROWSER_IS_IE && this.userDataForIE) {
			this.IE_CACHE_NAME = "storage";
			if ($(this.IE_CACHE_NAME) == null) {
				var div = document.createElement("DIV");
				div.id = this.IE_CACHE_NAME;
				document.body.appendChild(div);
			}
			this.store = $(this.IE_CACHE_NAME);
			this.store.style.behavior = "url('#default#userData')";
		}
	},
	getCookie: function(aCookieName) {
		var result = null;
		if (this.BROWSER_IS_IE && this.userDataForIE) {
			this.store.load(this.IE_CACHE_NAME);
			result = this.store.getAttribute(aCookieName);
		}
		else {
			for (var i = 0; i < document.cookie.split('; ').length; i++) {
				var crumb = document.cookie.split('; ')[i].split('=');
				if (crumb[0] == aCookieName && crumb[1] != null) {
					result = crumb[1];
					break;
				}
			}
		}

		if (this.BROWSER_IS_OPERA && result != null) {
			result = result.replace(/%22/g, '"');
		}
		return result;
	},
	setCookie: function(aCookieName, aCookieValue) {
		if (this.BROWSER_IS_IE && this.userDataForIE) {
			this.store.setAttribute(aCookieName, aCookieValue);
			this.store.save(this.IE_CACHE_NAME);
		}
		else {
			if (this.BROWSER_IS_OPERA) {
				aCookieValue = aCookieValue.replace(/"/g, "%22");
			}
			var date = new Date();
			date.setTime(date.getTime() + (this.cookieShelfLife*1000));
			var expires = '; expires=' + date.toGMTString();
			document.cookie = aCookieName + '=' + aCookieValue + expires + '; path=/';
		}
	},
	clearCookie: function(aCookieName) {
		if (this.BROWSER_IS_IE && this.userDataForIE) {
			this.store.load(this.IE_CACHE_NAME);
			this.store.removeAttribute(aCookieName);
			this.store.save(this.IE_CACHE_NAME);
		}
		else {
			document.cookie =	aCookieName + '=;expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/';
		}
	}
}

///////////////////////////////////////////////////
///////////////  Meldungen  //////////////////////

var cookiemanager = new CookieManager({shelfLife:10*60});

var NewsBox = Class.create();
NewsBox.prototype = {
	newsContainer: null,
	currentNews: 0,
	currentNewsObj: null,
	newsCount: 0,
	navBarObj: null,
	is_visible: true,
	mouseIsOver: false,
	menuButton: null,
	initialize: function() {
		try {
			this.newsContainer = $$(".news")[0];
		} catch(e) { return; }
		if (this.newsContainer==undefined) return;
		
		this.currentNewsObj = this.newsContainer.down(".news_content");
		this.newsCount = $$(".news .news_content").length;
		this.navBarObj = this.newsContainer.down(".news_navi");
		var me=this;
		var show_np=this.newsCount>1;
		$$(".news_navi a").each(function(no, i) {
			if (i==0 && show_np) 
				no.observe("click", function(){ me.showPrevious.apply(me,[]);});
			else if (i==me.newsCount+1 && show_np) 
				no.observe("click", function(){ me.showNext.apply(me,[]);});
			else 
				no.observe("click", function(){ me.showNews.apply(me,[i-1]);});
			no.href="javascript:void(0)";
		});
		if (this.newsCount>1) {
			this.newsContainer.down(".news_close a").observe("click", this.closeBox.bindAsEventListener(this));
		//	this.newsContainer.previous("a").observe("click", this.showBox.bindAsEventListener(this));
			new PeriodicalExecuter(this.showNextPE.bind(this), 8);
			this.newsContainer.observe("mouseover", this.checkMouse.bindAsEventListener(this));
			this.newsContainer.observe("mouseout", this.checkMouse.bindAsEventListener(this));
		}
		if (cookiemanager.getCookie("wb_news_off") == 1 && (typeof show_news == "undefined" || !show_news)) {
			this.is_visible=false;
			cookiemanager.setCookie("wb_news_off", 1);
		}
		else {
			this.is_visible=true;
			//this.newsContainer.up("li").addClassName("act");
			var me=this;
			$$(".a_subnavi li").each(function(subnav_obj, i){
				if (subnav_obj.innerHTML.indexOf("Meldungen")!=-1 && i==0) {
					subnav_obj.addClassName("act");
					me.menuButton=subnav_obj;
				}
			});
			Effect.BlindDown(this.newsContainer, {duration: 0.3});
		}
	},
	checkMouse: function(ev) {
		switch(ev.type) {
			case "mouseover": this.mouseIsOver=true; break;
			case "mouseout": this.mouseIsOver=false; break;
		}
	},
	showNextPE: function(pe) {
		if (!this.mouseIsOver) {
			this.showNext();
		}
	},
	showNext: function() {
		var nn= this.currentNews+1 >= this.newsCount ? 0 : this.currentNews+1;
		this.showNews(nn);
	},
	showPrevious: function() {
		var pn = this.currentNews-1 < 0 ? this.newsCount-1 : this.currentNews-1;
		this.showNews(pn);
	},
	showNews: function(num) {
		if (num==this.currentNews || num<0 || num>=this.newsCount) return;
		var newNews = this.newsContainer.down(".news_content", num).show();
		this.currentNewsObj.hide();
		newNews.show();
		//Effect.Fade(newNews,{from: 0.3, to: 1, duration: 0.5});
		this.currentNewsObj = newNews;
		
		this.navBarObj.down("a", this.currentNews+1).removeClassName("act");
		this.navBarObj.down("a", num+1).addClassName("act");
		this.currentNews=num;
	},
	closeBox: function() {
		//this.newsContainer.hide();
		if (!this.is_visible) return;
		this.is_visible=false;
		var me=this;
		Effect.BlindUp(this.newsContainer, {duration: 0.3, afterFinish:function(){
			me.menuButton.removeClassName("act");
		}});
		cookiemanager.setCookie("wb_news_off", 1);
	},
	showBox: function(ev) {
		Event.element(ev).blur();
		if (this.is_visible) this.closeBox();
		else {
			this.is_visible=true;
			this.menuButton.addClassName("act");
			Effect.BlindDown(this.newsContainer, {duration: 0.3});
			cookiemanager.setCookie("wb_news_off", 0);
		}
	}
}
var news_controller;
Event.observe(window, "load", function() {
dynamicNews();
	news_controller = new NewsBox();
	initTermine();
});

///////////////////////////////////
/////  St&#65533;cke-Akkordeon     //////

function MorphObject(el,rounds, startvalue, endvalue) {
	this.element=el;
	this.rounds=rounds;
	this.start_value=startvalue;
	this.end_value=endvalue;
	this.counter=0;
}

var MyMorph=Class.create();
MyMorph.prototype = {
	duration: 700,
	PI12: Math.PI/2,
	initialize: function() {
		this.stack=new Array();
		this.pe=new PeriodicalExecuter(this.execute.bind(this), 1/25);
	},
	addMorph: function(el, end_value) {
		this.stack.push( new MorphObject(el, Math.round(this.duration/(1000/25)), parseInt( el.getStyle("paddingTop")), end_value ));
	},
	execute: function(pe) {
		if (this.stack.length>0) {
			var pi12 = Math.PI/2;
			var finish_stack=[];
			this.stack.each(function(obj, i) {
				obj.counter++;
				// Sinuidale Bewegung
				var value = obj.start_value+ (Math.sin(pi12*( obj.counter/obj.rounds )) * (obj.end_value - obj.start_value));
				// Lineare Bewegung
				//var value=obj.start_value + (obj.counter/obj.rounds)*(obj.end_value-obj.start_value);
				if (obj.counter==obj.rounds) {
					value=obj.end_value;
					finish_stack.push(i);
				}	
				obj.element.setStyle({paddingTop: Math.round(value)+"px"});
			});
			if (finish_stack.length>0) {
				for(var i=finish_stack.length-1; i>=0; i--) {
					this.stack.splice(i,1);
				}
			}
		}
	}
}

var morphing = new MyMorph();
//////////////////////////

var tr_cur_active=false;
var tr_img_height=350;

function initTermine() {
	$$(".home .container h3").each(function(tc, i){
		if (i==0) {
			tc.addClassName("active");
			if (tc.getStyle("backgroundImage") != "none") {
				tc._oldHeight=tc.getHeight();
				tc.setStyle({paddingTop: tr_img_height - tc._oldHeight + "px"});
				tr_cur_active=tc;
			}
		}
		if (tc.getStyle("backgroundImage") != "none") {
			tc.observe("mouseover", openTermin);
		}
	});
}

function openTermin(ev) {
	var el=Event.element(ev);
	if (el.tagName.toLowerCase()!="h3") {
		try {
			el=el.up("h3");
		}
		catch(e) { return; }
	}
	if (tr_cur_active == el) return;
	if(tr_cur_active!==false && el != tr_cur_active) {
		closeTermin( tr_cur_active );
	}
	if (el._oldHeight==undefined) {
		el._oldHeight = el.getHeight();
	}
	el.addClassName("active");
	morphing.addMorph(el, tr_img_height-el._oldHeight);
	tr_cur_active=el;
}

function closeTermin(el) {
	el.removeClassName("active");
	morphing.addMorph(el, 0);
}


///////////////////////////////////////////
///////  Mitgleitende Navigation /////////

var Browser=getBrowser();

var ScrollNavigation = Class.create();
ScrollNavigation.prototype = {
	initialize: function() {
		this.nav_stack = [];
		this.pe = new PeriodicalExecuter(this.updateNavBoxes.bind(this), 1/25);
	},
	//getOffset: (Browser.name=="msie" && Browser.version < 8) ? Position.positionedOffset : Position.cumulativeOffset,
	getOffset: Position.cumulativeOffset,
	reinitialize: function() {
		Position.prepare();
		for (var index=0; index<this.nav_stack.length; index++) {
			var cont_box = this.nav_stack[index].nav_box;
			var offsets = this.getOffset(cont_box);
			this.nav_stack[index].top = Number(offsets[1]);
			//this.nav_stack[index].bottom = cont_box.getHeight()+offsets[1]-this.nav_stack[index].nav_box.getHeight();
		};
	},
	addNavigation: function (nav_box) {
		var nb = $(nav_box);
		Position.prepare();
		//var cont_box = nb.previous();
		var offsets = this.getOffset(nb);
		//this.nav_stack.push({top: Number(offsets[1])-18, bottom: cont_box.getHeight()+offsets[1]-nb.getHeight(), nav_box: nb});
		this.nav_stack.push({top: Number(offsets[1]-18),nav_box: nb});
		nb.makePositioned();
	},
	updateNavBoxes: function() {
		Position.prepare();
		this.nav_stack.each(function(navObj, index) {
			var navDiv = navObj.nav_box;
			var offsets = Position.cumulativeOffset(navDiv);
			var scroll_offset = Position.deltaY;
			//var tg_y = Math.max(navObj.top-36, Math.min( navObj.bottom-36, scroll_offset  )) - navObj.top;
			var tg_y = Math.max(navObj.top-36, scroll_offset ) - navObj.top;
			var cur_y = offsets[1]-navObj.top;
			var new_y = cur_y + (tg_y - cur_y)*0.3;
			navDiv.setStyle({top: Math.round(new_y)+"px"});
		});
	}
}

var NavBoxes;
function initNavigation() {
	NavBoxes = new ScrollNavigation();
	var regexp_str = (location.hash=="") ? location.href : location.href.substr(0, location.href.indexOf("#"));
	regexp_str += "\\#[\\w]{1,}";
	var regexp = new RegExp( regexp_str );
	$$("a[href!='#']").each(function(a){
		if (a.href.search( regexp )!=-1) { 
			Event.observe(a, "click", initScrollTo, true);
		}
	});
	
	if (!(Browser.name == "msie" && Browser.version < 6)) {
		$$(".flying_menu").each(function(a){
			NavBoxes.addNavigation( a );
		});
	}
}

//////////////////////////////////////
/////// Soft-Anchor Scroll //////////

var scroll_target, scroll_pe, js_scrolling=false;
function initScrollTo(event) {
	try {
		var anchor_name = Event.element(event).readAttribute("href").substr(1);
		var anchor_element = $$("[name="+anchor_name+"]").find(function(e){
			if (e.readAttribute("name")==anchor_name) return true;
			return false;
		});
		if (typeof anchor_element == "undefined") {
			anchor_element = $(anchor_name);
			if (typeof anchor_element == "undefined") {
				throw new Error("Anker nicht gefunden");
			}
		}
	}
	catch(e) { return; }
	
	//scroll_target = (Browser.name=="msie" && Browser.version < 8) ? Position.positionedOffset($(anchor_element))[1] : Position.cumulativeOffset($(anchor_element))[1];
	scroll_target = Position.cumulativeOffset($(anchor_element))[1];
	scroll_target += (Prototype.Browser.IE) ? 5 : 0;
	
	js_scrolling = true;
	var y_add = 0;
   scroll_pe = new PeriodicalExecuter(function(s_pe){
   	Position.prepare();
		var diff_y = scroll_target-Position.deltaY;
		var raw_add=diff_y*0.25;
		var my_y_add = Math.round(raw_add + y_add);
		y_add = raw_add - Math.round(my_y_add);
		
		if ( Math.abs(raw_add)<1) {
			window.scrollTo(Position.deltaX, scroll_target);
			js_scrolling=false;
			s_pe.stop();
			return;
		}
		window.scrollTo(Position.deltaX, Position.deltaY+my_y_add);
		
	}, 1/25);
	Event.element(event).blur();
	// vielleicht unn&#65533;tig, da capture beim INIT aktiviert ist
	Event.stop(event);
}
function stopJSScroller(event) {
	if (js_scrolling) {
		js_scrolling=false;
		scroll_pe.stop();
	}
}

Event.observe(window, "load", initNavigation);
Event.observe(document, "mousedown", stopJSScroller);
Event.observe(document, "keydown", stopJSScroller);
Event.observe(document, "DOMMouseScroll", stopJSScroller);

//////////////////////////////////////
///////  Galerie-Function ///////////

var Gallery = Class.create();
Gallery.prototype = {
	galContainer: null,
	currentPic: 0,
	lastPic: null,
	currentLayer: 0,
	picsCount: 0,
	layer: [],
	navBarObj: null,
	preloadedPics: [],
	pictures: [],
	loading: false,
	mouseIsOver: false,
	initialize: function(galCont) {
		this.galContainer = galCont;
		this.layer=[];
		this.pictures=[];
		this.layer[0]=this.galContainer.down("img");
		this.layer[0].setStyle({position: "absolute", zIndex: "0"});
		// zweites Bild f&#65533;r &#65533;berblendung initialisieren
		if (!this.layer[0].id) {
			this.layer[0].id = "galpic_"+Math.random();
		}
		new Insertion.After(this.layer[0].id, "<img id='"+this.layer[0].id+"_1' src='"+this.layer[0].src+"' alt='' style='position:absolute; display:none;' />");
		this.layer[1] = $(this.layer[0].id+"_1");

		this.navBarObj = this.galContainer.down(".block_navi");
		var me=this;
		this.picsCount = this.navBarObj.immediateDescendants().length-2;
		this.navBarObj.immediateDescendants().each(function(no, i) {
			if (no.classNames().toArray().indexOf("back") != -1)
				no.observe("click", function(){ me.showPrevious.apply(me,[]);});
			else if (no.classNames().toArray().indexOf("forward") != -1) 
				no.observe("click", function(){ me.showNext.apply(me,[]);});
			else {
				me.pictures.push({pic: no.href, txt: no.readAttribute("alt")});
				no.observe("click", function(){ me.showPic.apply(me,[i-1]);});
			}
			no.href="javascript:void(0)";
		});
		
		if (this.picsCount>1) {
			this.startPE(false);
			this.galContainer.observe("mouseover", this.checkMouse.bindAsEventListener(this));
			this.galContainer.observe("mouseout", this.checkMouse.bindAsEventListener(this));
		}
		this.pictures.each(function(pic,i){
			me.preloadedPics[i]=new Image();
			me.preloadedPics[i].src = pic.pic;
		});
	},
	startPE: function(restart) {
		if (restart) this.pe.stop();
		this.pe = new PeriodicalExecuter(this.PE_showNext.bind(this), 8);
	},
	checkMouse: function(ev) {
		switch(ev.type) {
			case "mouseover": this.mouseIsOver=true; break;
			case "mouseout": this.mouseIsOver=false; break;
		}
	},
	PE_showNext: function(pe) {
		if (!this.mouseIsOver) {
			this.showNext();
		}
	},
	showNext: function() {
		var nn= this.currentPic+1 >= this.picsCount ? 0 : this.currentPic+1;
		this.showPic(nn);
	},
	showPrevious: function() {
		var pn = this.currentPic-1 < 0 ? this.picsCount-1 : this.currentPic-1;
		this.showPic(pn);
	},
	
	showPic: function(num) {
		if (num==this.currentPic || num<0 || num>=this.picsCount || this.loading) return;
		this.startPE(true);
		this.lastPic = this.currentPic;
		this.currentPic=num;
		if (this.preloadedPics[num]==undefined) {
			this.preloadedPics[num]= new Image();
			this.preloadedPics[num].src = this.pictures[num].pic;
			this.loading=true;
			Event.observe(this.preloadedPics[num], "load", this.displayLayer.bindAsEventListener(this));
		}
		else if (this.preloadedPics[num].complete) {
			this.displayLayer();
		}
		else {
			Event.observe(this.preloadedPics[num], "load", this.displayLayer.bindAsEventListener(this));
			this.loading=true;
		}
		this.navBarObj.down("a", this.lastPic+1).removeClassName("act");
		this.navBarObj.down("a", num+1).addClassName("act");
	},
	displayLayer: function(ev) {
		var new_layer = this.currentLayer==0 ? 1 : 0;
		this.layer[new_layer].src = this.preloadedPics[this.currentPic].src;
		this.layer[new_layer].alt = this.pictures[this.currentPic].txt;
		if (new_layer==1) 
			Effect.Appear( this.layer[1], {duration: 0.3});
		else 
			Effect.Fade( this.layer[1], {duration: 0.3});
		
		this.currentLayer=new_layer;
		this.loading=false;
		
		try { 
			this.galContainer.down(".gallery_subline p").update(this.pictures[ this.currentPic ].txt);
		}
		catch(e) { }
	}
}

Event.observe(window, "load", function(){
	$$(".gallery").each(function(gal) {
		new Gallery( gal );
	});
});

//////////////////////////
/// Development Tools  //
////////////////////////
var tracedepth=0;var max_trace_depth=1;function debug(msg){if(debug.arguments.length==2){msg="<textarea rows=10 cols=20 style='width:600px;height:360px'>"+msg.escapeHTML()+"</textarea>";}try{if(typeof w=="undefined"||w.closed){w=window.open('','w','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=640,height=400');w.moveTo(screen.availWidth-640,0);}w.document.write(msg+"<br>");}
catch(e){try{$('debug_container').innerHTML+=msg+"<br>";}catch(e){var div=document.createElement('div');div.id='debug_container';div.innerHTML=msg+'<br />';document.body.appendChild(div);}}}function trace(o){var out="";var nofunctions=(trace.arguments.length>1&&trace.arguments[1]);var do_return=(trace.arguments.length>2&&trace.arguments[2]);try{for(z in o){try{if(o[z]!=""&&o[z]!=null)if(z=="innerHTML"||z=="outerHTML")out+=z+" = [..HTML-Code..]; <br>\n";
if(typeof o[z]=="function"&&nofunctions){continue;}if(typeof o[z]=="object"){out+=z+" : {<div style='margin-left: 20px'>";if(++tracedepth>max_trace_depth||z.indexOf('parent')!=-1||z.indexOf('own')!=-1)out+=" [ object ] ";else out+=trace(o[z],nofunctions,true);tracedepth--;out+="</div>}<br>";}else out+=z+" = "+o[z]+"; <br>";}catch(e){out+="<i>Fehler in "+z+": "+e+"</i><br />\n";}}}catch(ee){out+="<b>Fatal Error in tracing: "+ee+"</b>";}
if(do_return)return out;else debug(out)}




