var Carousel = new Class({
	Implements: [Options,Chain],
	
	obj: '',
	
	items: [],
	cloneIndex: 0,
	
	options: {
		css: 'grey',
		timeout: 20,
		step: 1
	},
	
	initialize: function(obj, options) {
		if ($type(obj)!='element') return false;
		
		this.obj = obj;
		this.setOptions(options);
	},
	
	create: function() {
		
		var wrapper = new Element('div',{
			'class': 'carousel-'+this.options.css
		}).wraps(this.obj);
		
		$each(this.obj.getChildren()[0].getChildren()[0].getChildren(), function(el, index) {
			var img = el.getChildren()[0].getChildren()[0];
			var morph = new Fx.Morph(img,{
				duration: 200,
				link: 'cancel'
			}).start('.nohover');
			img.setOpacity(.5).addEvents({
				'mouseenter': function() {
					morph.start('.hover-'+this.options.css);
					pause = true;
				}.bind(this),
				'mouseleave': function() {
					morph.start('.nohover-'+this.options.css);
					pause = false;
				}.bind(this)
			});
			this.items.push(el);
		}.bind(this));
		
		var scrollTo = 0;
		var pause = false;
	
		var timer = (function() {
			if (pause==true) return;
			
			this.chain(function() {
				wrapper.scrollTo(scrollTo,0);
				scrollTo += this.options.step;
			}.bind(this),
			function() {
				
				var containerWidth = this.obj.getParent().getStyle('width').toInt();
				var itemsWidth = this.obj.getStyle('width').toInt();
				
				if (scrollTo>=(itemsWidth-containerWidth-100)) {
					var clone = this.items[this.cloneIndex++].clone();
					clone.injectAfter(this.items[this.items.length-1]);
					
					var img = clone.getChildren()[0].getChildren()[0];
					var morph = new Fx.Morph(img,{
						duration: 200,
						link: 'cancel'
					}).start('.nohover');
					img.setOpacity(.5).addEvents({
						'mouseenter': function() {
							morph.start('.hover-'+this.options.css);
							pause = true;
						}.bind(this),
						'mouseleave': function() {
							morph.start('.nohover-'+this.options.css);
							pause = false;
						}.bind(this)
					});
					
					this.items.push(clone);
				}
			}.bind(this));
			
			while(this.$chain.length) this.callChain();
			
		}.bind(this)).periodical(this.options.timeout);
	}
});

