// Revealing Module Pattern
// Namespace
var carousel = function()
{
	// Configuration objects. Use for constants
	var o_config = {
		i_periodicalTimer : 7000,
		i_slideDuration : 1000
	};

	// Private variables
	var o_homepageCarousel;
	var i_carouselWidth;
	var i_slideWidth;
	var o_tween;
	var i_totalItems;
	var i_currentItem = 1;
	var b_direction = 1;
	
	// Private functions
	var init = function(o_carouselElement)
	{
		// Assign variables
		o_homepageCarousel = $('carousel').getElement('#homepageCarousel');
					
		// Calculate and set total width of o_homepageCarousel
		i_slideWidth = parseFloat(o_carouselElement.getStyle('width'));	
		i_totalItems = o_homepageCarousel.getElements('.carouselItem').length;								
		i_carouselWidth = i_slideWidth * i_totalItems;
		
		o_homepageCarousel.setStyle('width', i_carouselWidth);
								
		// Periodical function from mootools
		start.periodical(o_config.i_periodicalTimer);	
	};
	
	var start = function()
	{
		// Determine direction
		if(i_currentItem == 1)
		{
			b_direction = 1;
		}
		
		if(i_currentItem == i_totalItems)
		{
			b_direction = -1;
		}

		// Reduce or Increase counter to match the direction		
		if(b_direction == 1)
		{
			i_currentItem++;
		}
		else
		{
			i_currentItem--;
		}		
	
		// Determine position to slide to
		i_position = -((i_currentItem * i_slideWidth) - i_slideWidth); 
		
		// Gogo tween
 		o_tween = new Fx.Style(o_homepageCarousel, 'margin-left', 
		{
			duration: o_config.i_slideDuration,
			transition: Fx.Transitions.Cubic.easeOut
		});
		o_tween.start(i_position);
	};

	// Make functions public
	return{
		init : init
	};
}();

window.addEvent('domready', function()
{
	// Check if carousel exists
	if($('carousel'))
	{
		// Init carousel
		carousel.init($('carousel'));
	}
});
