/* ------------------------------------------------------------------------------------ *
| GLOBALS Javascript FILE :: For RANZ Showcase galleries + global functions				|
| js/globals.js																			|
| 																						|
| PROJECT :: www.ranz.ch v2.0															|
| Copyright (C) 2009, QUERIDODESIGN, Switzerland										|
| 																						|
+ ------------------------------------------------------------------------------------- +
| Authors :: Luis M (Rendez)															|
* ------------------------------------------------------------------------------------- */

(function(){

	Class.Mutators.Binds = function(self, binds) {
		if (!self.Binds) return self;
		delete self.Binds;
		var oldInit = self.initialize;
		self.initialize = function() {
			Array.flatten(binds).each(function(binder) {
				var original = this[binder];
				this[binder] = function(){
					return original.apply(this, arguments);
				}.bind(this);
				this[binder].parent = original.parent;
			}, this);
			return oldInit.apply(this,arguments);
		};
		return self;
	};

	// CUSTOM EVENTS 'nextimage' AND 'previmage' :: Rendez
	Element.Events.nextimage = {
	    base: 'keydown',
	    condition: function(event){
	        return (event.key == 'right' || event.key == 'down');
	    }
	};
	Element.Events.previmage = {
	    base: 'keydown',
	    condition: function(event){
	        return (event.key == 'left' || event.key == 'up');
	    }
	};

	var SlidingSet = new Class({

		Implements: Options,

		Binds: ['sweepToNext', 'sweepToPrev'],

		options: {
			sweepTime: 1000,
			keyboard: true,
			controlsAutoHide: false
		},

		load: function() {
			//window.addEvent('domready', function(){ new SlidingSet(arguments); }.pass(arguments));
			return new SlidingSet(arguments);
		},

		initialize: function() {
			var params = arguments[0];
			var wrapper = params[0];
			var images = params[1];
			var options = params[2];

			this.setOptions(options);
			this.wrapper = $(wrapper) || document.getElement(wrapper);
			this.images = (images !== null) ? images : new Array();
			if (!this.images.length) this.images = this.wrapper.getElements('img');
			this.length = this.images.length;
			this.index = 0;
			this.images.each(function(image, index){ (index != this.index) ? image.setStyle('visibility', 'hidden') : image.setStyles({'visibility': 'visible', 'opacity': '0.01'}); }, this);
			this.start();
		},

		start: function() {
			this.progression = this.wrapper.getElement('.progression');
			this.count = 0;
			this.pagination = this.wrapper.getElement('.pagination');
			this.paginate();
			this.rail = this.images[this.index].getSize().x;
			this.container = this.wrapper.getElement('.gallery_content ul').setStyle('width', (this.rail * this.length) + 1).getElement('li');
			this.fx = new Fx.Tween(this.container, {'property': 'margin-left', 'link': 'cancel', 'transition': 'sine:out', 'duration': this.options.sweepTime});
			this.fx2 = new Fx.Tween(this.container.getParent(), {'property': 'margin-left', 'link': 'cancel', 'transition': 'sine:out', 'duration': this.options.sweepTime});
			this.images.each(this.prepareLoad, this);
			this.setControls();
			this.change();
		},

		isVisible: function(index) {
			return this.images[index].getStyle('visibility') == 'visible';
		},

		prepareLoad: function(image, index) {
			image.addEvent('load', function(image, index){
				if (index != this.index) {
					image.setStyle('visibility', 'visible');
				} else {
					flag = true;
					image.set('tween', {'property': 'opacity', 'duration': 'normal'});
					image.tween(1);
				}
				this.progress(index);
			}.create({bind: this, arguments: [image, index]}));
			image.src = image.src + "?" + $time();
		},

		setControls: function() {
			this.prev = this.wrapper.getElement('.previous').addEvent('click', this.sweepToPrev);
			this.next = this.wrapper.getElement('.next').addEvent('click', this.sweepToNext);
			if (this.options.controlsAutoHide) this.calibrate();
			//if (this.options.keyboard) this.setKeyboardControls();
		},

		setKeyboardControls: function() {
			document.addEvent('nextimage', this.sweepToNext);
			document.addEvent('previmage', this.sweepToPrev);
		},

		calibrate: function() {
			if (this.index === 0) this.prev.setStyle('visibility', 'hidden');
			else this.prev.setStyle('visibility', 'visible');
			if (this.index === this.length - 1) this.next.setStyle('visibility', 'hidden');
			else this.next.setStyle('visibility', 'visible');
		},

		setDetails: function() {
			var index = this.index;
			var source = this.wrapper.getElements('.gallery_content ul li')[index].getElement('.gallery_details');
			var recipient = this.wrapper.getElement('#gallery_detail');
			
			details = $(new SlidingSet.Details(source, recipient)).replaces(recipient);
			details.set('opacity', 0);
			details.set('tween', {property: 'opacity', duration: this.options.sweepTime / 2});
			fx = details.get('tween');
			fx.start.delay(this.options.sweepTime, fx, 1);
		},

		change: function(oldIndex) {
			if (!this.isVisible(this.index)) {
				return this.index = oldIndex;
			}
			value = -this.index * this.rail;
			value2 = (this.index === 0) ? value : value + this.rail;
			this.fx.start(value).chain(function(){
				if (this.options.controlsAutoHide) this.calibrate();
				this.paginate();	
			}.bind(this));

			this.fx2.start(value2);
			this.setDetails();
		},

		sweepToNext: function() {
			oldIndex = this.index;
			this.index = (this.index + 1) % this.length;
			this.change(oldIndex);
		},
	
		sweepToPrev: function() {
			oldIndex = this.index;
			this.index = (this.index === 0) ? this.length - 1 : this.index - 1;
			this.change(oldIndex);
		},

		paginate: function() {
			this.pagination.set('text', String(this.index + 1) + "/" + String(this.images.length));
		},

		progress: function(loaded) {
			if (loaded) {
				this.count++;
				if (this.count == this.length - 1) {
					this.progression.set('text', "Fertig!");
					(function(){
						this.progression.fade('out');
					}).create({bind: this, delay: 600})();

				} else {
					this.progression.set('text', "geladen " + String(this.count + 1) + " von " + String(this.images.length));
				}
			}
		}

	});

	SlidingSet.Details = new Class({

		toElement: function() {
			if (!this.element) {
				this.element = this.recipient.clone(false, true);
				this.element.set('html', this.source.get('html'));
			}
			return this.element;
		},

		initialize: function(source, recipient) {
			this.source = source;
			this.recipient = recipient;
		}

	});

	window.addEvent('domready', function() {
		if (Cookie.read('loaded_overlay') != 'true') {
			var src = '/images/globals/nav_keys_bg.png';
			new Asset.image(src, {onload: function() {
				Cookie.write('loaded_overlay', 'true', {'path': '/'});
			}});
		}
		
		var navkeys = $('navkeys');
		if (!navkeys) return;

		navkeys.setStyle('visibility', 'hidden');

		var overlay = Cookie.read('shown_overlay') != 'true';
		var gallery = null;
		var wrapper = 'showcase_gallery';
		var firstImg = ($(wrapper) || document.getElement(wrapper)).getElement('img').setStyle('visibility', 'hidden');
		new Asset.image(firstImg.get('src'), {onload: function(){
			gallery = SlidingSet.prototype.load(wrapper, null, {sweepTime: 600});
			var evaporate = function(){
				if (overlay) navkeys.fade('out');
				gallery.setKeyboardControls();
			};
			if (overlay) {
				navkeys.setStyle('visibility', 'visible');
				Cookie.write('shown_overlay', 'true', {'path': '/'});
				evaporate.delay(2700);
				navkeys.addEvent('click', evaporate);
			} else {
				gallery.setKeyboardControls();
			}
		}});
		firstImg.src = firstImg.src + "?" + $time();
	});

})();

// HOME CLASS :: Rendez
var Home = new Class({

	Implements: Options,

	options: {
		timer: 5000,
		stopAtTheEnd: true
	},

	initialize: function(data, options) {
		this.setOptions(options);
		// change these options only
		this.content = document.getElement('.content_container.home');
		this.contentOut = new Fx.Tween(this.content, {'property': 'opacity', 'duration': 'long', 'onComplete': this.change.bind(this)});
		this.contentIn = new Fx.Tween(this.content, {'property': 'opacity', 'duration': 'long'});
		this.data = data;
		this.index = 0;
		this.start();
	},

	start: function() {
		this.content.set('opacity', 0);
		this.contentIn.start(1);
		this.interval = this.transition.periodical(this.options.timer, this);
	},

	transition: function() {
		this.contentOut.start(0);
	},

	change: function() {
		this.index++;
		this.index = this.index % this.data.getLength();
		this.content.set('html', this.data[this.index].content);
		this.contentIn.start(1);
		if (this.options.stopAtTheEnd) {
			if (this.index >= this.data.getLength() - 1) {
				$clear(this.interval);
			}
		}
	}

});

window.addEvent('domready', function(){

	if (!(field = $('home_pages'))) return;
	var json = eval(field.value), data = new Hash();
	for (bit in json) {
		if (json.hasOwnProperty(bit)) data.include(bit, json[bit]);
	}
	new Home(data);

});
