window.addEvent('domready', function() { 

	var wrapper = $('carouselwrapper'); // The outer wrapper
	var carousel = $('carousel'); // The inner wrapper
	var items = $$('#carousel li'); // The different elements, this is an array
	var item_width = 228; // The full width of a single item (incl. borders, padding, etc)
	var max_margin = (items.length-1) * item_width;

	carousel.style.width = String(items.length * item_width) + "px";
	for(var i = 0; i < items.length/3; i++) { // Add a dot for each page of mini-grants
		$('controls').innerHTML += "<img src='images/minigrant-dot-hollow.gif' />"; }
	var dots = $$('#controls img');
	dots[0].src = "images/minigrant-dot-solid.gif";
	var current_page = 0;
	
	var animation = new Fx.Tween(carousel, {duration: 500, transition: Fx.Transitions.Cubic.easeInOut}); //more customization at: http://mootools.net/docs/Fx/Fx
	
	// Update the dots
	function update_dots(pos) {
		dots[current_page].src = "images/minigrant-dot-hollow.gif";
		current_page = Math.ceil(-pos*items.length/3/(max_margin+item_width));
		dots[current_page].src = "images/minigrant-dot-solid.gif";
	}
	
	// The function to browse forward
	function next_item(pos){
		var next_pos;
		if(pos == -max_margin+2*item_width) { next_pos = 0; }
		else if(pos == -max_margin+3*item_width) { next_pos = pos - item_width; }
		else if(pos == -max_margin+4*item_width) { next_pos = pos - 2*item_width; }
		else { next_pos = pos - 3*item_width; }

		animation.start('left', next_pos);
		update_dots(next_pos);
	}
	
	// The function to browse backward
	function previous_item(pos){
		var next_pos;
		if(pos == 0) { next_pos = -max_margin+2*item_width; }
		else if(pos == -item_width || pos == -2*item_width) { next_pos = 0; }
		else { next_pos = pos + 3*item_width; }
		
		animation.start('left', next_pos);
		update_dots(next_pos);		
	}
	
	// Set up the 'next' and 'previous' buttons
	$('next').addEvent('click', function(e){
		e.stop();
		next_item(parseInt(carousel.getStyle('left')));
	});
	$('previous').addEvent('click', function(e){
		e.stop();
		previous_item(parseInt(carousel.getStyle('left')));
	});
	
});