/**
 * Slidr.js
 * Copyright (c) Fluid Creativity, 2009
 *
 * Implements a slider which scrolls content horizontally pausing between each internal element
 */

var Slidr = new Class({

	Implements: [Options, Events],

	options: {
		slideDelay: 3000,
		slideDuration: 500,
		slideWidth: 100,
		transition: 'quad',
		canPause: false
	},

	initialize: function (el, options) {
		this.el = $(el);
		this.setOptions(options);
		this.setupComponent();
	},

	setupComponent: function() {
		// Container element
		this.slider = new Element('div').setStyles({ 'position': 'relative', 'overflow': 'hidden', 'width': this.el.getParent().getWidth() }).wraps(this.el);

		// Add events
		if (this.options.canPause) {
			this.el.addEvents({
				'mouseenter': function(e) {
					this.store('mouseOver', true);
				},
				'mouseleave': function(e) {
					this.eliminate('mouseOver');
				}
			});
		}
	},

	getInternalWidth: function() {
		var width = 0;

		this.el.getChildren().each(function(el) {
			width += el.getWidth() + el.getStyle('margin-left').toInt();
		});

		return width;
	},

	start: function() {
		var internalWidth = this.getInternalWidth();

		if (internalWidth > this.el.getSize().x) {
			this.el.setStyles({
				'width': internalWidth,
				'position': 'relative'
			});

			this.el.set('tween', {
				duration: this.options.slideDuration,
				transition: this.options.transition,
				link: 'cancel',
				onComplete: function() {
					this.el.setStyle('left', 0).getFirst().dispose().removeClass('firstItem').inject(this.el);
					this.el.getFirst().addClass('firstItem');

					this.slideComponent.delay(this.options.slideDelay, this);
				}.bindWithEvent(this)
			});

			this.slideComponent.delay(this.options.slideDelay, this);
		}
	},

	slideComponent: function() {
		if (this.slider) {
			if (this.el.retrieve('mouseOver')) {
				this.slideComponent.delay(1000, this);
			} else {
				this.el.tween('left', -this.options.slideWidth);
			}
		}
	},

	toElement: function() {
		return ($defined(this.slider) ? this.slider : this.el);
	}
});

