/** 
 * @description		carousel plugin for prototype.js
 * @author		Victor Stanciu; contact [at] victorstanciu [dot] ro; http://www.victorstanciu.ro/ 
				inspired by Glider.js by Bruno Bornsztein - http://missingmethod.com/projects/glider.html
 * @version		0.2
 * @date		26/02/08
 * @requires		prototype.js 1.6, effects.js 1.8
*/

Carousel = Class.create(Abstract, {

	initialize: function (scroller, slides, options) {

		this.scrolling	= false;
		this.scroller	= scroller;
		this.slides		= slides;

		this.options    = Object.extend({ duration: 0.5, frequency: 3 }, options || {});

		this.slides.each(function(slide, index) {
			slide._index = index; 
			});

		if (this.options.auto) {
			this.start();
			}

		},
	
	moveTo: function (element) {

		this.previous= this.current ? this.current : this.slides[0];
		this.current = $(element);

		var scrollerOffset = this.scroller.cumulativeOffset();
		var elementOffset = this.current.cumulativeOffset();
		this.scrolling = new Effect.SmoothScroll(this.scroller, {duration: this.options.duration, x: (elementOffset[0] - scrollerOffset[0]), y: (elementOffset[1] - scrollerOffset[1])});

		return false;

		},

	next: function () {
		if (this.current) {
			var currentIndex = this.current._index;
			var nextIndex = (this.slides.length - 1 == currentIndex) ? 0 : currentIndex + 1;      
			} else {
				var nextIndex = 1;
				}	

		if (nextIndex == 0) {
			this.scroller.scrollLeft = 0;
			nextIndex = 1;
			}

		this.moveTo(this.slides[nextIndex]);
		},


	stop: function () { clearTimeout(this.timer); },
	
	start: function () { this.periodicallyUpdate(); },
		
	periodicallyUpdate: function () {
		if (this.timer != null) {
			clearTimeout(this.timer);
			this.next();
			}
		this.timer = setTimeout(this.periodicallyUpdate.bind(this), this.options.frequency * 1000);
		}

	});

Effect.SmoothScroll = Class.create();

Object.extend(Object.extend(Effect.SmoothScroll.prototype, Effect.Base.prototype), {

	initialize: function (element) {
		this.element = $(element);
		var options = Object.extend({ x: 0, y: 0, mode: 'absolute' } , arguments[1] || {});
		this.start(options);
		},

	setup: function () {
		if (this.options.continuous && !this.element._ext ) {
			this.element.cleanWhitespace();
			this.element._ext = true;
			this.element.appendChild(this.element.firstChild);
			}
   
		this.originalLeft = this.element.scrollLeft;
		this.originalTop = this.element.scrollTop;

		if (this.options.mode == 'absolute') {
			this.options.x -= this.originalLeft;
			this.options.y -= this.originalTop;
			}
		},

	update: function (position) {   
		this.element.scrollLeft = this.options.x * position + this.originalLeft;
		this.element.scrollTop  = this.options.y * position + this.originalTop;
		}

	});