Carousel = Class.create();
Object.extend(Object.extend(Carousel.prototype, Abstract.prototype), {
	initialize: function(wrapper, options){
		this.scrolling  = false;
		this.wrapper    = $(wrapper);
		this.scroller   = this.wrapper.down('div.scroller');
		this.sections   = this.wrapper.select('div.section');
		this.controls   = this.wrapper.select('div.controls a');
		this.options    = Object.extend({
			duration: 1.0,
			frequency: 8
		}, options || {});

		this.sections.each( function(section, index) {
			section._index = index;
			if (index > 0) section.hide();
		});
		this.controls.each(function(link) {
			link.className = 'slide_menu_inactive';
		});
		this.controls[0].className = 'slide_menu_active';

		this.events = {
			click: this.click.bind(this)
		};

		this.addObservers();
		if(this.options.initialSection) this.moveTo(this.options.initialSection, this.scroller, {
			duration:this.options.duration
		});  // initialSection should be the id of the section you want to show up on load
	},

	addObservers: function() {
		this.controls.invoke('observe', 'click', this.events.click);
	},

	click: function(event) {
		var element = Event.findElement(event, 'a');
		if (this.scrolling) {
			this.scrolling.cancel();
		}

		this.moveTo(element.href.split("#")[1], this.scroller, {
			duration:this.options.duration
		});
		Event.stop(event);
		this.stop();
	},

	moveTo: function(element, container, options) {
		this.current = $(element);

		Position.prepare();
		var containerOffset = Position.cumulativeOffset(container),
		elementOffset = Position.cumulativeOffset($(element));

		this.sections.invoke('hide');
		this.scrolling = new Effect.Appear(this.current);

		currentElementId = this.current.id;
		this.controls.each(function(link) {
			link.className = (link.href.split("#")[1] == currentElementId)
				? 'slide_menu_active'
				: 'slide_menu_inactive';
		});

		return false;
	},

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

		this.moveTo(this.sections[nextIndex], this.scroller, {
			duration: this.options.duration
		});
	},

	previous: function() {
		if (this.current) {
			var currentIndex = this.current._index;
			var prevIndex = (currentIndex == 0) ? this.sections.length - 1 :
			currentIndex - 1;
		} else var prevIndex = this.sections.length - 1;

		this.moveTo(this.sections[prevIndex], this.scroller, {
			duration: this.options.duration
		});
	},

	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);
	}
});