/**
 * @author mark.gerrard
 */
var mCarousel = new Class({
	options: {
		prevBtn: 'prev',
		nextBtn: 'next',
		anim: {
			amount: 4,
			effect: Fx.Transitions.Cubic.easeInOut,
			duration: 500
		},
		item: {
			klass: 'item',
			width: 142
		},
		onPrevious: Class.empty,
		onNext: Class.empty
	},
	initialize: function(container, options) {
		this.setOptions(options);
		
		this.container = $(container);
		this.aItems = $A($(container).getElements('.'+this.options.item.klass));
		
		this.pastItems = 0;
		
		this.prepareItems();
		
		$(this.options.nextBtn).addEvent('click', function(e) {
			new Event(e).stop();
			this.next();
		}.bind(this));
		
		$(this.options.prevBtn).addEvent('click', function(e) {
			new Event(e).stop();
			this.previous();
		}.bind(this));
	},
	prepareItems: function() {
		opts = this.options;

		this.container.width = (this.aItems.length * this.options.item.width);
		
		anim = this.options.anim;
		this.container.fx = this.container.effects({duration: anim.duration, transition: anim.effect, wait: false});
		this.container.setStyles({
			width: this.container.width
		}, this);
		this.pastItems = 0;
	},
	next: function() {
		if(this.pastItems+this.options.anim.amount == this.aItems.length) {
			this.pastItems = 0;
		} else if (this.aItems.length - (this.pastItems+this.options.anim.amount) < this.options.anim.amount) {
			this.pastItems += (this.aItems.length-this.pastItems)-this.options.anim.amount;
		} else {
			this.pastItems+= this.options.anim.amount;
		}
		
		this.animate(this.pastItems);
		
		this.fireEvent('onNext');
	},
	previous: function() {
		if(this.pastItems == 0) {
			this.pastItems = this.aItems.length - this.options.anim.amount;
		} else if (this.pastItems < this.options.anim.amount) {
			this.pastItems -= this.pastItems;
		} else {
			this.pastItems -= this.options.anim.amount;
		}
		
		this.animate(this.pastItems);
		this.fireEvent('onPrevious');
	},
	animate: function(shiftNo) {
		this.container.fx.start({'left': - shiftNo * this.options.item.width});
	}
});

mCarousel.implement(new Options, new Events);