// This code is copyright James Andrews 2010 all rights reserved.  Not for free use.

// attache the carousel function to jQUery.
jQuery.fn.fadeInOutCarousel = function()
{
	// Set the carousel container equal to relative.
	this.css('position','relative');
	var currentShownId = 1;
	var identifier = 1;
	var playing = true;
	var playInterval = 5000;
	var carouselObjs = Array();

	var carouselObjs = jQuery('.slide');

	// Set the position of all the carousel objects to absolute.
	jQuery(".slide").css('position','absolute');
	jQuery(".slide").css('top','1px');
	jQuery(".slide").css('left','1px');
	jQuery(".slide").css('display','none');
	jQuery(".slide").css('z-index','10');

	jQuery("#slide-"+currentShownId).css('display','block');
	
	// Set up the clickable navigation.
	jQuery(".tb-carousel-nav").click(function()
	{
		// Figure out what was clicked.
		splitId = this.id.split('-');
	 	identifier = splitId[splitId.length-1];

		// Control the navigation.
		switch(identifier)
		{
			case "p":
			    identifier =  parseInt(currentShownId)-1;
				if(identifier == 0) { identifier = carouselObjs.length; }
				break;
			case "n":
			    identifier =  parseInt(currentShownId)+1;
				if(identifier > carouselObjs.length) { identifier=1; }
				break;
			case "r":
				playing = true;
			    break;
			case "w":
				playing = false;
			    break;
			default:
		}

		if(identifier != "r" && identifier != "w" && !playing)
		{
			// change the view.
			viewControl(currentShownId, identifier);
		}
	});

	jQuery(".slide").click(function()
	{
		uri = this.getAttribute('href');
		if(uri)
		{
			window.location = uri;
		}
	});

	var viewControl = function(fromId, toId)
	{
		// If we are not currently showing that ID change to the new ID.
		if(toId != fromId)
		{
			jQuery("#slide-" + fromId).fadeOut();
			jQuery("#slide-" + toId).fadeIn();
			currentShownId = parseInt(toId);
			
			jQuery("#counter").val(parseInt(currentShownId));
		}
	}

	// Loop function.  Gets called so that we can loop the images.
	var playIfPlaying = function()
	{
		// if playing is true then go through
		// each item and display it as needed.
		if(playing)
		{
			identifier = currentShownId + 1;
			if(identifier == (carouselObjs.length + 1)) identifier = 1;
			if(identifier == 0) identifier = carouselObjs.length;
			viewControl(currentShownId, identifier);
		}

		setTimeout (function ()
		{
			playIfPlaying();
		}
	, playInterval );	
	}

	// do a set timeout and start things playin.
	setTimeout (function ()
	{
		playIfPlaying();
	}
	, playInterval );
	
};

