var ShowReel = new Class({

	Implements: Options,
	
	options: {
		speed		: 5000
	},

	initialize: function(view,items,options){
		
		//Extend Array Class
		Array.implement({
			randomize: function() {
				return this.sort(function() {return 0.5 - Math.random();});
			}
		});
		
		//Set Options
		this.setOptions(options);
		
		//Define variables
		this.current 	= 0;
		this.viewport 	= view;
		this.items		= this.buildItems(items.randomize());
		this.length		= items.length;
				
		this.next();
		
		if (this.length > 1) {
		
			var loop = this.next.periodical(this.options.speed,this);
			
			//cancel loop
			this.items.each(function(item){
				item.item.addEvents({
					'mouseenter'		: function()
					{
						$clear(loop);
						this.current = item.key;
						this.next();
					}.bind(this),
					'mouseleave'		: function()
					{
						loop = this.next.periodical(this.options.speed,this);
					}.bind(this)
				});
			}.bind(this));
		
		}
		
	},
	
	buildItems: function(items)
	{
		var result = new Hash();
		items.each(function(item,key){
			result.set('item_' + key, new Hash({
				'key'		: key,
				'base'		: '/afbeeldingen/',
				'image'		: item.getElement('a').get('rel'),
				'title'		: item.getElement('a').get('title'),
				'img'		: item.getElement('img'),
				'link'		: item.getElement('a').get('href'),
				'item'		: item
			}));
		});
		return result;
	},
		
	next: function(){
		
		var current = this.items.get('item_' + this.current);
				
		//empty viewport
		this.viewport.empty();
		
		//create new image element
		var image = new Element('img');
		
		image.set('src',current.base + 'BR_' + current.image)
		.setStyles({
			'position'		: 'relative',
			'z-index'		: 0,
			'cursor'		: 'pointer'
		})
		.inject(this.viewport)
		.fade('hide')
		.fade('in')
		.addEvent('click',function(){
			if (!current.link.contains('jpg')) window.location = current.link;
		});
		
		//create new title element
		var title = new Element('div');
		
		title.set('html',current.title)
		.setStyles({
			'position'		: 'absolute',
			'bottom'		: 0,
			'left'			: 0,
			'right'			: 0,
			'font-size'		: 12,
			'font-weight'	: 'bold',
			'background'	: 'url(/assets/images/black.png) repeat',
			'color'			: '#ffffff',
			'padding'		: 10,
			'z-index'		: 5,
			'cursor'		: 'pointer'
		})
		.inject(this.viewport)
		.fade('hide')
		.fade('in')
		.addEvent('click',function(){
			if (!current.link.contains('jpg')) window.location = current.link;
		});
				
		//change all icons to gray
		this.items.each(function(item){
			item.img.set('src',item.base + 'GS_SR_' + item.image);
		});
		
		//change active icon
		current.img.set('src',current.base + 'SR_' + current.image);
		
		this.current++;
		if (this.current >= this.length) this.current = 0;
	}

});

window.addEvent('load',function(){
	var showreel = new ShowReel($('showreel-big'),$$('.showreel-item'));
});
