// http://bit.ly/ishiv | WTFPL License
window.innerShiv=function(){function h(c,e,b){return/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i.test(b)?c:e+"></"+b+">"}var c,e=document,j,g="abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video".split(" ");return function(d,i){if(!c&&(c=e.createElement("div"),c.innerHTML="<nav></nav>",j=c.childNodes.length!==1)){for(var b=e.createDocumentFragment(),f=g.length;f--;)b.createElement(g[f]);b.appendChild(c)}d=d.replace(/^\s\s*/,"").replace(/\s\s*$/,"").replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/(<([\w:]+)[^>]*?)\/>/g,h);c.innerHTML=(b=d.match(/^<(tbody|tr|td|col|colgroup|thead|tfoot)/i))?"<table>"+d+"</table>":d;b=b?c.getElementsByTagName(b[1])[0].parentNode:c;if(i===!1)return b.childNodes;for(var f=e.createDocumentFragment(),k=b.childNodes.length;k--;)f.appendChild(b.firstChild);return f}}();

/**
 * jquery plugins
 */
/* color plugin, see http://stackoverflow.com/questions/190560/jquery-animate-backgroundcolor */
(function(d){d.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(f,e){d.fx.step[e]=function(g){if(!g.colorInit){g.start=c(g.elem,e);g.end=b(g.end);g.colorInit=true}g.elem.style[e]="rgb("+[Math.max(Math.min(parseInt((g.pos*(g.end[0]-g.start[0]))+g.start[0]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[1]-g.start[1]))+g.start[1]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[2]-g.start[2]))+g.start[2]),255),0)].join(",")+")"}});function b(f){var e;if(f&&f.constructor==Array&&f.length==3){return f}if(e=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(f)){return[parseInt(e[1]),parseInt(e[2]),parseInt(e[3])]}if(e=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(f)){return[parseFloat(e[1])*2.55,parseFloat(e[2])*2.55,parseFloat(e[3])*2.55]}if(e=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(f)){return[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]}if(e=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(f)){return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)]}if(e=/rgba\(0, 0, 0, 0\)/.exec(f)){return a.transparent}return a[d.trim(f).toLowerCase()]}function c(g,e){var f;do{f=d.curCSS(g,e);if(f!=""&&f!="transparent"||d.nodeName(g,"body")){break}e="backgroundColor"}while(g=g.parentNode);return b(f)}var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]}})(jQuery);
/* isChildOf */
(function($) {$.fn.isChildOf = function(exp){return $(this).parents().filter(exp).length>0;};}(jQuery));

window.log=function(){
 
	if (site && site.ie7) {
		if (!$('.log').length) {
			$('<textarea class="log">').appendTo($('body')).html('');
		}
		var text = arguments[0];
		$('.log').html( $('.log').html() + text + '<br>');
	}
	log.history=log.history||[];log.history.push(arguments);if(this.console){console.log(Array.prototype.slice.call(arguments))}
};
 
window.rmb = window.rmb || {};

/**
 * Stops an event.
 * @param e The event
 * @returns false
 */
var prevent = function(e) {
	e.preventDefault();
	e.stopPropagation();
	return false;
};

/**
 * Reads or sets the hash value. If no value is passed, the current has is returned.
 * @param value (optional)
 * @returns Current hash (if no value was passed)
 */
var hash = function(value) {
	if (value!==undefined && value!==null) {
		if (value.charAt(0)=='/') {
			value = value.substr(1,value.length);
		}
		window.location.href = '#/'+value;
	}
	else {
		var hash = window.location.hash;  
		return hash.replace('/','').replace('#','');
	}
};
 
/**
 * site object
 */
 
var site = {
		
	options: {
		ssInterval: 8000,
		ssTransitionDuration: 3000,
		homeMaxChars: 150
	},
	
	
	/* colors used for the site background (animated color tweens use these values */ 
/*	bgcolors: {
		blau: '#dee7ec',
		olive: '#ebe6d8',
		bordeaux: '#e0d6d7',
		orange: '#f8ece8',
		grau: '#dfdfe0'
	},*/
	bgcolors: {
		grau: '#d9d9d9',
		olive: '#f3f0e9',
		orange: '#f7ece8',
		blau: '#dee7ec',
		bordeaux: '#e0d6d7'
	},
	navbgcolors: {
		grau: '#69696b',
		olive: '#a58a47',
		orange: '#cd6758',
		blau: '#6692ab',
		bordeaux: '#6e4146'
	},
		 
	defaultTheme: 'blau',
	
	el: null,
	overlay: null,
	errors: null,
	error: function(msg) {
		!this.errors ? this.errors=[] : null;
		this.errors.push(msg);
	},
	init: function() {
	 
    
		this.ie7 = $.browser.msie && parseFloat($.browser.version,10) < 8;
		if(this.ie7) {
			$('body').addClass('ie7');
		}
		$.ajaxSetup ({  
		    cache: false  
		});
		
		$('.intro .skipmessage').hide();
		
		site.el = $('.site'); 
		// initialize themes
		site.el.theme();
		
	 
		$('body').addClass('scripted'); 	
		$('.overlay').css({opacity:0, display:'block'})
		 
		if (IS_IPAD) {
			$('body').addClass('ipad');
		}
  
		$('.nav > ul').addClass('l1');
		$('.nav > ul > li > ul').addClass('l2');
		$('.nav ul ul ul').addClass('l3'); 
		
		//---------------------------------------------------
		// ALL NAVIGATON LINKS
		//---------------------------------------------------
 
	
		
		site.convertLinks();

		$('.nav a').each(function() { 
			var href = $(this).attr('href');
			if (href) {   
				//$(this).replacetext();
				if( $(this).attr('data-width')) {
					$(this).width($(this).attr('data-width'));
				}
			}
		}); 
		$('.vnav a.title').each(function() {$(this).replacetext();})

		$('.vnav').wrapInner('<div class="vnav-inner">');  
		

		var hnav = $('.hnav')[0]; 
		this.hNavMenu = new rmb.HNavMenu(hnav); 
		 
		var vnav = $('.vnav')[0]; 
		this.vNavMenu = new rmb.VNavMenu(vnav); 
		
		
		
		//---------------------------------------------------
		// VERTICAL NAVIGATON LINKS
		//---------------------------------------------------
 
		//$('.vnav').vNavSubmenu();
		
		$('.vnav .l2 > li > a').each(function() {
			var l3 = $(this).parent().find('.l3');
			var hasSub = l3.length > 0 && !l3.hasClass('tabbed');
 
			$(this).closest('li').addClass(hasSub ? 'has-submenu' : 'no-submenu');
			//$(this).vNavHilight();
			if (hasSub) {
				if (IS_IPAD) {
					$(this).unbind();
					this.addEventListener('touchstart', function() {
						//$('.vnav').vNavSubmenu('show', this);
					}, false);
				} 
			}
		});
	  
		$(document).pngFix(); 

	
		 
		
		/* create element for bg colors */
		site.el.before($('<div class="bgcolor">'));
		site.layout();
		site.resize();
		//site.resize();
		$(window).bind('resize', site.resize);
		
		site.emailLinks();
		 
		$('.pages').before($('<div class="vnav-bgfill">'));
		
		// hash navigation
		$(window).hashchange(site.onHashChange);
		$('.nav a').live('click', function() { 
			if ($(this).attr('href') == '#/'+hash()) {
				site.loadContent($(this).attr('data-href'));
			}
		})
 
		// make large titles unklickable
		$('a.title').unbind().click(function(e) {
			return prevent(e);
		});
 
		
		if (swfobject.hasFlashPlayerVersion("9") && !hash()) { 
			site.showIntro();
		}
		else {
			site.hideIntro();
		}
		
		$('.title.rmb').click(function(e) {
			//if (e.shiftKey) {
				site.loadAdmin();
			//}
		})
		
		$(window).hashchange(); 
		
		$('<a class="admin-login">Login</a>').appendTo($('body')).click(site.loadAdmin);
		
		$('.site').css('visibility', 'visible'); 
		/*
		if (location.href.indexOf('192.168') > -1 || location.href.indexOf('localhost') > -1) {
			$('<script>')
			.attr('src', 'https://getfirebug.com/firebug-lite.js')
			.appendTo(document.body);
		}
		*/
		
		
		// IE7 fix:
		 
		if (this.ie7) {
			$(document).bind('mousedown', function(e) {
				//alert($(e.target).isChildOf('.l3')+', '+$(e.target).closest('a').attr('data-path'))
				if ($(e.target).isChildOf('.l3')) {
					hash($(e.target).closest('a').attr('data-path'))
				}
			});

			$(".chzn-container").live('mouseenter', function(){
			      $('.chzn-container').css('zIndex',1);
			      $(this).closest('.chzn-container').css('zIndex',100);
			  });
		}
		 
		
		
		if ($.cookie('login')=='true') {
			this.loadAdmin();
		}
		 
	}, 
	loadAdmin: function() {
		//$.getScript('js/rmb.admin.js');
		$('<script>')
		.attr({
			type: 'text/javascript',
			src: 'js/admin/rmb.admin.js'
		})
		.appendTo($('head'))
	},
	 
	layout: function() {
		
		/*
		$('.reflect').wrapInner('<span>').wrapInner('<div class="reflections">');
		$('.reflect span').vflection({
		    color:'black', 
		    parent: 'div',
		    height: 20,
		    darkness: 20,
		    opacity: 20
		});
		*/

		site.saturation();
		
		$('.home h2').html('<img src="img/home-aktuelles.png">')
		
		$('.square.content').each(function() {
			if ($(this).find('.inner').length === 0) {
				$(this).wrapInner('<div class="inner">');
			}
		});
		
		/*$('.image-holder:eq(0)').addClass('first');*/
		$('section.first').removeClass('first');
		$('section:eq(0)').addClass('first');
		
		$('select').chosen();
		
		site.hilightNavLink();
		
		if ($.browser.msie) {
			
			var themeName = site.getThemeByUrl(location.href);
			if ($.fn.ie_roundedbox) { $('.rounded').ie_roundedbox({theme:themeName}); }
			if ($.fn.ie_imagebox) { $('.imagebox').ie_imagebox({theme:themeName}); }
		}
		
		$('.layout.links li').each(function() {
			var url = $(this).find('a').attr('href');
		 
			$(this).find('.imagebox')
				.css('cursor', 'pointer')
				.click(function() {
					$(this).closest('li').find('a').click();
				})
		})
		
		if (hash() != 'home' && hash() != '') {
			site.footerLinks();
			site.headerLinks();
		}
		/*
		if ($('.layout > .header').next().hasClass('image-holder')) {
			$('.layout').addClass('large-image');
		}
		*/
		if ($.fn.fixBoxModel) {
			$('*').fixBoxModel();
		}
		 
		$('[data-height]').each(function() {
			$(this).css('height', $(this).attr('data-height'));
		});
	},
	parseInt: function(n) {
		var r = parseInt(n,10); 
		return isNaN(r) ? 0 : r;
	},
	
	getLayoutHeight: function() {
		
		
		
		$('.layout').css('height','auto');
		var lh = $('.layout').outerHeight();
	 
		var h = 0;		
		$('.layout > *').each(function() {
			var $t = $(this);   
			h += $t.outerHeight() + site.parseInt($t.css('margin-bottom')); 
		});
 
		h += $('.pages').position().top;
		//h += $('.layout .header').outerHeight();
		//h += $('.layout .footer').outerHeight();
		
		return Math.max(lh,h);
	},
	resize: function() { 
		var h = Math.max(
			$(window).height(), 
			Math.max(
				$('.vnav').height(), 
				site.getLayoutHeight()
			)
		); 
		//log(h);
		var bgFillHeight ;
		if (site.slideshowActive) { 
			h = 1449;
			$('.vnav-bgfill').hide();
			bgFillHeight = h; 
		}
		else {
			bgFillHeight = null;
			$('.vnav-bgfill').show();
		}
	 
		if (site.ie7) {
			$('body, .site, .layout, .bgcolor').css({
				minHeight:h,
				height:'auto!important',
				height:h
			});
		}
		$('body, .site, .layout, .bgcolor').height( h );  
		$('.vnav-bgfill').height( bgFillHeight || Math.max($('.vnav-inner').height(), h+25) )

		//log( '-> ' +( bgFillHeight || Math.max($('.vnav-inner').height(), h+25) ) );
 
	},
	getThemeByUrl: function(url) {
		
		var path;
		if (url.indexOf('#') != -1) {
			path = url.split('#')[1];
		}
		else
		if (url.indexOf('?p=') != -1) {
			path = url.split('?p=')[1];
		}
		if (!path) {
			return null;
		}
		 
		var result = null;
		$('a').each(function() {
			if (result) return; 
			if ($(this).attr('data-path') == path) { 
				result = $(this).attr('data-theme');
				//log('result found', this)
			}
		})
		//log('-->', result)
		return result;
	},
	/**
	 * Findet den link in der navigation, der zur einer bestimmten Seite führt
	 * @param path oder url
	 * @return jQuery Objekt des links oder null
	 */
	getNavByHref: function(href) {
		var result = null;
		$('.nav a').each(function() {
			if (href.indexOf( $(this).attr('href') ) != -1 || href.indexOf( $(this).attr('data-href') )!=-1 || href.indexOf( $(this).attr('data-path') )!=-1) {
				result = $(this);
			}
		})
		return result ? $(result[0]) : null;
	}, 
	emailLinks: function() {
		$('a.email').each(function() {
			var email = $(this).text().replace(' at ','@');
			$(this).html(email/*.replace('RMB','<b>RMB</b>')*/).attr('href','mailto:'+email);
		});
	},
	/* scrolls page to top */
	top: function(e) { 
		$('html, body').animate({ scrollTop: 0 }, 'slow');
		if (e) {
			return prevent(e);
		}
	},
	getSectionName: function() { 
		if ($('.header h2').length) {
			return $('.header h2').text();
		} 
		
		return '';
	},
	headerLinks: function() {
		if ($('.layout').attr('data-page')) {
			$('h2.current-page').remove();
			$('.header h2')
				.css('cursor','pointer')
				.click(function() {
					hash( hash().substr(0, hash().lastIndexOf('/')) );
				})
				.after(
					$('<h2 class="current-page">'+$('.layout').attr('data-page')+'</h2>')
				);
		}
		else {
			$('h2.current-page').remove();
		}
		
	},
	footerLinks: function() {
		$('.footer').remove();
		var footer = $('<div class="footer">');
		
		footer.append(
			$('<div class="links">')
			.append($('<h3>' + site.getSectionName() + '</h3>'))
		);
		
		var nav = site.getNavByHref(location.href);
		
		if (nav) { 
			var ul = $('<ul>');
		 
			if (nav.isChildOf('.has-submenu')) {
				nav.parent().find('.l3 a').each(function() { 
					ul.append($('<li><a href="'+$(this).attr('href')+'">'+$(this).attr('data-text')+'</a></li>'))
				});
			}
			 
			if (nav.isChildOf('.l3')) {
				nav.closest('.l3').find('a').each(function(i) { 
					
					var li = $('<li>'); 
					var a = $('<a>')
					.attr('href', $(this).attr('href'))
					.text($(this).attr('data-text'))
					.appendTo(li);
					if (i%3==2) {
						li.addClass('last')
					}
					if ('/'+hash() == $(this).attr('data-path')) {
						a.addClass('active')
					}
					ul.append(li); 
				});
			}
			if (ul.find('li').length) {
				footer.find('.links').append(ul)
			}
		}
		footer.append($('<a class="top" href="">NACH OBEN</a>').click(site.top));
 
		if (ul && ul.find('li').length == 0) { 
			footer.find('h3').empty()
		}
		footer.appendTo($('.layout'));
		
		site.resize();
	},
	// TODO: try..catch rauswerfen. Fehler tritt wohl auf wenn kein hash/navlink vorhanden ist
	hilightNavLink: function() {
		var navlink = $('a[data-path="/'+hash()+'"]');
		
		if (navlink.isChildOf('.l3')) {
			//navlink.closest('.has-submenu').find('a:eq(0)').vNavHilight('active');
			var parentLink = navlink.closest('.has-submenu').find('a:eq(0)');
			$('.vnav a').each(function() {
				 if (this.navitem && this != navlink[0] && this != parentLink[0]) {
					 this.navitem.unlock();
				 }
			}); 
			try {
				parentLink[0].navitem.lock();
			} catch(e) {}
		} else {
			
			$('.vnav a').each(function() {
				 if (this.navitem && this != navlink[0]) {
					 this.navitem.unlock();
				 }
			});
			
			try {
				navlink[0].navitem.lock();
			} catch(e) {}
			//navlink.vNavHilight('active');
		}
		
		$('.hnav a').removeClass('active');
		if (navlink.isChildOf('.hnav')) {
			navlink.addClass('active')
		} 
		if (!hash() && !navlink.length) {
			$('.hnav a:first').addClass('active');
		}
	},
	onHashChange: function() {
		
		var _hash = hash(); 
		if (_hash == 'admin') { 
			site.loadAdmin();
			hash(site.currentHash);
			return; 
		}
		
		if (!site.currentHash) {
			site.currentHash = '';
			site.currentSection = '';
			site.currentSubSection = '';
		} 
		
		if (_hash == 'home' || !_hash) { 
			if (!site.introActive) { 
				site.showSlideShow(); 
			} 
		}else { 
			site.hideSlideShow();
		}
		if (!_hash) {
			return;
		}
		
		site.hilightNavLink();
//		$('.vnav')[0].navmenu.submenu.hide();
//		$('.vnav').vNavSubmenu('hide');	
		
		var navlink = $('.nav a[data-path="/'+_hash+'"]');

		$('.site').theme('load', navlink.attr('data-theme'));	
		site.loadContent(navlink.attr('data-href'));
		
		$('.vnav-bgfill').animate({backgroundColor:site.navbgcolors[navlink.attr('data-theme')]}, 600); 
		 
		var section = _hash.split('/')[0];
		var subSection = _hash.split('/').length==3 ? _hash.split('/')[1] : undefined;
		$('body')
			.removeClass('page-'+site.currentHash.replace(/\//g,'-'))
			.addClass('page-'+_hash.replace(/\//g,'-')) 
			.removeClass('section-'+site.currentSection)
			.addClass('section-'+_hash.split('/')[0])
			.removeClass('sub-'+site.currentSubSection)
			.addClass(subSection ? 'sub-'+subSection : '')
			
		site.currentSection = section;	
		site.currentSubSection = subSection;
		site.currentHash = _hash;
	},

	showIntro: function() {
		if ($.cookie('intro-passed')) {
			return this.hideIntro();
		}
		$.cookie('intro-passed', true);
		var swf = "swf/rmb_intro_110916.swf";	
		var flashVars = { 
		};		
		var attributes = {
			id:"introswf" ,
			name:"introswf" ,
			allowScriptAccess:"always"
		};		 
		var params = {
			wmode: "transparent"
		}  
		$(document).bind('mousedown.intro', function() {
			site.hideIntro();
		}); 
		$(window).bind('resize.intro', function() {
			var winWidth = $(window).width();
			var siteWidth = $('.site').width();
			var swfWidth = 1400;
			$('.introbg').width(winWidth);
			$('.introbg').height($('img.blau').height());
			
			if (winWidth > siteWidth) {
				$('.intro object').css({
					left: (winWidth-swfWidth)/2 + 24
				});
			}
			else {
				$('.intro object').css({
					left: (siteWidth-swfWidth)/2 + 24
				});
			}
			 
		});
		var onEmbed = function() {
			$(window).trigger('resize.intro');
		};
		site.introActive = true;
		swfobject.embedSWF(swf, "flashContent", "1400", "1150", "9.0.124", "swf/expressInstall.swf", flashVars, params, attributes, onEmbed);
		site.hideSlideShow(); 
		$('.introbg').height($('img.blau').height())
		$('.intro').show().append($('<span class="skipmessage">Klicken Sie um das Intro zu überspringen</span>'));
		
	},
	hideIntro: function() {  
		site.introActive = false;
		site.showSlideShow();
		$(document).unbind('mousedown.intro');
		$(window).unbind('resize.intro');
		swfobject.removeSWF("introswf");
		$('.intro').animate({opacity:0},800, function() {
			$('.intro').remove(); 
		}); 

		if (!hash()) {
			hash('home');
		}
	},
	
	getBgColorByImage: function(img) {
		var clrname = $(img).attr('src').split('slide_')[1].split('.')[0];
		return this.bgcolors[clrname]	
	},
	/* slides thru themes */
	showSlideShow: function() {
 
		var duration = this.options.ssInterval;
		var speed = this.options.ssTransitionDuration;
		
		
		if (!site.slideshowContainer) {
			$('.slideshow-container').show();
			site.slideshowContainer = $('.slideshow-container');
		}
		else {
			$('.pages').before(site.slideshowContainer);			
		}
		  
		var queue = $('#slideshow-queue');
		var slides = $('#slideshow');  
		
		slides.find('img').appendTo(queue);
		queue.find('.blau').appendTo(slides).show();
		
		var initalImg = slides.find('img').last();
		var initalClr = site.getBgColorByImage(initalImg);
		
		$('.bgcolor').css('background-color', site.bgcolors.blau);
	
		 
		var next = function() { 
			window.clearTimeout(site.slideshowTimeout);	
			var img = queue.find('img').first(); 
			img
			.hide() 
			.appendTo(slides)
			.stop().fadeIn(speed, function() {
				$(this).prev().appendTo(queue);
				site.slideshowTimeout = window.setTimeout(next, duration);
			}) 
			$('.bgcolor').animate({ backgroundColor: site.getBgColorByImage(img) }, speed);
		};
		
		site.slideshowTimeout = window.setTimeout(next, duration);
		site.slideshowActive = true;
		site.resize(); 
	},
	pauseSlideShow: function() {
		if (!site.slideshowActive) {
			return;
		}
		window.clearTimeout(site.slideshowTimeout);		 
	}, 
	hideSlideShow: function() {
		if (!site.slideshowActive) {
			return;
		}
		site.slideshowActive = false;
		if (!site.slideshowContainer) {
			site.slideshowContainer = $('.slideshow-container');
		}
		if ($('#slideshow img').length > 1) { $('#slideshow img:eq(0)').appendTo($('#slideshow-queue')); }
		window.clearTimeout(site.slideshowTimeout);
		site.slideshowContainer.remove(); 
		 
	}, 
	// TODO: eval entfernen
	loadRequiredScripts: function(target) { 
		//if (!this.loadedScripts) {
		//	this.loadedScripts = [];
		//}
		//var loadedScripts = this.loadedScripts;
		
		// log('loadRequiredScripts', target)
		var _loaded = function() { 
			target.find('.execute-js').each(function() { 
				eval($(this).attr('data-function'))();
			});
		};
		target.find('.require-js').each(function() {
			// log('required: '+$(this).attr('data-src'))
			var src = $(this).attr('data-src');
			if (src) {
				//var already_loaded = $.inArray(src, loadedScripts) > -1; 
				// log('Already loaded?', already_loaded)
				//if (already_loaded) { 
					
					//_loaded();
				//}
				//else {
				//log('site.loadRequiredScripts()', src)
				$.getScript(src, _loaded);
				//loadedScripts.push(src);
				//}
			}
		});
		
	}, 
	refresh: function() {
		this.loadContent(this.currentUrl);	
	},
	loadContent: function(url) {
	 
		site.currentUrl = url;
		// new way:load template only 
		var template = 'content/'+url.split('p=/')[1]+'.html';
		site.currentTemplate = template;
		site.showSpinner();
		
		$(window).trigger('rmbLoadContent', [{
			page: url
		}]);
		 
		$.ajax({
		  url: template,
		  dataType: 'html', 
		  success: site.contentLoaded
		});
		$('body').css('cursor', 'progress');
	},
	loading: function(flag) {
		flag ? site.showSpinner() : site.hideSpinner();
	},
	contentLoaded: function(data) {
    
		if (data) {
      // IE8 <:section> fix                 
		  var tmp = $('<div>').append(data).remove();
      tmp.find('section').each(function() {  
        $(this).before( innerShiv('<section>' + $(this).html() + '</section>') );
        $(this).remove();
      });
      // usual IE fix :)
			$('.pages').empty().append( innerShiv( tmp.html() ));
		}
		
		
		$('.layout img').bind('load.resize', function() {
			site.resize();
			$(this).unbind('load.resize');
		})
		
		// blackwhite/hovercolor
		
//		$('.rounded.imagebox img').hoverSaturate();
		
		//site.resize();
		site.emailLinks();
		site.top();
		site.vNavMenu.submenu.hide();
		//$(document).pngFix(); 
		

		site.convertLinks();
		site.layout(); 
		
 
		
		site.resize();
		
		site.loadRequiredScripts($('.layout'));
		
		$(window).trigger('rmbContentLoaded', [{
			page: hash()
		}]);

		site.hideSpinner();
		$('body').css('cursor', 'auto');
		
		// portrait/wer-sind-wir/organisation
		//site.currentTemplate = hash() + '.html';
		/*
		if (site.ie7) {
			setTimeout(function() {
				site.resize();
			}, 500);
		}*/
		
        site.hideEmptyFileLinks();
        
        if (hash() == 'home') {
        	site.populateHome();
        }
	},
	hideEmptyFileLinks: function() {
		 $('a.more').each(function() {
        	var href = $(this).attr('href'); 
        	if (href && href.substr(href.length-6, href.length) == 'files/') {
        		$(this).hide();
        	}
        });
	},
	populateHome: function() {
		var target = $('.layout .ajax-content');
		target.empty();
		
		var loaded = function(data) {
			//log('loaded')
			var content = $( '<div>' ).append( innerShiv( $('<div>').append(data).remove().html()) );
	 
			content.find('section').each(function() {
				var new_section = $('<section>');
				new_section.append($(this).find('h3:eq(0)'));
				new_section.append( $('<p>').html($(this).find('p:eq(0)').html().substr(0,site.options.homeMaxChars)+'...') );
				target.append(new_section)
			})
		};
		$.ajax({
		  url: 'content/aktuelles.html',
		  dataType: 'html', 
		  success: loaded
		});
	},
	saturation: function(target) {
 
		var targets = target || $('.imagebox');
		targets.each(function() {
			if ($(this).isChildOf('.static')) {
				return;
			}
			$(this).find('.desaturated').remove();
			$(this).find('canvas').remove();
			$(this).css('position','relative');
			var img = $(this).find('img');
			
			
			var clone = img.clone();
			clone.addClass('desaturated');
			img.after(clone);
			
			if ($.browser.msie) {
				clone[0].style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)';
				//clone[0].style['-ms-filter'] = 'progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)'; ;
			}
			else { 
				Pixastic.process(clone[0], "desaturate", {average : false});
			} 
 
			
			var container = $(this).closest('section')
			//container.width( $('.layout').width() )
			.css({
				position: 'relative',
				left: 0,
				//'padding-left': 65,
				'padding-top': 20,
				'padding-bottom': 20 
			});
			
			 
			container.hover(function() {
				//log(this)
				$(this).addClass('hovered');
				$(this).find('.desaturated').hide();
			}, function() {
				$(this).removeClass('hovered');
				$(this).find('.desaturated').show();				
			});
			
			if ($.browser.webkit) {
				$(this).css({
					'-webkit-mask': 'url(img/imagebox-mask-webkit.png)' 
				});
				//img.css('position','static');
			}
			  
		});
	},
	convertLinks: function() {
		$('.nav a, a.internal').each(function() { 
			var href = $(this).attr('href');
			if (href && href.indexOf('?p=')!=-1) { 
				// HASH NAVIGATON  
				$(this).attr({
					'href': href.replace('?p=','#')
				}); 
			 
				$(this).attr({
					'data-href': href, 
					'data-path': href.split('?p=')[1]
				})
				 
			}
		});
		
		if (site.ie7) {
			$('.hnav a img').click(function() {
				hash( $(this).closest('a').attr('data-path') );
			});
		}
	},
	
	/**
	 * Lädt ein stylesheet ins dokument.
	 * @param url Das zu ladende Stylesheet
	 */
	loadCSS: function(url) {
		if (document.createStyleSheet) {
			document.createStyleSheet(url);
		}
		else {
			$('html > head').append(
				$('<link/>').attr({
					rel: 'stylesheet',
					type: 'text/css',
					media: 'screen',
					href: url
				})
			);
		}
	},
	
	loadLESS: function(url) {
		var time = new Date().getTime();
		var id = 'less_'+time;
		$('html > head').append(
			$('<link/>').attr({
				rel: 'stylesheet/less',
				type: 'text/css', 
				href: url,
				id: id
			})
		);
		less.sheets.push($('#'+id)[0]);
		less.refresh();
	},
	
	showSpinner: function() {  
		if ($('body > .spinner').length) {
			$('body > .spinner').addClass('active').show();
			return;
		}
		$('<div class="spinner">Daten werden geladen</div>').appendTo( $('body') );
	},
	
	hideSpinner: function() {
		$('body > .spinner').removeClass('active').hide();
	},
	
	

	
	/**
	 * Erzeugt eine textarea über die ganze Sichtbar Fläche und zeigt darin text an. 
	 * Können wir für dev-Sachen nutzen, um zB das generierte HTML einzusehen / zu überprüfen.
	 */
	debugDialog: function(content) {
		if (!jQuery.ui) {
			return alert('Bitte erst einloggen!')
		}
		var id = 'ta_'+new Date().getTime();
		var resize = function() {
			var ta = $('#'+id);
			var di = ta.closest('.ui-dialog');
			ta.width(di.width()-30);
			ta.height(di.height()-10);
		}
		
		$('<textarea>')
		.val(content)
		.attr('id', id)
		.dialog({
			title: 'Output Dialog',
			width: $(window).width()*0.9,
			height: $(window).height()*0.7,
			open: resize,
			resize: resize
		})
	}
	
	
};


(function($) {  
 
	var l = location.href;
	if (l.indexOf('?p=') !=-1 ) {
		location.href = l.replace('?p=','#');
	}
	$(document).ready(function() { 
	
		site.init();
		
	});
	
}(jQuery));

window.hideIntro = function() {
	site.hideIntro();
}
window.hideIntroBG = function() {
	$('.skipmessage').animate({opacity:0},'fast');
	$('.introbg').animate({opacity:0},'fast');
}
