var wrapper;
var carousel;
var items;
var item_width = 182 + 20; // The full width of a single item (incl. borders, padding, etc ... if there is any)
var max_margin;
var animation;

function next_item(pos){
	if(pos == -max_margin){
		animation.start('left', 0);
	} else {
		var newposition = pos - item_width;
		animation.start('left', newposition);
	}
}

function previous_item(pos){
	if(pos == 0){
		animation.start('left', -max_margin);
	} else {
		var newposition = pos + item_width;
		animation.start('left', newposition);
	}
}

function scroll_to_index(pos){
	newpos = 0 - ((pos - 1) * item_width);
	animation.start('left', newpos);
}

window.addEvent('load', function() {
	wrapper = $('scroller_frame'); // The outer wrapper
	carousel = $('scroller_contents'); // The inner wrapper
	items = $$('#scroller_contents li'); // The different elements, this is an array
	max_margin = items.length * item_width - item_width;
	animation = new Fx.Tween(carousel, {duration: 500, onStart: function(){
		$$('#scroller_control ul li a.active').each(function(item) {
			item.removeClass('active');
		});
	}, onComplete: function(){
		pos_index = -(parseInt(carousel.getStyle('left')) / item_width);
		$$('#scroller_control ul li a')[pos_index].addClass('active');
	}});
	
	$$('#scroller_control ul li a')[0].addClass('active');
	
	$('img_scroller_right').addEvent('click', function(e){
		var event = new Event(e);
		var position = parseInt(carousel.getStyle('left'));
		next_item(position);
		event.stop();
	});

	$('img_scroller_left').addEvent('click', function(e){
		var event = new Event(e);
		var position = parseInt(carousel.getStyle('left'));
		previous_item(position);
		event.stop();
	});
	
	pills = $$('#scroller_control ul li a');
	for (i = 0; i < pills.length; i++) {
		pills[i].rel = i+1;
		pills[i].addEvent('click', function(e) {
			var event = new Event(e);
			scroll_to_index(event.target.rel);
			event.stop();
		});
	}
	
	//$('pill_box').setStyle('width', pills.length * 15 + 'px');
});