//  Mootools Carousel Object - Written by Kristofer Baxter (kris@intellistrand.com)
//  Note, this does not support periodic movement of objects, but can be extended to do so.
//  Requirements: Mootools v1.1+ - Current Example Page, http://horry.ifg.net/

//  Example Call:
//  new Carousel(elements(as mootools objects), triggers(as mootools objects), {options})
//	new Carousel($$('div#carousel div'), $$('div#carousel-control li'), $('next'), $('previous'), {elementSize: 360, fxDuration: 1000});
	
var Carousel = new Class({

	setOptions: function(options){
		this.options = {
			activeImage: '/media/carousel/periodicActive.gif',
			inactiveImage: '/media/carousel/periodic.gif',
			fxStyle: 'margin-left',
			fxDuration: 300,
			elementSize: (this.elements[0].getStyle('width').toInt() + this.elements[0].getStyle('padding-right').toInt()),
			defaultElement: $random(0, (this.count-1))
		}
		Object.extend(this.options, options || {});
	},

	initialize: function(elements, triggers, next, previous, options){
		this.elements = elements;
		if (this.elements.length > 1) {
			this.triggers = triggers;
			this.count = triggers.length;
			this.setOptions(options);
			this.fx = new Fx.Style(this.elements[0].getParent(), this.options.fxStyle, {duration: this.options.fxDuration});
			this.fx.now = 0;
			this.showing = this.options.defaultElement;
			this.active = true;
			this.setActive(0);
		
			this.triggers.each(function(el, index) {
				el.addEvent('click', function(e) {
					var temp = this.showing;
					this.showing = index;
					this.setActive(temp);
				}.pass([el, index], this));
			}, this);
		
			next.addEvent('click', function(e) {
				var temp = this.showing;
				this.showing = (this.showing >= (this.count-1)) ? 0 : (this.showing+1);
				this.setActive(temp);
			}.pass([next], this));
		
			previous.addEvent('click', function(e) {
				var temp = this.showing;
				this.showing = (this.showing > 0) ? (this.showing-1) : (this.count-1);
				this.setActive(temp);
			}.pass([next], this));
		}
	},

	setActive: function(oldvalue) {
		if (this.isActive()) {
			this.hault();
			var newSize = -1 * (this.options.elementSize * this.showing);
			this.fx.start(this.fx.now.round(), newSize);
			this.triggers[oldvalue].getFirst().src = this.options.inactiveImage;
			this.triggers[this.showing].getFirst().src = this.options.activeImage;
			this.restart();
		}
	},
	
	isActive: function() {
		return this.active;
	},
	
	hault: function() {
		this.active = false;
	},
	
	restart: function() {
		this.active = true;
	}
});
