var index = 0;
var count = 0;
var pe;
var anim = false;
var interval = 5;

document.observe('dom:loaded', function() {
	count = $('horizontal_carousel').down('ul').childElements().length;
	// alert(count);
	$$('.previous_button').invoke('observe', 'click', moveContainerPrevious);
	$$('.next_button').invoke('observe', 'click', moveContainerNext);
	startPe();
});

moveContainerNext = function(e) {
	if(anim == false) {
		anim = true;
		pe.stop();
		trackIndex('next');
		var w = $('horizontal_carousel').down('li').getWidth();
		if(index == count) {
			w = -1*w*(count - 1);
			index = 0;
		}
		new Effect.Move($('horizontal_carousel').down('ul'), { x: -w, mode: 'relative', duration: 0.3, afterFinish: function(e) { anim = false; startPe(); } });
	}
}

moveContainerPrevious = function(e) {
	if(anim == false) {
		anim = true;
		pe.stop();
		trackIndex('prev');
		var w = $('horizontal_carousel').down('li').getWidth();
		if(index < 0) {
			w = -1*w*(count - 1);
			index = count - 1;
		}
		new Effect.Move($('horizontal_carousel').down('ul'), { x: w, mode: 'relative', duration: 0.3, afterFinish: function(e) { anim = false; startPe(); } });
	}
}

trackIndex = function(dir) {
	if(dir == "next")
		index++;
	else
		index--;
}

startPe = function() {
	pe = new PeriodicalExecuter(moveContainerNext, interval);
}