jQuery(function() {

	var interval,
		currentPicNum = 1,
		nextPicNum = 2,
		currentThumb,
		totalPics = 0,
		currentPic,
		nextPic,
		numPics = 0,
		pause = 4000,
		fadeInAmt = 500,
		thumbOpacity = 0.5;
		imgPath = "images/",
		imgType = ".jpg",
		splashImage = jQuery("#feature-splash"),
		featurePics = jQuery("#feature-pics");

	
	jQuery(".feature-thumb").each(function()
	{
		totalPics++;
		var o = jQuery(this);
		var uri = imgPath+o.attr("id")+imgType;
		o.click(goToSlide);
		o.attr("id", "feature-t"+totalPics);

		var img = new Image();
		jQuery(img)
			.load(function () {

				numPics++;
			
				splashImage.css("opacity", 1-numPics/totalPics);

				if (numPics == totalPics)
				{
					splashImage.remove();
					startShow();
				}

				var a = jQuery("<a href='"+o.attr("rel")+"'></a>");
				a.append(jQuery(this));
				featurePics.append(a);
			
			})
			
			.error(function (e) {
				log("error"+e)
			})

			.attr('src', uri)
			.attr('id', "feature-pic-"+totalPics)				
			.attr('class', "feature-pic");

	});


	function goToSlide(e)
	{
		var i = jQuery(this).index()+1;
		if (i != currentPicNum)
		{
			pauseShow();
			nextPicNum = i;
			fadeInPic(fadeInAmt);
			currentPicNum = i;
			resumeShow();
		}
	}
	
	function pauseShow()
	{
		clearInterval(interval);
	}

	function resumeShow()
	{
		interval = setInterval(goNextPic, pause);	
	}

	
	function startShow()
	{
		currentPic = jQuery("#feature-pic-1");
		var p = currentPic;
		currentThumb = jQuery("#feature-t1");
		addTclass(currentThumb);
		p.fadeIn(fadeInAmt);	
		resumeShow();
	}
	
	function fadeInPic(s)
	{
		nextPic = jQuery("#feature-pic-"+nextPicNum);
		currentPic = jQuery("#feature-pic-"+currentPicNum);
		setThumb();
		featurePics.append(nextPic.parent().remove());
		nextPic.fadeIn(s, function(e)
		{
			currentPic.hide();
		});		
	}	
	
	function goNextPic()
	{

		if (currentPicNum > totalPics)
		currentPicNum = 1;	
		calcNext();
		fadeInPic(fadeInAmt);
		currentPicNum++;	
				
	}	

	function calcNext()
	{
		nextPicNum = currentPicNum+1;
		if (nextPicNum > totalPics)
		nextPicNum = 1;	
	}
	
	function setThumb()
	{
		removeTclass(currentThumb);		
		currentThumb = jQuery("#feature-t"+nextPicNum);		
		addTclass(currentThumb);		
	}
	
	function addTclass(t)
	{
		t.addClass("feature-thumb-on");	
	}
	
	function removeTclass(t)
	{
		t.removeClass("feature-thumb-on");		
	}
	

});
