/* ===================================================================
	
	GeorgRudolph.de
	---------------
	Code by Florian Pichler, es&es, somewhatcreative.com
	
====================================================================*/
/*
---
script: Loop.js
description: Runs a class method on a periodical
license: MIT-style license.
authors: Ryan Florence <http://ryanflorence.com>
docs: http://moodocs.net/rpflo/mootools-rpflo/Loop
requires:
- core:1.2.4/'*'
provides: [Loop]
...
*/

var Loop = new Class({

	loopCount: 0,
	isStopped: true,
	isLooping: false,
	loopMethod: $empty,

	setLoop: function(fn,delay){
		if(this.isLooping) {
			this.stopLoop();
			var wasLooping = true;
		} else {
			var wasLooping = false;
		}
		this.loopMethod = fn;
		this.loopDelay = delay || 3000;
		if(wasLooping) this.startLoop();
		return this;
	},

	stopLoop: function() {
		this.isStopped = true;
		this.isLooping = false;
		$clear(this.periodical);
		return this;
	},

	startLoop: function(delay) {
		if(this.isStopped){
			var delay = (delay) ? delay : this.loopDelay;
			this.isStopped = false;
			this.isLooping = true;
			this.periodical = this.looper.periodical(delay,this);
		};
		return this;
	},

	resetLoop: function(){
		this.loopCount = 0;
		return this;
	},

	looper: function(){
		this.loopCount++;
		this.loopMethod(this.loopCount);
		return this;
	}

});

/*
---
script: SlideShow.js
description: Easily extendable, class-based, slideshow widget. Use any element, not just images. Comes with packaged transitions but is easy to extend and create your own transitions.  The class is built to handle the basics of a slideshow, extend it to implement your own navigation piece and custom transitions.
license: MIT-style license.
authors: Ryan Florence
docs: http://moodocs.net/rpflo/mootools-rpflo/SlideShow
requires:
  - Loop
provides: [SlideShow]
...
*/
var SlideShow = new Class({
	Implements: [Options, Events, Loop],
		options: {
			/*
			onShow: $empty,
			onShowComplete: $empty,
			onReverse: $empty,
			onPlay: $empty,
			onPause: $empty
			*/
			delay: 7000,
			transition: 'crossFade',
			duration: '500',
			autoplay: false
		},
	initialize: function(element, options){
		this.setOptions(options);
		this.setLoop(this.showNext, this.options.delay);
		this.element = document.id(element);
		this.slides = this.element.getChildren();
		this.current = this.slides[0];
		this.setup();
		if(this.options.autoplay) this.startLoop();
	},
	setup: function(){
	  this.setupElement();
	  this.setupSlides();
		return this;
	},
	setupElement: function(){
		var el = this.element;
		if(el.getStyle('position') != 'absolute' && el != document.body) el.setStyle('position','relative');
		return this;
	},
	setupSlides: function(){
		this.slides.each(function(slide, index){
			this.storeTransition(slide).reset(slide);
			if(index != 0) slide.setStyle('display','none');
		}, this);
		return this;
	},
	storeTransition: function(slide){
		var classes = slide.get('class');
		var transitionRegex = /transition:[a-zA-Z]+/;
		var durationRegex = /duration:[0-9]+/;
		var transition = (classes.match(transitionRegex)) ? classes.match(transitionRegex)[0].split(':')[1] : this.options.transition;
		var duration = (classes.match(durationRegex)) ? classes.match(durationRegex)[0].split(':')[1] : this.options.duration;
		slide.store('ssTransition', transition);
		slide.store('ssDuration', duration);
		return this;
	},
	getTransition: function(slide){
		return slide.retrieve('ssTransition');
	},
	getDuration: function(slide){
		return slide.retrieve('ssDuration');
	},
	show: function(slide){
		this.fireEvent('show');
		slide = (typeof slide == 'number') ? this.slides[slide] : slide;
		if(slide != this.current){
			var transition = this.getTransition(slide);
			var duration = this.getDuration(slide);
			var previous = this.current.setStyle('z-index', 1);
			var next = this.reset(slide);
			this.transitions[transition](previous, next, duration, this);
			(function() { 
				previous.setStyle('display','none');
				this.fireEvent('showComplete');
			}).bind(this).delay(duration);
			this.current = next;
		}
		return this;
	},
	reset: function(slide){
		return slide.setStyles({
			'position': 'absolute',
			'z-index': 0,
			'display': 'block',
			'left': 0,
			'top': 0
		}).fade('show');
		return this;
	},
	nextSlide: function(){
		var next = this.current.getNext();
		return (next) ? next : this.slides[0];
	},
	previousSlide: function(){
		var previous = this.current.getPrevious();
		return (previous) ? previous : this.slides.getLast();
	},
	showNext: function(){
		this.show(this.nextSlide());
		return this;
	},
	showPrevious: function(){
		this.show(this.previousSlide());
		return this;
	},
	play: function(){
		this.startLoop();
		this.fireEvent('play');
		return this;
	},
	pause: function(){
		this.stopLoop();
		this.fireEvent('pause');
		return this;
	},
	reverse: function(){
		var fn = (this.loopMethod == this.showNext) ? this.showPrevious : this.showNext;
		this.setLoop(fn, this.options.delay);
		this.fireEvent('reverse');
		return this;
	}
});

SlideShow.adders = {
	transitions:{},
	add: function(className, fn){
		this.transitions[className] = fn;
		this.implement({
			transitions: this.transitions
		});
	},
	addAllThese : function(transitions){
		$A(transitions).each(function(transition){
			this.add(transition[0], transition[1]);
		}, this);
	}
	
}
$extend(SlideShow, SlideShow.adders);
SlideShow.implement(SlideShow.adders);
SlideShow.add('fade', function(previous, next, duration, instance){
	previous.set('tween',{duration: duration}).fade('out');
	return this;
});
SlideShow.addAllThese([
	['none', function(previous, next, duration, instance){
		previous.setStyle('display','none');
		return this;
	}],
	['crossFade', function(previous, next, duration, instance){
		previous.set('tween',{duration: duration}).fade('out');
		next.set('tween',{duration: duration}).fade('in');
		return this;
	}],
	['fadeThroughBackground', function(previous, next, duration, instance){
		var half = duration/2;
		next.set('tween',{ duration: half }).fade('hide');
		previous.set('tween',{ 
			duration: half, onComplete: function(){ next.fade('in'); }
		}).fade('out');
	}],
	['pushLeft', function(previous, next, duration, instance){
		var distance = instance.element.getStyle('width').toInt();
		next.setStyle('left', distance);
		[next, previous].each(function(slide){
			var to = slide.getStyle('left').toInt() - distance;
			slide.set('tween',{duration: duration, link: 'cancel'}).tween('left', to);
		});
		return this;
	}],
	['pushRight', function(previous, next, duration, instance){
		var distance = instance.element.getStyle('width').toInt();
		next.setStyle('left', -distance);
		[next, previous].each(function(slide){
			var to = slide.getStyle('left').toInt() + distance;
			slide.set('tween',{duration: duration, link: 'cancel'}).tween('left', to);
		});
		return this;
	}],
	['pushDown', function(previous, next, duration, instance){
		var distance = instance.element.getStyle('height').toInt();
		next.setStyle('top', -distance);
		[next, previous].each(function(slide){
			var to = slide.getStyle('top').toInt() + distance;
			slide.set('tween',{duration: duration}).tween('top', to);
		});
		return this;
	}],
	['pushUp', function(previous, next, duration, instance){
		var distance = instance.element.getStyle('height').toInt();
		next.setStyle('top', distance);
		[next, previous].each(function(slide){
			var to = slide.getStyle('top').toInt() - distance;
			slide.set('tween',{duration: duration}).tween('top', to);
		});
		return this;
	}],
	['blindLeft', function(previous, next, duration, instance){
		var distance = instance.element.getStyle('width').toInt();
		next.setStyles({
			'left': distance,
			'z-index': 1
		}).set('tween',{duration: duration}).tween('left', 0);
		return this;
	}],
	['blindRight', function(previous, next, duration, instance){
		var distance = instance.element.getStyle('width').toInt();
		next.setStyles({
			'left': -distance,
			'z-index': 1
		}).set('tween',{duration: duration}).tween('left', 0);
		return this;
	}],
	['blindUp', function(previous, next, duration, instance){
		var distance = instance.element.getStyle('height').toInt();
		next.setStyles({
			'top': distance,
			'z-index': 1
		}).set('tween',{duration: duration}).tween('top', 0);
		return this;
	}],
	['blindDown', function(previous, next, duration, instance){
		var distance = instance.element.getStyle('height').toInt();
		next.setStyles({ 
			'top': -distance, 
			'z-index': 1 
		}).set('tween',{duration: duration}).tween('top', 0);
		return this;
	}],
	['blindDownFade', function(previous, next, duration, instance){
		this.blindDown(previous, next, duration, instance).fade(previous, next, duration, instance);
	}],
	['blindUpFade', function(previous, next, duration, instance){
		this.blindUp(previous, next, duration, instance).fade(previous, next, duration, instance);
	}],
	['blindLeftFade', function(previous, next, duration, instance){
		this.blindLeft(previous, next, duration, instance).fade(previous, next, duration, instance);
	}],
	['blindRightFade', function(previous, next, duration, instance){
		this.blindRight(previous, next, duration, instance).fade(previous, next, duration, instance);
	}]
]);

/*
	Push by pichfl & langa
*/
SlideShow.add('push', function(previous, next, duration, instance){
	//by @langa
	var a = instance.slides.indexOf(previous).toInt();
	var b = instance.slides.indexOf(next).toInt();
	var c = (instance.slides.length-1).toInt();
	if ((a < b || (a > b && b == 0 && a == c)) && !(a == 0 && b == c)){
		this.pushLeft(previous, next, duration, instance);
	}else{
		this.pushRight(previous, next, duration, instance);
	}
});

/* 
	Super!
*/

Element.implement({
	act: function(){ this.addClass('interact'); return this; }
});

var SuperArrow = new Class({
	Implements: [Events, Options],
	options: {
		direction: 'right',
		className: 'squareButton',
		events: {}
	},
	initialize: function(options){
		this.setOptions(options);
		this.direction = (this.options.direction == 'left')?'left':'right';
		return this.build();
	},
	build: function(){
		this.element = new Element('div',{
			'class': 'arrow '+this.direction+' '+this.options.className,
			'events': this.options.events
		});
		this.elementInner = new Element('div',{
			'html': (this.direction != 'right')?'&larr;':'&rarr;'
		}).inject(this.element).grab(new Element('em'));
		return this.element;
	},
	toElement: function(){ 
		return this.element; 
	}
});

var SuperImage = new Class({
	Implements: [Events, Options],
	options: {
		wrapper: undefined,
		imagesSrc: [],
		imagesSize: {x:1600, y:1200}
	},
	images: [],
	c: 0,
	l: [],
	attached: false,
	initialize: function(element,options){
		this.setOptions(options);
		this.element = element;
		this.build();
		this.start();
		this.attach();
	},
	build: function(){
		//BG
		this.element.setStyle('background-image', 'none');

		var wrapTemp = document.id(this.options.wrapper);
		if($defined(wrapTemp))
		{
			this.wrapper = wrapTemp;
		}
		else
		{
			this.wrapper = new Element('div',{
				'id': 'bodyImage'
			}).inject(body);
		}
		if(this.wrapper.getElements('img').length > 0)
		{
			this.images[this.c] = document.id(this.wrapper.getElement('img'));
			var t = this.images[this.c].get('src');
			this.options.imagesSrc = [t].combine(this.options.imagesSrc.erase(t));
			this.images[this.c].addClass(this.getImageAlign(this.options.imagesSrc[this.c]));
			this.l[this.c] = true;
			this.c++;
		}
		else
		{
			this.l[this.c] = false;
			this.next(true);
		}
		this.switchButton = new SuperArrow().act().addClass('switchButton');
	},
	start: function(){
		this.resize();
		this.wrapper.addEvents({
			'mousemove:relay(img)': function(ev, el){
				ev.preventDefault();
			}
		});
		return this.element;
	},
	resize: function(){
		var s = this.element.getSize();
		this.wrapper.setStyle('height',s.y);
		var img = this.wrapper.getElement('img');
		var a = this.options.imagesSize.x;
		var b = this.options.imagesSize.y;
		var imageRatio = b/a;
		if(s.y/s.x < imageRatio){
			img.set({
				width: (s.x).toInt(),
				height: (s.x*imageRatio).toInt()
			});
		}else{
			img.set({
				width: (s.y/imageRatio).toInt(),
				height: (s.y).toInt()
			});
		}
	},
	getImageAlign: function(str){
		var str = ($defined(str))?str:'';
		return str.match(/(?:_)(.*)(?:\.)/)[1];
	},
	next: function(notcounting){
		if(!notcounting){
			this.c = (this.c < this.options.imagesSrc.length-1)?this.c+1:0;
		}
		if( this.l[this.c] == false ){
			var imgAsset = new Asset.image(this.options.imagesSrc[this.c], {
				width: this.options.imagesSize.x,
				height: this.options.imagesSize.y,
				'class': this.getImageAlign(this.options.imagesSrc[this.c]),
				onload: function(){
					this.images[this.c] = imgAsset;
					this.l[this.c] = true;
					this.showNext();
				}.bind(this)
			});
		}else{
			this.showNext();
		}
	},
	showNext: function(){
		document.id(this.wrapper.getElement('img')).dispose();
		this.wrapper.empty();
		this.images[this.c].inject(this.wrapper);
		this.resize();
		this.switchButton.fade('show');
	},
	addImages: function(images){
		this.options.imagesSrc = this.options.imagesSrc.combine(images);
		for(i=0;i<this.options.imagesSrc.length;i++){
			if(i<this.l.length){
				continue;
			}
			this.l[i] = false;
		}
		this.attached = false;
		this.attach();
	},
	attach: function(){
		if(this.options.imagesSrc.length > 1 && this.attached == false){
			this.switchButton.inject(body).addEvent('click', function(ev){
				this.switchButton.fade('hide');
				this.next();
			}.bind(this));
		}
		this.attached = true;
	}
});

//Globals
var bodyJSON, body, bodyImage, contentSliders;
var resizeTimeout;

window.addEvents({
	'domready': function(){
		body = document.id(document.body).removeClass('nojs').addClass('js');
		
		bodyImage = new SuperImage(body,{
			wrapper: 'bodyImage',
			imagesSrc: [],
			imagesSize: {x: 1700, y: 1200}
		});
		
		(function(){
			bodyJSONP = new Request.JSONP({
				url: 'http://georgrudolph.de/a/b/',
				onComplete: function(jsonObj){
					bodyImage.addImages(jsonObj.images);
				}
			}).send();
		})();

		var slides = $('slides');
		if($defined(slides)){
			var slideChildrenHeight = [];
			slides.getChildren().each(function(el,i){
				var width = el.getParent().getSize().x,
				img = el.getElement('img'),
				as = el.getElement('.assets');
				slideChildrenHeight[i] = el.getSize().y;
				
				/*
				if (img && window.getSize().x < 970) {
					el.setStyle('min-width', '0');
					el.getElement('.text').setStyle('width', width
						-img.getSize().x-el.getStyle('padding-left').toInt()
						-el.getStyle('padding-right').toInt()
						-500
						-as.getStyle('margin-right').toInt()
					)
					as.setStyle('width', 500);
				}
				*/
				var newEl = new Element('div',{
					'styles': { 'width': width }
				}).grab(el.clone()).replaces(el);
				el = newEl;
			});
			slides.setStyle('height', slideChildrenHeight.max());

			if(slides.getChildren().length > 1){
				var locked = false;
				var contentSlides = new SlideShow(slides,{
					transition: 'crossFade',
					duration: '400',
					onShowComplete: function(){ locked = !locked; }
				});
				var contentSlidesNav = new Element('div',{ 
					'class': 'nav slides' 
				}).inject(slides,'after');
				var navPrev = new SuperArrow({
					direction: 'left',
					events: {
						'click': function(){ 
							if(!locked){
								contentSlides.showPrevious(); 
								locked = !locked;
							}
						}
					}
				}).inject(contentSlidesNav).act();
				var navNext = new SuperArrow({
					events: {
						'click': function(){ 
							if(!locked){
								contentSlides.showNext(); 
								locked = !locked;
							}
						}
					}
				}).inject(contentSlidesNav).act();
			}
		}
		
		var elPage = $('page');
		if($defined(elPage)){
			elPage.getElements('.plain').each(function(x){
				x.getElements('li').each(function(el,i,a){
					if(i != a.length-1) el.appendText('/');
				});
			});
			
			if(body.hasClass('referenzen')){
				elPage.getElements('a').each(function(el){
					el.store('info', el.get('title'));
					el.removeProperties('href','title');
					el.addClass('info');
				});
				
				var infobox = new Element('div', {
					'class': 'mouseoverInfo'
				}).inject(body).set('tween', {link: 'cancel', duration: 100}).fade('hide');
				
				elPage.addEvent('mouseleave', function(){
					infobox.fade('hide');
				});
				
				elPage.getElements('a').addEvents({
					'mouseenter': function(ev){
						var a = ev.target;
						if(a.tagName == 'CANVAS')
							a = a.parentNode.parentNode;
						infobox.set('text', $(a).retrieve('info'));
						infobox.fade('in');
					},
					'mouseleave': function(ev){
						elPage.fireEvent('mouseleave');
					}
				});
			}
		}
		
		Cufon.replace("#page .plain",{
			hover:true,
			textShadow:"0px 1px rgba(0, 0, 0, 0.5)"
		})
		.replace("#page .content  h2,#page .content h3")
		.replace("#page .post  h2,#page .post h3",{
			hover:true
		});
	},
	'resize': function(){
		if( bodyImage != undefined )
		{
			if( Browser.Engine.trident )
			{
				$clear(resizeTimeout);
				resizeTimeout = (function(){ bodyImage.resize(body); }).delay(5);
			}
			else
			{
				bodyImage.resize(body);
			}
		}
	}
});
