var Carousel = Class.create({			
	initialize: function(container, canvas, objects, period) {
	    this.container = container;
		this.canvas = canvas;
	    this.objects = objects;
		this.period = period;
		this._cycleTimer = null;
		this.current = 0;
		
		this._windowSize = 104;
		
		// setup the canvas and window
		var carouselWindow = this.container.childElements().find(function(obj) {
			return obj.hasClassName('window');
		});
		carouselWindow.setStyle({
			position: 'relative',
			height: this._windowSize + 'px',
			overflow: 'hidden',
			width: '100%'
		});
		
		// setup the canvas
		this.canvas.setStyle({
			position: 'absolute',
			top: '0',
			left: '0'
		});
		
		// set the article height (they have a 4px margin)
		this.objects.invoke('setStyle', {height: this._windowSize-5 + 'px'});
	},
	
	addSwitches: function() {
		carousel = this;
		this.switches = new Element('div', {'class': 'switches'});
		this.objects.each(function(obj, i) {
			var link = new Element('a', {href: '#'}).update(i+1);
			if (i == carousel.current) {
				link.addClassName('active');
			}
			link.observe('click', function(e) {
				carousel.switchTo(i);
				carousel.stop();
				Event.stop(e);
			});
			carousel.switches.insert(link, {position: 'bottom'});
		})
		this.container.insert(this.switches, {position: 'top'});
	},

	// start the cycle
	start: function() {
		this.started = true;
		var oThis = this;
		var cycleFunc = function() { oThis.cycle(); }
		this._cycleTimer = new PeriodicalExecuter(cycleFunc, this.period);
	},
	
	// stop the cycle
	stop: function() {
		this.started = false;
		//window.clearTimeout(this._cycleTimer);
		if (this._cycleTimer !== null) {
			this._cycleTimer.stop();
		}
	},
	
	// changes the panels
	switchTo: function(to) {
		this.current = to;
		var ypos = to*-this._windowSize;
		new Effect.Move(this.canvas, {x: 0, y: ypos, mode: 'absolute'});
		/*this.objects.each(function(obj,i) {
			if (to == i) {
				obj.show();
			} else {
				obj.hide();
			}
		});*/
		this.setActive(to);
	},
	
	// does cycle
	cycle: function() {
		var to = ++this.current;
		if (this.objects.size() <= to) {
			to = 0;
		}
		this.switchTo(to);
	},
	
	// actives the switch link
	setActive: function(i) {
		if (this.switches !== null && this.switches.childElements().size() >= i && i >= 0) {
			this.switches.childElements().each(function (obj, j) {
				if (i == j) {
					obj.addClassName('active');
				} else {
					obj.removeClassName('active');
				}
			});
		}
	}
});