jQuery(document).ready( function()
{

		var images = [];
		var currentIndex = 0;
		var prevIndex = null;
		var isFading = false;
		var timer;
		
		// --- Lets Start By Getting All The Images
		var slider = $("#preamble > div");
		var list = $("#slide-refs li")
		var slides = $(".slide", slider);
		var images = $("img", slides);

		// --- Add click states the LI's
		jQuery.each(list, function(i)
		{
			$(this).bind('click', function()
			{
				moveTo(i);
			});
		});
		
		// --- Hide all but the top one
		jQuery(".slide:not(:nth-of-type(1))").toggle();
		
		// --- Add in the Left & Right Nav if there are more than 1 images
		if(slides.length>1)
		{
			// ---- Start the interval
			play()
			
			// ---- Clear interval if on hover
			slider.bind('mouseover', function()
			{
				clearInterval(timer);
			})
			
			// ---- Restart If Not
			slider.bind('mouseleave', function()
			{
				play();
			})
		
			prevIndex = images.length;
			/* $("<a class='prev' href='#'>Previous</a>").bind('click', movePrev).appendTo("#slides");
			$("<a class='next' href='#'>Next</a>").bind('click', moveNext).appendTo("#slides"); */
		}
		
		function moveTo(i)
		{
			clearInterval(timer)
			timer = setInterval(function() { moveNext() }, 5000);
			fadeIndex = i;
			changeImage(fadeIndex);
			return false;
		}
		
		function moveNext()
		{
			fadeIndex = (currentIndex >= slides.length-1) ? 0 : currentIndex+1
			changeImage(fadeIndex);
			return false;
		}
		
		function movePrev()
		{
			fadeIndex = (currentIndex == 0) ? slides.length-1 : currentIndex-1
			changeImage(fadeIndex);
			return false;
		}
		
		function play()
		{
			clearInterval(timer)
			timer = setInterval(function() { moveNext() }, 5000);
		}
		
		/* ---------- [ FUNC: Change The Image ] ----------- */
		function changeImage(index)
		{
			// ---- Reassign The Indexes
			prevIndex = currentIndex;
			currentIndex = index;
			
			$(list).eq(prevIndex).removeClass("active");
			$(list).eq(currentIndex).addClass("active");
			// --- Lets make sure the next image has loaded before we start the fade.
			var imgToFadeIn = images.eq(index)
			var src = imgToFadeIn.attr("src");

			if(!isFading)
			{

				isFading = true;
				$(slides[prevIndex]).fadeOut(500, function()
				{
					
				})
				
				$(slides[index]).fadeIn(200, function()
				{
					isFading = false;
				})	

			}

		
			/*var src = o.attr("href");
			$(description).html("<p>" +  o.attr("title") + "</p>");
			var img = $("<img />").attr('src', src).load(function() {
			loader.toggle();
			$(viewer).html(img);*/
			
		  }
		
	})
