var HorzScroller = Class.create();
HorzScroller.prototype = {
	containerId: 0,
	size: 0,
	width: 0,
	current: 0,
	xPos: 0,
	targetPos: 0,
	animation: {
		repeat: 30,
		dynamic: 20,
		constant: 4
	},
	buttons: [],
	initialize: function(containerId, numElements, itemWidth) {
		this.containerId = containerId;
		this.size = numElements,
		this.width = itemWidth,
		$(this.containerId).style.width = (this.width * this.size) + "px";
		return this;
	},	
	slideTo: function(index) {
		if ((index == this.current) || (index < 0) || (index > this.size - 1)) {
		   return;
        }
		this.current = index;
		this.targetPos = this.current * this.width; 
		this.updatePos();
		this.updateButtons();
	},
	updatePos: function() {
		if (this.targetPos < this.xPos) {
			this.xPos = Math.max(this.xPos + ((this.targetPos - this.xPos) / this.animation.dynamic) - this.animation.constant, this.targetPos);
		} else {
			this.xPos = Math.min(this.xPos + ((this.targetPos - this.xPos) / this.animation.dynamic) + this.animation.constant, this.targetPos);
		}
		$(this.containerId).style.marginLeft = -this.xPos + "px";
		if (this.xPos != this.targetPos) {
			setTimeout(this.updatePos.bind(this), this.animation.repeat);
		}
	},
	next: function() {
		this.slideTo(this.current + 1);
	},
	prev: function() {
		this.slideTo(this.current - 1);
	},
	setButtons: function(newButtons) {
		this.buttons = newButtons;
		this.updateButtons();
	},
	updateButtons: function() {
		for (i = 0; i < this.buttons.length; i++) {
			if (!this.buttons[i]) continue;
			this.buttons[i].update(this.current, this.size);
		}			
	}
};

var ButtonController = Class.create();
ButtonController.prototype = {
	id: 0,
	first: false,
	visible: false,
	animation: {
		duration: 1.0,
		transition: Effect.Transitions.linear
	},
	initialize: function(id, isFirst) {
		this.id = id;
		this.first = isFirst;
		return this;
	},
	calcVisibility: function(itemIndex, numItems) {
		if (this.first) {
			return itemIndex > 0;
		} else {
			return itemIndex < numItems - 1;
		}
	},
	update: function(itemIndex, numItems) {
		if (this.calcVisibility(itemIndex, numItems) == this.visible) {
			return;
		}
		this.visible = !this.visible;
		if (this.visible) {
			$(this.id).style.visibility = "visible";
			fromOpacity = 0.0;
			toOpacity = 1.0;
		} else {
			fromOpacity = 1.0;
			toOpacity = 0.0;				
		}
		new Effect.Opacity(this.id, 
			{ 
				duration: this.animation.duration, 
				transition: this.animation.transition, 
				from: fromOpacity, 
				to: toOpacity 
			});
	}
};

