/*var myShow = new Slideshow('show', data, {controller: false, height: 300, hu: 'images/', thumbnails: true, width: 400, thumb_height:'84px', thumb_width:'84px'});*/
/**
Adapted from....
Script: Slideshow.js
	Slideshow - A javascript class for Mootools to stream and animate the presentation of images on your website.

License:
	MIT-style license.

Copyright:
	Copyright (c) 2008 [Aeron Glemann](http://www.electricprism.com/aeron/).

Dependencies:
	Mootools 1.2 Core: Fx.Morph, Fx.Tween, Selectors, Element.Dimensions.
	Mootools 1.2 More: Assets.
*/

Slideshow = new Class({
	Implements: [Chain, Events, Options],
	
	options: {
		center: true,
		classes: [],
		delay: 6000,
		duration: 750,
		height: false,
		href: '',
		hu: '',
		linked: false,
		loop: true,
		match: /\?slide=(\d+)$/,
		num_items: 0,
		overlap: true,
		replace: [/(\.[^\.]+)$/, '$1'],
		resize: 'width',
		slide: 0,
		thumb_height: '120px',
		thumb_width: '120px',
		thumbnails: false,
		transition: function(p){return -(Math.cos(Math.PI * p) - 1) / 2;},
		width: false
	},
	

	initialize: function(el, thumbs, options){
		this.setOptions(options);
		this.slideshow = $(el);
		if (!this.slideshow)
			return;
		this.slideshow.set('styles', {'display': 'block', 'position': 'relative', 'z-index': 0});
		var match = window.location.href.match(this.options.match);
		this.slide = (this.options.match && match) ? match[1].toInt() : this.options.slide;
		this.counter = this.delay = this.transition = 0;
		this.direction = 'left';
		if (!this.options.overlap)
			this.options.duration *= 2;
		var anchor = this.slideshow.getElement('a') || new Element('a');
		if (!this.options.href)
			this.options.href = anchor.get('href') || '';
		if (this.options.hu.length && !this.options.hu.test(/\/$/)) 
			this.options.hu += '/';
			
		// styles
		var keys = ['slideshow', 'thumbnails', 'hidden', 'visible', 'inactive', 'active'];
		var values = keys.map(function(key, i){
			return this.options.classes[i] || key;
		}, this);
		this.classes = values.associate(keys);
		this.classes.get = function(){
			var str = '.' + this.slideshow;
			for (var i = 0, l = arguments.length; i < l; i++)
				str += ('-' + this[arguments[i]]);
			return str;
		}.bind(this.classes);

		// thumbs
		this.firstrun = true;
		this.showed = {'array': [], 'i': 0};
		if ($type(thumbs) == 'array'){
			thumbs = new Array(thumbs.length).associate(thumbs.map(function(image, i){ return image + '?' + i }));
		}
		this.thumbs = {'hrefs': [], 'thumbnails': []};
		for (image in thumbs){
			var obj = thumbs[image] || {};
			var caption = (obj.caption) ? obj.caption.trim() : '';
			var href = (obj.href) ? obj.href.trim() : ((this.options.linked) ? this.options.hu + image : this.options.href);
			var thumbnail = image;
			this.thumbs.hrefs.push(href);
			this.thumbs.thumbnails.push(thumbnail);
		}
    this.num_items = this.thumbs.thumbnails.length;
		var loaded = this.thumbs.thumbnails.length;
		if (!loaded)
			return; 
		
		// events
		this.events = $H({'mousemove': []});


    // create thumbnails
		this.options.thumbnails = {};
		var el = this.slideshow.getElement(this.classes.get('thumbnails'));
		var thumbnails = (el) ? el.empty() : new Element('div', {'class': this.classes.get('thumbnails').substr(1)}).inject(this.slideshow);

		var div = thumbnails.getSize();
		this.height = this.options.height || div.y;
		this.width = this.options.width || div.x;
		this.a = this.image = this.slideshow.getElement('img') || new Element('img');
		this.a.set('styles', {'display': 'none', 'position': 'absolute', 'zIndex': 1});
		this.b = this.a.clone();
		thumbnails.setStyle('overflow', 'hidden');
		var ul = new Element('ul', {'tween': {'link': 'cancel'}}).inject(thumbnails);
		this.thumbs.thumbnails.each(function(thumbnail, i){
			var li = new Element('li').inject(ul);
			var a = new Element('a', {
				'events': {
					'loaded': function(){
						this.thumbs.thumbnails.pop();
						var div = thumbnails.getCoordinates();
						var props = thumbnails.retrieve('props');
						var limit = 0, pos = props[1], size = props[2];
						thumbnails.getElements('li').each(function(li){
							var li = li.getCoordinates();
							if (li[pos] > limit) limit = li[pos];
						}, this);
						thumbnails.store('limit', div[size] + div[props[0]] - limit);
					}.bind(this)
				},
        'rel':'lightbox',
 				'href': this.options.hu + thumbnail,
				'morph': $merge(this.options.thumbnails, {'link': 'cancel'})
			}).inject(li);
			var img = new Asset.image(this.options.hu + thumbnail, {
        'width':this.options.thumb_width,
        'height':this.options.thumb_height,
				'onload': function(){this.fireEvent('loaded');}.bind(a)
			}).inject(a);
		}, this);
		thumbnails.set('events', {
			'scroll': function(n, fast){
				var div = this.getCoordinates();
				var ul = this.getElement('ul').getPosition();
				var props = this.retrieve('props');
				var axis = props[3], delta, pos = props[0], size = props[2], value;
				var tween = this.getElement('ul').get('tween', {'property': pos});
				if ($chk(n)){
					var li = this.getElements('li')[n].getCoordinates();
					delta = div[pos] + (div[size] / 2) - (li[size] / 2) - li[pos]
					value = (ul[axis] - div[pos] + delta).limit(this.retrieve('limit'), 0);
					if (fast)
						tween.set(value);
					else
						tween.start(value);
				}
				else{
					var area = div[props[2]] / 3, page = this.retrieve('page'), velocity = -0.07;
					if (page[axis] < (div[pos] + area))
						delta = (page[axis] - div[pos] - area) * velocity;
					else if (page[axis] > (div[pos] + div[size] - area))
						delta = (page[axis] - div[pos] - div[size] + area) * velocity;
					if (delta){
						value = (ul[axis] - div[pos] + delta).limit(this.retrieve('limit'), 0);
						tween.set(value);
					}
				}
			}.bind(thumbnails),
			'update': function(fast){
				var thumbnails = this.slideshow.retrieve('thumbnails');
				thumbnails.getElements('a').each(function(a, i){
					if (i == this.slide){
						if (!a.retrieve('active', false)){
							a.store('active', true);
							var active = this.classes.get('thumbnails', 'active');
							if (fast) a.get('morph').set(active);
							else a.morph(active);
						}
					}
					else {
						if (a.retrieve('active', true)){
							a.store('active', false);
							var inactive = this.classes.get('thumbnails', 'inactive');
							if (fast) a.get('morph').set(inactive);
							else a.morph(inactive);
						}
					}
				}, this);
				if (!thumbnails.retrieve('mouseover'))
					thumbnails.fireEvent('scroll', [this.slide, fast]);
			}.bind(this)
		})
		var div = thumbnails.getCoordinates();
		thumbnails.store('props', (div.height > div.width) ? ['top', 'bottom', 'height', 'y'] : ['left', 'right', 'width', 'x']);
		var mousemove = function(e){
			var div = this.getCoordinates();
			if (e.page.x > div.left && e.page.x < div.right && e.page.y > div.top && e.page.y < div.bottom){
				this.store('page', e.page);
				if (!this.retrieve('mouseover')){
					this.store('mouseover', true);
					this.store('timer', function(){this.fireEvent('scroll');}.periodical(50, this));
				}
			}
			else {
				if (this.retrieve('mouseover')){
					this.store('mouseover', false);
					$clear(this.retrieve('timer'));
				}
			}
		}.bind(thumbnails);
		this.events.mousemove.push(mousemove);
		document.addEvent('mousemove', mousemove);
		this.slideshow.store('thumbnails', thumbnails);

		// begin show
		this._preload();
	},
	
	go: function(n, direction){
		if ((this.slide - 1 + this.thumbs.thumbnails.length) % this.thumbs.thumbnails.length == n || $time() < this.transition)
			return;		
		$clear(this.timer);
		this.delay = 0;		
		this.direction = (direction) ? direction : ((n < this.slide) ? 'right' : 'left');
		this.slide = n;
		this._preload(false);
	},

	_preload: function(fast){
		if (!this.preloader)
		 	this.preloader = new Asset.image(this.options.hu + this.thumbs.thumbnails[this.slide], {'onload': function(){
				this.store('loaded', true);
			}});
		if (this.preloader.retrieve('loaded') && $time() > this.delay && $time() > this.transition){
			this.image = (this.counter % 2) ? this.b : this.a;
			this.image.set('styles', {'display': 'block', 'height': 'auto', 'visibility': 'hidden', 'width': 'auto', 'zIndex': this.counter});
			['src', 'height', 'width'].each(function(prop){
				this.image.set(prop, this.preloader.get(prop));
			}, this);
			this.slideshow.retrieve('thumbnails').fireEvent('update', fast);
		  this.counter++;
		  this.delay = $time() + this.options.duration + this.options.delay;
		  this.direction = 'left';
		  this.transition = $time() + this.options.duration;
		  this.slide = (this.slide + 1) % this.num_items;
   		this._preload();
		}
		else {
			this.timer = this._preload.delay(100, this, fast);
		}
	}
});