var BannerRotator = function()
{
	var numberOfItems = null;
	var currentItem = null;
	var currentTicket = null;
	var playing = null;
	
	this.init = function()
	{
		this.numberOfItems = $('#homepage-banners .homepage-banner-image').length;
		
		if(this.numberOfItems > 0)
		{
			this.currentItem = 1;
			this.playing = true;
			this.start();
		}
		
		var ref = this;
		$('#homepage-banner-next').click(function(){
			ref.showNext();
		});
		
		$('#homepage-banner-previous').click(function(){
			ref.showPrevious();
		});
		
		$('#homepage-banner-play-pause').click(function(){
			if(ref.playing)
			{
				ref.stop();
				ref.playing = false;
				$(this).find('img').attr('src', '/img/play-button.png').attr('alt', 'Play');
			}
			else
			{
				ref.start();
				ref.playing = true;
				$(this).find('img').attr('src', '/img/pause-button.png').attr('alt', 'Pause');
			}
		})
		
		$('#homepage-banners .image-selector .control').each(function(index){
			$(this).click(function(){
				// Add 1 because array from jQuery is 0 indexed, but our images are 1 indexed.
				ref.switchTo(index + 1);
			});
		})
	}
	
	this.start = function()
	{
		var ref = this;
		this.currentTicket = setTimeout(function(){
			ref.showNext();
		}, 6000);
	}
	
	this.showNext = function()
	{
		var next = this.currentItem + 1;
		if(next > this.numberOfItems)
		{
			next = 1;
		}
		
		this.switchTo(next);
	}
	
	this.showPrevious = function()
	{
		var prev = this.currentItem - 1;
		if(prev < 1)
		{
			prev = this.numberOfItems;
		}
		
		this.switchTo(prev);
	}
	
	this.switchTo = function(itemNumber)
	{
		this.stop();
		
		var oldItem = this.currentItem;
		
		$('#homepage-banner-image-' + itemNumber).fadeIn('slow');
		$('#homepage-banner-image-' + oldItem).fadeOut('slow');
		this.currentItem = itemNumber;
		
		// Don't automatically load the next item if we are currently paused.
		if(this.playing)
		{
			this.start();
		}
	}
	
	this.stop = function()
	{
		clearTimeout(this.currentTicket);
	}
}
