﻿var Flipbook = new Class({
	initialize: function( thb, thumbset ) {
		this.thumbDIV = thb;
		this.thumbset = thumbset;
		this.DIVwidth = thb.getSize().x;
		this.img = thb.getElements('img');
		this.img.setStyle('display','none');
		this.space = this.DIVwidth/thumbset.length;
		var $this = this;
		this.thumbDIV.addEvent('mousemove', function(e) {
			$this.evalPosition(e.page.x,e.page.y);
		});
		this.activeNr = -1;
		this.activeThumb = false;
	}
	,evalPosition: function ( xp, yp ) {
		var DIVpos = this.thumbDIV.getPosition();
		var nr = Math.floor((xp-DIVpos.x)/this.space);
		if( nr != this.activeNr) {
			this.activeNr = nr;
			if( this.activeThumb !== false ) {
				this.activeThumb.destroy();
			}
			var th = this.thumbset[nr].clone();
			this.activeThumb = th.inject(this.thumbDIV,'top');
			this.activeThumb.setStyles({
				position: 'absolute'
				,left: Math.round((this.DIVwidth - this.activeThumb.getSize().x)/2)
			});
		}
	}
	,die: function() {
		this.thumbDIV.removeEvents('mousemove');
		if( this.activeThumb ) this.activeThumb.dispose();
		this.img.setStyle('display','block');
	}
});

	
var MG_Cont = new Class({
	Implements : [Chain]
	,initialize : function(CM, ct, nW ){
		this.MIN_SCR_WIDTH = 1024;
		this.MIN_SCR_HEIGHT = 650;
		
		this.isMobile = document.body.ontouchstart !== undefined;

		this.CM = CM;
		this.contentType = ct;
		this.navWidth = nW;
		this.DIV = $('content'); // outside div
		this.DIV.setStyles({
			overflow: 'hidden'
		}); 
		this.follower = new Element('div', {
			styles: {
				position: 'absolute'
				,zIndex: 999
			}
		});
		var pl = new Element('img', {
			src: '/assets/plus.png'
			,id: 'plus'
			,styles: {
				position: 'absolute'
			}
		});
		pl.inject(this.follower);
		var min = new Element('img', {
			src: '/assets/minus.png'
			,id: 'minus'
			,styles: {
				position: 'absolute'
			}
		});
		min.inject(this.follower);
		this.reset();
	}
	,reset:function() {
		this.IMG = false;
		this.IMGloaded = 0;
		if( this.contentType === 'category') {
			this.initStrecken();
		}
		if( this.contentType === 'gallery') {
			this.initPic();
		}
		if( this.contentType === 'video') {
			this.initVideo();
		}		
		if( this.contentType === 'special') {
			this.initSpecial();
		}
		if( this.contentType === 'video wall') {
			this.initVideoWall();
		}
	}
	,initStrecken: function() {
		this.strecken = $$('.cat li');
		this.mainIMGpaths = [];
		for( var i=0; i<this.strecken.length; i++) {
			var strecke = this.strecken[i];
			var img = strecke.getElement('img').dispose();
			this.mainIMGpaths[i] = img.get('src');
			var thb = strecke.getElements('a:first-child');

			if(img.get('_width')) thb.setStyle('width', img.get('_width')+'px');

			strecke.setStyle('display','none');
			if( !this.isMobile && strecke.get('_type') === 'img' ) {
				var $this = this;
				thb.store('thumbSetLoaded', 0);
				thb.store('strid', strecke.get('_strid'));
				thb.setStyle('opacity',.5);
				thb.addEvents({
					'mouseenter': function() {
						$this.streckeMouseEnter(this.retrieve('strid'));
					}
					,'mouseleave': function() {
						$this.streckeMouseLeave(this.retrieve('strid'));
					}
				});
			}
		}
		// HIJACK HREFS here
		$$('.cat a').addEvent('click', function(event){
			event.preventDefault();
			event.stop();
			this.blur();
			if( !History.hasPushState()) {
				var loc = window.location;
				if( loc.pathname !== '/' ) {
					window.location = 'http://'+loc.hostname+'/#'+this.get('href');
					return;
				}
			}
			History.push(this.get('href'));
		});
	}
	,streckeMouseEnter: function( strid ) {
	if( this.activeFlipbook ) return;
		var strecke = $$('li[_strid='+strid+']')[0];
		var thb = strecke.getElements('a:first-child')[0];
		if( thb.retrieve('thumbSetLoaded') == false ) {
			thb.setStyle('opacity',1);
		} else {
			this.activeFlipbook = new Flipbook( thb, this.thumbSets[ strecke.retrieve('setid') ]);
		}
	}
	,streckeMouseLeave: function( strid ) {
		var strecke = $$('li[_strid='+strid+']')[0];
		var thb = strecke.getElements('a:first-child');
		if( thb.retrieve('thumbSetLoaded') == false ) {
			thb.setStyle('opacity',.5);
		} else {
			if( this.activeFlipbook ) {
				this.activeFlipbook.die();
				delete this.activeFlipbook;
			}
		}
	}
	,activateFlipbook: function( strecke) {
		strecke.store('setid', 'id'+strecke.get('_strid'));
		var thb = strecke.getElements('a:first-child');
		thb.setStyle('opacity',1);
		thb.store('thumbSetLoaded', 1);
	}
	,loadNextIMG: function() {
		var $this = this;
		if( this.IMGloaded >= 0 ){
			var e = this.strecken[this.IMGloaded].getElements('a:first-child');
			this.IMGasset.inject(e[0]);
			this.IMGasset.fade('hide');
			(function(){
				this.set('tween', {duration: 300});
				this.fade('in')
			}).delay(150, this.IMGasset);
		};
		++this.IMGloaded;
		if( this.IMGloaded < this.strecken.length ) {
			this.IMGasset = new Asset.image( this.mainIMGpaths[this.IMGloaded], {
				onLoad: function() { $this.loadNextIMG(); }
			}); 
		} else {
			if( !this.isMobile ) {
				this.thumbSetsLoaded = 0;
				this.thumbSet = false;
				this.thumbSets = {};
				this.loadNextThumbSet();
			}
		}
	}
	,loadNextThumbSet: function( ths ) {
		if( !ths ) {
			if( this.thumbSet != false) {
				this.thumbSets['id'+this.strecken[this.thumbSetsLoaded].get('_strid')] = this.thumbSet;
				this.activateFlipbook(this.strecken[this.thumbSetsLoaded]);
				this.thumbSet = false;
				this.thumbSetsLoaded++;
				if( this.thumbSetsLoaded == this.strecken.length ) {
					return 0;
				}
			}
			if( this.thsRequest ) {
				if( this.thsRequest.running ) {
					this.thsRequest.cancel();
					this.thsRequest = false;
				}
			}
			if( this.strecken[this.thumbSetsLoaded].get('_strid') == -1 ) {
				this.thumbSetsLoaded++;
				//this.thumbSet = 'single';
				this.loadNextThumbSet();
			}
			var $this = this;
			this.thsRequest = new Request.JSON({
				url: 'getthumbset.php'
				,data: { 'strid': this.strecken[this.thumbSetsLoaded].get('_strid'), 'ajax': 1 }
				,onComplete: function(jsonObj,j2) {
					$this.loadNextThumbSet(jsonObj);
				}
			,onFailure: function(xhr) {
			}
			,onException: function(headerName, value) {
			}
			}).send();
		} else {
			if( ths.paths.length === 0 ) {
				this.thumbSet = 'single';
				this.loadNextThumbSet();
			}
			var $this = this; 
			this.thumbSet = Asset.images( ths.paths, {
				onComplete: function() {
					$this.loadNextThumbSet();
				}
			});
		}
	}
	,initPic: function() {
		this.onResizeHandler = this.onResize.bind(this);
		window.addEvent('resize', this.onResizeHandler );
		this.IMGframe = $$('a.frame')[0];
		var i = this.IMGframe.getElement('img');
		this.imgOrg = i.clone();
		i.setStyle('display','none');
		/* Asset.image(i.get('src'), {
			onLoad: this.IMGonLoad.bind(this);
		}); */
		this.sizeOrg = {
			frameW: this.IMGframe.get('_width')
			,frameH: this.IMGframe.get('_height')
			,frameX: this.navWidth  // set in CM
			,frameY: 36 // padding top content
			,picW: this.imgOrg.get('_width')
			,picH: this.imgOrg.get('_height')
			,rightMargin: 40
			,bottomMargin: 10 + 32  //margin content + AGBs
		};
		this.IMGframe.addEvent('click', function(e) {e.stop();} );
		
		if( this.IMGframe.get('href') != this.IMGframe.get('prevpic') ) {
			
			if( this.isMobile ) {
				this.overlayDIV = new Element('div');
				this.overlayDIV.setStyle('position', 'absolute');
				this.overlayDIV.inject( this.IMGframe, 'top' );
				this.overlayIMG = new Element('img', { src: '/assets/over.png' } );
				this.overlayIMG.inject( this.overlayDIV );
				var minus = new Element('img', { 
					src: '/assets/minus.png'
					,styles: { position: 'absolute', top: 'auto', bottom: '50%', left: '25px', right: 'auto' }
				} );
				minus.inject( this.overlayDIV, 'top');
				var plus = new Element('img', { 
					src: '/assets/plus.png'
					,styles: { position: 'absolute', top: 'auto', bottom: '50%', left: 'auto', right: '25px' }
				} );
				plus.inject( this.overlayDIV, 'top');
				
				this.overlayDIV.set('tween', { duration: 600 });
				this.overlayDIV.fade('hide');
				
			} 
		}
		this.onResize();
	}
	,imgMouseOver: function( stat ) {
		if( stat === 'over' && !this.following ) {
			this.following = true;
			this.follower.inject(this.DIV,'bottom');
			this.followO = {
				followMiddleX: this.IMGframe.getCoordinates().left + this.IMGframe.getCoordinates().width/2
				,plus: this.follower.getElement('#plus')
				,minus: this.follower.getElement('#minus')
			};
			this.setFollowerPositionHandler = this.setFollowerPosition.bind(this);
			$(document.body).addEvent('mousemove', this.setFollowerPositionHandler);
			//this.setFollowerPositionHandler();
		}
		if( stat === 'out' && this.following ) {
			this.following = false;
			$(document.body).removeEvent('mousemove', this.setFollowerPositionHandler);
			this.follower = this.follower.dispose();
		}
	}
	,setFollowerPosition: function(ev) {
		var showPlus = ev.page.x > this.followO.followMiddleX;
		this.followO.plus.setStyle('display', showPlus ? 'block':'none');
		this.followO.minus.setStyle('display', showPlus ? 'none':'block');
		this.follower.setStyles({
			left:ev.page.x + (showPlus ? -70 : 11)
			,top: ev.page.y-55
		});
	}
	,imgClick: function(event){
		//event.preventDefault();
		event.stop();
		this.IMGframe.blur();
		
		if(this.overlayDIV) this.clearOverlay();
		this.IMGframe.removeEvent('click', this.imgClickHandler );
		this.IMGframe.addEvent('click', function(event) { event.stop(); this.blur(); } );
		
		this.IMGframe.removeEvent('mouseover', this.imgMouseOverHandler );
		this.IMGframe.removeEvent('mouseout', this.imgMouseOutHandler );
		this.imgMouseOver('out');
			
		
		var pos = this.IMGframe.getCoordinates();
		var href = this.IMGframe.get('href');
		if( event.page.x < pos.left + pos.width/2 ) {
			var href = this.IMGframe.get('prevpic');
		}
		if( !History.hasPushState()) {
			var loc = window.location;
			if( loc.pathname !== '/' ) {
				window.location = 'http://'+loc.hostname+'/#'+href;
				return;
			}
		}
		
		if(this.isMobile) {
			this.clearOverlay();
		} else {
			//this.IMGframe.set('opacity', '.5');
		}
		History.push(href);
		return false;
	}
	,overlayFade: function( args ) {
		this.overlayDIV.fade( args );
	}
	,initVideo: function() {
		this.videoLoaded = false;
	
		var $this = this;
		var vid = $$('.video')[0];
		var size = { x: vid.get('_width'), y: vid.get('_height') };
		new Request.JSONP({
		  url: 'http://www.vimeo.com/api/oembed.json',
			data: {
				autoplay: 'true',
				url: ''+vid.get('_url'),
				title: 'false',
				portrait: 'false',
				byline: 'false',
				color: '#DDDDDD',
				height: ''+size.y
			} /**/,
			onComplete: function(j1){
				this.videoLoaded = true;
				this.vidResponse = j1;
				this.injectVideo();
			}.bind(this)
		}).send();
	}
	,injectVideo: function() {
		if( this.videoLoaded ) {
			//var e = Elements.from( this.vidResponse.html );
			var vid = $$('.video')[0];
			vid.set('html',this.vidResponse.html);
		}
	}
	,initSpecial: function() {
		
	}
	,initVideoWall: function() {
		this.onResizeHandler = this.onResizeVideoWall.bind(this);
		window.addEvent('resize', this.onResizeHandler );
		var vidWallDIV = $$('.video-wall')[0];
		if( vidWallDIV ) {
			var vidWall = new Swiff( '/assets/wall.swf', {
				id: 'videoWallSWF'
				,width: '100%'
				,height: '100%'
				,params: {
					wMode: 'opaque'
					,bgcolor: '#D9DADB'
					,allowFullScreen: 'true'
				}
				,vars: {
					mg_clip_sizes: vidWallDIV.get('data-coords')
					,mg_clips: vidWallDIV.get('data-urls')
					,minVolume: vidWallDIV.get('data-minvol')
					,maxVolume: vidWallDIV.get('data-maxvol')
					,directory: 'http://new.marcusgaab.com/assets/uploads/'
				}
			});
			vidWallDIV.empty();
			vidWall.inject(vidWallDIV);
			this.onResizeVideoWall();
		}
	}
	,getGalleryID: function() {
		var gid = 0;
		if( this.contentType === 'gallery' ) {
			gid = Number($$('.frame')[0].get('_galid'));
		}
		return gid;
	}
	,showIMG: function() {
		if(this.spinner) {
			clearTimeout(this.spinnerTimer);
			this.spinner.destroy();
		}
		this.IMGasset.inject(this.IMGframe);
		this.IMG = this.IMGasset;
		
		if( this.IMGframe.get('href') != this.IMGframe.get('prevpic') ) {
			this.imgClickHandler = this.imgClick.bind(this);
			this.IMGframe.addEvent('click', this.imgClickHandler );
			if( this.isMobile ) {
				this.overlayFadeShowHandler = this.overlayFade.bind(this,[ 'show' ]);
				this.overlayFadeOutHandler = this.overlayFade.bind(this,['hide' ]);
				$(document.body).addEvent('touchstart', this.overlayFadeShowHandler );
				$(document.body).addEvent('touchend', this.overlayFadeOutHandler);
			} else {
				this.imgMouseOverHandler = this.imgMouseOver.bind(this, 'over');
				this.imgMouseOutHandler = this.imgMouseOver.bind(this, 'out');
				this.IMGframe.addEvent('mouseover', this.imgMouseOverHandler );
				this.IMGframe.addEvent('mouseout', this.imgMouseOutHandler );
			}
		} else {
			this.IMGframe.setStyle('cursor','default');
		}
		this.onResize();
	}
	,onResizeVideoWall: function() {
		var sizeWin = window.getSize();
		sizeWin.x = Math.max( sizeWin.x, this.MIN_SCR_WIDTH);
		sizeWin.y = Math.max( sizeWin.y, this.MIN_SCR_HEIGHT);
		var sizeNew = {};
		sizeNew.x = sizeWin.x - (this.navWidth + 40);
		sizeNew.y = sizeWin.y - 00;	
		
		var outf = $('outframe');
		if( outf ) outf.setStyles({
			'width': sizeNew.x
			,'height': sizeNew.y
		});
		/* 
		var coordsets = $('outframe').getElement('.video-wall').get('data-coords');
		coordsets = coordsets.split('|');
		var coords = { xmin:0, xmax:0, ymin:0, ymax:0 }; 
		for(var i=0; i<coordsets.length; i++) {
			var set = coordsets[i].split(',');
			coords.xmin = Math.min( coords.xmin, Number(set[1]) );
			coords.xmax = Math.max( coords.xmax, Number(set[1])+Number(set[3]) );
			coords.ymin = Math.min( coords.ymin, Number(set[2]) );
			coords.ymax = Math.max( coords.ymax, Number(set[1])+Number(set[4]) );
		}
		var outf = $('outframe');
		if( outf ) outf.setStyles({
			'width': (coords.xmax + 50) - coords.xmin
			,'height': (coords.ymax + 80) - coords.ymin
		}); */
	}
	,onResize: function() {
		var sizeWin = window.getSize();
		sizeWin.x = Math.max( sizeWin.x, this.MIN_SCR_WIDTH);
		sizeWin.y = Math.max( sizeWin.y, this.MIN_SCR_HEIGHT);
		var sizeNew = {};
		sizeNew.x = sizeWin.x - (this.sizeOrg.frameX + this.sizeOrg.rightMargin);	// fenster größe abzgl. frame position und frame rand
		sizeNew.y = sizeWin.y - (this.sizeOrg.frameY + this.sizeOrg.bottomMargin + 32);
		
		var outf = $('outframe');
		if( outf ) outf.setStyle('width', sizeNew.x);
		
		if( this.IMGframe ) {
			
			var factorX = sizeNew.x / this.sizeOrg.frameW; // neue breite / frame original  breite
			var factorY = sizeNew.y / this.sizeOrg.frameH; // neue breite / frame original  breite
			var factor = Math.min(factorX, factorY);
			
			if( !this.isMobile ) if(this.sizeOrg.frameH * factor < 500) factor = 500 / this.sizeOrg.frameH;
			
			factor = Math.min(factor, 1);
			
			var w = Math.round(this.sizeOrg.frameW * factor);
			var h = Math.round(this.sizeOrg.frameH * factor);
			
			
			this.IMGframe.setStyles({
				width: w
				,height: h
			});
			
			if(this.overlayIMG) {
				this.overlayIMG.setStyles({
					width: w
					,height: h
				});
			}
			
			if( this.IMG !== false ) {
				w = Math.round(this.sizeOrg.picW * factor);
				h = Math.round(this.sizeOrg.picH * factor);
				this.IMG.setStyles({
					width: w
					,height: h
				});
			}
		}
	}
	,fadeIn: function() {
		if( this.contentType === 'category' ) {
			for( var i=0; i<this.strecken.length; i++) {
				(function() {this.setStyle('display','inline-block');}).delay(i*120+200,this.strecken[i]);
			}
			this.IMGloaded = -1;
			this.loadNextIMG();
		}
		if( this.contentType === 'gallery' ) {
			$this = this;
			this.spinner = new Spinner(this.DIV);
			var spf = function(){ $this.spinner.show(true);};
			this.spinnerTimer = spf.delay(1000);
			this.IMGasset = new Asset.image( this.imgOrg.get('src'), {
				onLoad: function() { $this.showIMG(); }
			});
		}
		if( this.contentType === 'video' ) {
			this.injectVideo();
		}
	}
	,update: function( type, html ) {
		this.contentType = type;
		this.clear();
		var e = Elements.from( html, false );
		e.inject(this.DIV);
		this.reset();
		this.fadeIn();
	}
	,clearOverlay: function(p) {
		if(this.overlayDIV) this.overlayDIV.dispose();
		delete this.overlayDIV;
		$(document.body).removeEvent('touchstart', this.overlayFadeShowHandler );
		$(document.body).removeEvent('touchend', this.overlayFadeOutHandler);
	}
	,clear: function() {
		if( this.thsRequest ) {
			if( this.thsRequest.running ) {
				this.thsRequest.cancel();
				this.thsRequest = false;
			}
		}
		if( this.thumbSets ) {
			Object.each(this.thumbSets, function(thSet) {
				if( thSet !== 'single' ) {
					for( var i=0; i<thSet.length; i++ ) {
						thSet[i].empty();
					}
				}
			});
		}
		delete this.thumbSets;
		this.clearOverlay();
		window.removeEvent('resize', this.onResizeHandler );
		this.DIV.empty();
	}
});


var ContentManager = new Class({
	initialize : function(o){
		this._isIndex = o._isIndex;
		
		this.doHijack = Browser.Features.xhr;
		
		this.setContentType();
		this.hasFlash = (Browser.Plugins.Flash && Browser.Plugins.Flash.version > 8) ? 1 : 0;
	
		this.NAV = new MG_Navigation();
		
		this.TXT = new MG_Text(this);
		
		this.CONT = new MG_Cont(this, this.contentType, this.NAV.getWidth());
		this.currentGalleryID = this.CONT.getGalleryID();
		this.COUNTER = new MG_Counter();
		this.COUNTER.hide(true);
		this.CTXT = new MG_CText();
		this.CTXT.hide(true);
		
		var $this = this;
		this.hasIntro = this._isIndex && ($('intro') != null && document.body.ontouchstart === undefined);
		if(this.hasIntro ) {
			this.waitForIntro = true;
			this.introDIV = $('intro');
			this.loadIntroImg();
		}
		this.NAV.onLoadComplete = function() {
			if( !$this.waitForIntro ) this.fadeAllIn();
		}
		this.NAV.onFadeComplete = function() {
			this.navReady();
		}.bind(this);
		
		
		History.addEvent('change', function(url){ this.onHistoryChange(url); }.bind(this) );
		
		if( History.hasPushState() ) {
			if( document.location.hash.substr(1) != '' ) this.onHistoryChange(document.location.hash.substr(1));
		}
		
		if (!History.hasPushState()) {
			// Check if there is a hash
			var hash = document.location.hash.substr(1);
			if (!hash) {
			} else {
				// If the hash equals the current page, don't do anything
				var path = document.location.pathname.split('/');
				path = path[path.length - 1];
				if (hash != path) {
					// Load the page specified in the hash
					this.onHistoryChange(hash);
				}
			}
		}
	}
	,loadIntroImg: function() {
		var $this = this;
		this.introAsset = Asset.image( this.introDIV.get('data-url'), {
			onLoad: function() { $this.showIntroImg(1); }
			,onError: function() { alert("An error with your internet connection has occured. Please try again."); }
		});
	}
	,showIntroImg: function( step ) {
		var $this = this;
		if( step === 1 ) {
			if( !window.innerWidth ) {
				var sizeWin = { x:document.body.offsetWidth, y: document.body.offsetHeight };
			} else {
				var sizeWin = { x: window.innerWidth, y: window.innerHeight };//window.getSize();
			}
			var pwidth = parseInt(this.introDIV.get('data-width'),10);
			var pheight = parseInt(this.introDIV.get('data-height'),10);
			var fx = (sizeWin.x-80) / pwidth;
			var fy = (sizeWin.y-80) / pheight;
			var f = Math.min(fx,fy);
			this.introAsset.inject(this.introDIV);
			var picW = Math.round(pwidth * f);
			var picH = Math.round(pheight * f);
			this.introAsset.setStyles({
				width: picW
				,height: picH
				,cursor: 'pointer'
			});
			this.introDIV.setStyles({
				left: Math.round( (sizeWin.x - picW)/2 )
				,top: Math.round( (sizeWin.y - picH)/2 )
			});
			this.introDIV.fade('hide');
			this.introAsset.addEvent('click', function() {
				$this.showIntroImg(2);
			});
			(function() {$this.introDIV.fade('in')}).delay(1000);
			this.introTimer = (function() {$this.showIntroImg(2);}).delay(4000);
		}
		if( step === 2 ) {
			clearTimeout(this.introTimer);
			delete this.introTimer;
			this.introDIV.removeEvents('click');
			this.introDIV.fade('out');
			(function() {$this.showIntroImg(3);}).delay(600);
		}
		if( step === 3 ) {
			this.introDIV.dispose();
			this.NAV.fadeAllIn();
		}
	}
	,navReady: function() {
		switch( this.contentType) {
			case 'txt':
				this.TXT.fadeIn(); 
				break;
			case 'category':
				this.CONT.fadeIn(); 
				break;
			case 'gallery':
				this.CONT.fadeIn();
				this.CTXT.fadeIn();
				this.COUNTER.initCounter();
				break;
			case 'video':
				this.CONT.fadeIn();
				this.CTXT.fadeIn();
				break;
			case 'special':
				this.CONT.fadeIn();
				this.CTXT.fadeIn();
				break;
			case 'video wall':
				this.CONT.fadeIn();
				this.CTXT.fadeIn();
				break;
		}
	}
	,setContentType: function() {
		if(!0) {
			if( $$('#textpage > div').length > 0 ) {
				this.contentType = 'txt';
				return;
			}
			if($$('#content > ul.cat').length > 0) {
				this.contentType = 'category';
				return;
			}
			if($$('#content .frame').length > 0) {
				this.contentType = 'gallery';
				return;
			}
			if($$('#content > .video').length > 0) {
				this.contentType = 'video';
				return;
			}
			if($$('#content .video-wall').length > 0) {
				this.contentType = 'video wall';
				return;
			}			
			if($$('#content > iframe').length > 0) {
				this.contentType = 'special';
				return;
			}
		}
	}
	,onHistoryChange: function( newURL ) {
		if( this.jRequest ) {
			if( this.jRequest.running ) {
				this.jRequest.cancel();
				this.jRequest = false;
			}
		}
		$(document.body).setStyle('cursor','progress');
		var $this = this;
		this.jRequest = new Request.JSON({
			url: 'getcontent.php'
			,data: { 'hash': newURL, 'ajax': 1, 'hasFlash': this.hasFlash }
			,onComplete: function(jsonObj,j2) {
				$this.processResponse(jsonObj);
			}
			,onFailure: function(xhr) {
				alert("failure "+xhr);
			}
			,onException: function(headerName, value) {
				alert("exception "+headerName+" - value: "+value);
			}
		}).send();
	}
	,processResponse: function( newData ){
		$(document.body).setStyle('cursor','default');
		document.title = newData.pagetitle;
		if(newData.catID ) this.NAV.switchActiveItem(newData.catID);
		if( newData.type == 'category' ) {
			this.currentGalleryID = 0;
			this.CONT.update( 'category',newData.contentHTML );
			this.currentContent = this.CONT;
			this.COUNTER.clear();
			this.CTXT.clear();
			this.TXT.clear();
		}
		if( newData.type == 'gallery' ) {
			this.CONT.update( 'gallery', newData.contentHTML );
			this.COUNTER.update( newData.counterHTML, (this.currentGalleryID != newData.galleryID) );
			this.CTXT.update(newData.ctextHTML, (this.currentGalleryID != newData.galleryID));
			this.currentContent = this.CONT;
			this.currentGalleryID = newData.galleryID;
			this.TXT.clear();
		} 
		if( newData.type == 'video' ) {
			this.currentGalleryID = 0;
			this.CONT.update( 'video', newData.contentHTML );
			this.CTXT.update(newData.ctextHTML, (this.currentGalleryID != newData.galleryID));
			this.TXT.clear();
		} 
		if( newData.type == 'special' ) {
			this.currentGalleryID = 0;
			this.CONT.update( 'special', newData.contentHTML );
			this.CTXT.update(newData.ctextHTML, (this.currentGalleryID != newData.galleryID));
			this.TXT.clear();
		} 
		if( newData.type == 'video wall' ) {
			this.currentGalleryID = 0;
			this.CONT.update( 'video wall', newData.contentHTML );
			this.CTXT.update(newData.ctextHTML, (this.currentGalleryID != newData.galleryID));
			this.TXT.clear();
		} 
		if( newData.type == 'textpage' ) {
			this.currentGalleryID = 0;
			this.TXT.update( newData.textpageHTML );
			this.currentContent = this.TXT;
			this.CONT.clear();
			this.COUNTER.clear();
			this.CTXT.clear();
		}
	},
	clearContent: function( fields ) {
	}
});



var MG_Navigation = new Class({
	initialize : function(options){
		this.complete = 0;
		this.largestWidth = 0;
		var img_paths_large = [];
		this.items_large = $$('a.large[_img]');
		for( var i=0; i<this.items_large.length; i++ ) {
			var item = this.items_large[i];
			item.fade('hide');
			img_paths_large.push(item.get('_img'));
			this.largestWidth = Math.max( this.largestWidth, item.get('_width'));
		}
		var img_paths_small = [];
		this.items_small = $$('a.small[_img]');
		for( var i=0; i<this.items_small.length; i++ ) {
			var item = this.items_small[i];
			item.fade('hide');
			img_paths_small.push(item.get('_img'));
			this.largestWidth = Math.max( this.largestWidth, item.get('_width'));
		}
		var $this = this;
		this.large_images = new Asset.images(img_paths_large, { 
			onComplete: function() {
				$this.replaceLargeText();
			}
		});
		this.small_images = new Asset.images(img_paths_small, { 
			onComplete: function() {
				$this.replaceSmallText();
			}
		});
		
		// Hijax!
		$$('.nav').addEvent('click', function(event){
			if(  this.get('target') !== '_blank' ) {
				event.preventDefault();
				this.blur();
				if( !History.hasPushState()) {
					var loc = window.location;
					if( loc.pathname !== '/' ) {
						window.location = 'http://'+loc.hostname+'/#'+this.get('href');
						return;
					}
				}
				History.push(this.get('href'));
			}
		});
	}
	,replaceLargeText: function() {
		for( var i=0; i<this.items_large.length; i++ ) {
			var item = this.items_large[i];
			this.replaceItem( item, i, 35, this.large_images );
			if( item.hasClass('active') ) this.setItemActive(item.get('id'), true );
		}
		this.callCompleted();
	}
	,replaceSmallText: function() {
		for( var i=0; i<this.items_small.length; i++ ) {
			var item = this.items_small[i];
			this.replaceItem( item, i, 23, this.small_images );
			if( item.hasClass('active') && item.get('target') !== '_blank') this.setItemActive(item.get('id'), true );
		}
		this.callCompleted();
	}
	,replaceItem: function( it, i, h, imgs ) {
		it.setStyles({
			width: it.get('_width')+'px', 
			overflow: 'hidden',
			position: 'relative',
			height: h,	
			fontSize: 1
		});
		
		var plain = imgs[i];
		plain.setStyles({
			position: 'absolute',
			left: 0,
			top: 0
		});
		plain.inject(it);
		
		var bold = plain.clone();
		bold.setStyles({
			position: 'absolute',
			left: 0,
			top: -h
		});
			
		bold.addClass('over');
		bold.inject(it);
		
		it.getElement('.over').fade('hide');
		it.addEvent('mouseover', function() {
			if( this.retrieve('active') === true ) return false;
			var el = this.getElement('.over');
			el.set('tween', {duration: 10});
			el.fade('in');
		});
		it.addEvent('mouseout', function() {
			if( this.retrieve('active') === true ) return false;
			var el = this.getElement('.over');
			el.set('tween', {duration: 200});
			el.fade('out');
		});
	}
	,switchActiveItem: function( catID ) {
		if(this.currentActiveItem) this.setItemActive( this.currentActiveItem.get('id') );
		this.setItemActive( "r"+catID, true );
	}
	,setItemActive: function( id, status ) {
		var item = $(id);
		item.store('active', status );
		if( status ) {
			item.getElement('.over').fade('show');
			this.currentActiveItem = item;
		} else {
			item.getElement('.over').fade('hide');
			if( item == this.currentActiveItem ) this.currentActiveItem = null;
		}
	}
	,callCompleted: function() {
		if( ++this.complete === 2 ) {
			this.onLoadComplete();
		}
	}
	,fadeAllIn: function() {
		var items = [];
		items.push($$('h1[class=logo]')[0].getElements('a')[0]);
		var ul1 = $$('ul[class=nav-lev1]');
		for( var i=0; i<ul1.length; i++) {
			var el = ul1[i].getElements('a');
			for( var c=0; c<el.length; c++) {
				items.push(el[c]);
			}
		}
		var ul2 = $$('ul[class=nav-lev2]');
		for( var i=0; i<ul2.length; i++) {
			var el = ul2[i].getElements('a');
			for( var c=0; c<el.length; c++) {
				items.push(el[c]);
			}
		}
		items.push($$('div[class=agb]')[0].getElements('a')[0]);
		items.push($$('div[class=rss]')[0].getElements('a')[0]);
		
		
		if( CM._isIndex ) {
			for( var i=0; i<items.length; i++ ) {
				if(i===items.length-1) items[i].store('isLast','true')
				var $this = this;
				(function() {
					this.set('tween', {duration: 80});
					this.fade('in');
					if( this.retrieve('isLast')==='true' ) $this.onFadeComplete();
				}).delay(i*50+500,items[i]);
			}
		} else {
			for( var i=0; i<items.length; i++ ) {
				items[i].fade('show');
			}
			this.onFadeComplete();
		}
	}
	,getWidth: function() {
		return this.largestWidth + 40 + 35; // width + padding body + paddingrght leftcol
	}
});


var MG_Counter = new Class({
	Implements : [Chain]
	,initialize : function(CM){
		this.stripWidths = new Array( 89, 103, 143);
		this.leftWidths = new Array( 60, 60, 90);
		this.slashMarginR = new Array( -30, -33, -35);
		var cs = ['/assets/counter1.png','/assets/counter2.png','/assets/counter3.png','/assets/slash.png'];
		var $this = this;
		this.loaded = false;
		this.cStrips = new Asset.images(cs, { 
			onComplete: function() {
				$this.stripsLoaded();
			}
		});
		this.DIV = $('counter');	
	}
	,initCounter: function( str ) {
		this.currentNr = 0;
		this.totalNr = 0;
		if(!str) str = this.DIV.get('html');
		this.DIV.set('html','');
		
		this.currentDIV = new Element('div', {
			styles: {
				float: 'left'
				,position: 'relative'
			}
		});	
		this.currentDIV.inject(this.DIV);
		
		this.totalDIV = new Element('div', {
			styles: {
			}
		});	
		this.totalDIV.inject(this.DIV);
		
		if( str != '' ) {
			this.digits = str.split('/');
			this.hide(false);
			var xp = this.buildCurrent(this.digits[0]);
			this.buildTotal(this.digits[1]);
			this.totalDIV.tween('margin-left', xp);
		}
	}
	,buildCurrent: function(nr) {
		if(this.currentNr != nr ) {
			this.currentNr = nr;
			if( this.oldNrDIV ) {
				this.oldNrDIV.dispose();
			}
			if( this.oldNrDIV = this.newNrDIV )	this.oldNrDIV.getElement('img').fade('out');
			
			var stripNr = Math.floor(nr/10);
			var singleNr = nr - stripNr*10;
			this.newNrDIV = new Element('div', {
				styles: {
					overflow: 'hidden'
					,position: 'absolute'
					,top: 17
					,left: 0
					,width: this.stripWidths[stripNr]
					,height: 126
				}
			});	
			this.newNrDIV.inject(this.currentDIV,'bottom');
			var strip = this.cStrips[stripNr].clone();
			strip.inject(this.newNrDIV,'bottom');
			strip.setStyles({
				position: 'relative'
				,top: singleNr * -126
			});
			this.newNrDIV.getElement('img').fade('hide');
			this.newNrDIV.getElement('img').fade('in');
		} else {
			var stripNr = 0;
		}
		return this.leftWidths[stripNr];
	}
	,buildTotal: function(nr) {
		if(this.totalNr != nr ) {
			this.totalNr = nr;
			this.totalDIV.empty();
			var slash = this.cStrips[3].clone();
			slash.inject(this.totalDIV,'top');
			slash.setStyles({
				position: 'relative'
				,top: 10
			});
			
			var stripNr = Math.floor(nr/10);
			var singleNr = nr - stripNr*10;
			this.totalNrDIV = new Element('div', {
				styles: {
					overflow: 'hidden'
					,position: 'relative'
					,width: this.stripWidths[stripNr]
					,height: 126
					,display: 'inline-block'
					,left: this.slashMarginR[stripNr]
					,'margin-left': 0
				}
			});	
			this.totalNrDIV.inject(this.totalDIV,'bottom');
			var strip = this.cStrips[stripNr].clone();
			strip.inject(this.totalNrDIV,'bottom');
			strip.setStyles({
				position: 'relative'
				,top: singleNr * -126
			}); 
		}
		if( this.totalDIV.getStyle( 'margin-left' ) == 0 ) this.totalDIV.setStyle( 'margin-left',this.leftWidths[0] )
	}
	,stripsLoaded: function() {
		this.loaded = true;
	}
	,update: function( html, isNewGallery ) {
		if( isNewGallery ) {
			this.initCounter( html );
			return;
		} 
		var newDigits = html.split('/');
		var xp = this.buildCurrent( newDigits[0] );
		this.totalDIV.tween('margin-left', xp);
	}
	,hide: function( stat ) {
		var x = stat ? 'none' : 'block';
		this.DIV.setStyle('display', x);
	}
	,clear: function( ) {
	//ccccccccccccccccccccc
		this.DIV.empty();
	}
});



var MG_CText = new Class({
	Implements : [Options,Events],
	options : {
	}
	,initialize : function(options){
		this.DIV = $('ctext');
		this.DIV.setStyles({
			//overflow: 'hidden'
		});
	}
	,fadeIn: function() {
		this.hide(false);
	}
	,update: function( html, newGal ) {
		this.hide(false);
		if( newGal ) {
			this.DIV.set('html', html );
		}
	}
	,hide: function( stat ) {
		var x = stat ? 'none' : 'block';
		this.DIV.setStyle('display', x);
	}
	,clear: function( ) {
		this.DIV.empty();
	}
});



var MG_Text = new Class({
	Implements : [Chain]
	,initialize : function(CM){
		this.CM = CM;
		this.DIV = $('textpage'); // outside div
		this.DIV.setStyles({
			height: 0
			,overflow: 'hidden'
			,display: 'none'
		}); 
		this.fx = new Fx.Tween( this.DIV, {duration: 300, transition: Fx.Transitions.Quart.easeOut});
		this.reset();
	}
	,doTelephones: function() {
		$$('#textpage span[data-img]').each( function(item) {
			var src = item.get('data-img');
			item.set('html', '<img src="'+src+'" />');
		});
	}
	,reset: function() {
		this.content = $$('#textpage > div:first-child')[0];
		if( this.content ) { // div holding the text
			this.content.fade('hide');
			this.loaded = true;
		}
		this.doTelephones();
	}
	,fadeIn: function() {
		this.DIV.setStyle('display', 'block');
		var h = this.content.measure( function(){ return this.getSize().y; });
						
		var a= function() {
			this.fx.start('height', h);
		}.bind(this);
		
		var b= function() {
			this.DIV.setStyle('height','auto');
			this.content.set('tween',{duration: 300});
			this.content.fade('in');
		}.bind(this);
		
				 
		this.fx.start('border', 0).chain(a).chain(b);
	}
	,update: function( html ) {
		this.clear();
		var e = Elements.from( html );
		e.inject(this.DIV);
		this.reset();
		this.fadeIn();
	}
	,clear: function() {
		if( this.fx ) this.fx.clearChain();
		this.DIV.empty();
		this.fx.start('height', 0);
	}
});

// *************************************************************************************************

(function() {
	var _isIndex = window.location.hash === '' && window.location.pathname === '/'; // startSeite?
	

	
	window.addEvent('domready', function() {
		CM = new ContentManager( {_isIndex:_isIndex} );
	});
})();
