/*
 * Prototype image slider by David Chambers
 * http://davidchambersdesign.com/prototype-image-slider/
 * { last updated: 14 November 2009 }
 *
 * Requires Prototype:
 * http://www.prototypejs.org/
 *
 * Requires script.aculo.us:
 * http://script.aculo.us/
 */

var Slider = Class.create({
	initialize: function (element, duration, n) {
		var children, l, dimensions, w = 0, h = 0, wrap, nav;
		element = $(element);
		children = element.childElements();
		l = children.length;
		if (n == undefined || isNaN(n)) {
			n = 0
		}
		else if (n < 0) {
			n = l + n;
			if (n < 0) {
				n = 0
			}
		}
		else if (n >= l) {
			n = 0
		}
		children.each(function (child) {
			dimensions = child.getDimensions();
			if (dimensions.width > w) {
				w = dimensions.width
			}
			if (dimensions.height > h) {
				h = dimensions.height
			}
		});
		wrap = new Element('div');
		wrap.setStyle({
			marginLeft: n * (-w-10) + 'px',
			width: children.length * (w+10) + 'px',
			height: h + 'px'
		});
		children.each(function (child) {
			child.setStyle({
				cssFloat: 'left',
				width: w + 'px',
				marginRight: '10px'
			});
			wrap.appendChild(child)
		});
		element.setStyle({
			width: w + 'px',
			overflow: 'hidden'
		});
		element.appendChild(wrap);

		this.duration = (duration == undefined ? 1.0 : duration);
		this.wrap = wrap;
		this.nav = nav;
		this.w = w+10; // width of each slide
		this.h = h; // height of each slide
		this.l = l; // number of slides in slide show
		this.n = n; // number of the active slide
		this.auto = false;
		this.interval = 5.0;

	},

	isFirst: function () {
		return (this.n == 0)
	},

	isLast: function () {
		return (this.n == this.l - 1)
	},

	slide: function () {
		new Effect.Morph(this.wrap, {
			style: 'margin-left: -' + this.n * this.w + 'px;',
			duration: this.duration
		})
		if(this.auto) setTimeout(function() {if(sl.auto) sl.next()},(this.interval+this.duration)*1000)
	},

	prev: function () {
		if(this.isFirst()) {
			this.n=this.l-1
			this.slide();			
			//e.stop()
		} else {
			this.n--;
			this.slide();
			//e.stop()
		}
	},

	next: function () {
		if(this.isLast()) {
			this.n=0
			this.slide();			
			//e.stop()
		} else {
			this.n++;
			this.slide();
			//e.stop()
		}
	},
	
	startAuto: function () {
		this.auto = true
		sltimer = setTimeout(function(){if(sl.auto) sl.next()},this.interval*1000)
	}
});
