var allCarousels=Array();

function initCarousels() {
	allCarouselDivs=$$('div.carousel_container');
	if (getFirst(allCarouselDivs)!=null) {
		for (i=0; i<allCarouselDivs.length; i++) {
			allCarousels[i]=new Carousel(allCarouselDivs[i]);
		}
	} else {
		allCarousels=Array();
	}
}

function getFirst(ary) {
	if (typeof ary=="undefined") return null;
	if (ary==null) return null;
	if ( (typeof ary!="object") && (typeof ary!="function") ) return null;
	if (ary.length==0) return null;
	return ary[0];
}

var carouselAnimating=false;

function Carousel(parentObj) {
	this.parentObj=$(parentObj);
	this.button=Array();
	this.button[0]=getFirst(this.parentObj.select(".carousel_left"));
	this.button[1]=getFirst(this.parentObj.select(".carousel_right"));
	uls=this.parentObj.getElementsByTagName("ul");
	this.ul=getFirst(uls);
	if (this.ul!=null) {
		this.lis=this.ul.getElementsByTagName("li");
	} else {
		alert("Unable to identify the unordered list in the carousel.");
		if (uls==null) {
			alert("uls: null");
		} else {
			alert("uls: "+typeof uls);
		}
		return false;
	}
	
	// Register this instance with the buttons.
	this.button[0].carousel=this;
	this.button[1].carousel=this;
	
	this.button[0].onclick=function() {
		this.carousel.scrollClicked(-1);
		return false;
	}
	this.button[1].onclick=function() {
		this.carousel.scrollClicked(1);
		return false;
	}
	
	// Calculate the total width of the lis
	this.totalWidth=0;
	for (ci=0; ci<this.lis.length; ci++) {
		this.totalWidth+=this.lis[ci].clientWidth;
	}
	
	this.displayWidth=this.ul.parentNode.clientWidth;
	
	this.maxX=this.totalWidth-this.displayWidth;
	if (this.maxX<0) this.maxX=0; // Don't let it drop smaller than zero.
	
	this.ul.style.width=this.totalWidth+"px";
	
	this.enableDisable(0);
}

Carousel.prototype.enableDisable=function(xPos) {
	if (xPos>=0) {
		this.button[0].addClassName("disabled");
	} else {
		this.button[0].removeClassName("disabled");
	}
	
	if (xPos<=0-this.maxX) {
		this.button[1].addClassName("disabled");
	} else {
		this.button[1].removeClassName("disabled");
	}
}

Carousel.prototype.scrollClicked=function(amount) {
	if (!carouselAnimating) {
		x=this.ul.offsetLeft; // Get the current position
		x-=amount*this.displayWidth; // Figure out the desired more
		if (x>0) x=0; // Don't left it move off the right.
		if (x<0-this.maxX) x=0-this.maxX; // Don't let it move off the left.
		
		this.enableDisable(x);
		
		carouselAnimating=true; // Raise the animating flag.
		
		new Effect.Move(this.ul, { x: x, y: 0, mode: 'absolute', afterFinish: function() { carouselAnimating=false; } });
	}
}
