// Custom slideshow
// Chris @ Anywhichway 2010
//
// usage $(thumbs).boydSlides(), where thumbs are a collection of links to images


jQuery.fn.boydSlides = function(options) {

	var defaults = {
			inProgress: false,
			firstRun: true
		},
		options = $.extend({}, defaults, options),
		pick = function(event) {

			event.preventDefault();

			if (options.inProgress || $(this).is(".current")) return;

			options.inProgress = true;

			switchImages.apply(this);
			scrollThumbs.apply(this);

		},
		switchImages = function() {

			var $container = $("#image"),
				$target = $("#full"),
				targetSrc = $(this).attr("href"),
				$thumb = $(this),
				instateNew = function() {

					$(this)
						.remove();

					$("#inserted")
						.prop("id", "full");

					options.inProgress = false;

				};

			$thumb
				.addClass("current")
				.fadeTo(200, 1)
			.siblings("a")
				.removeClass("current")
				.each(turnDown);

			$container
				.append("<img src='" + targetSrc + "' id='inserted' />");

			$("#inserted")
				.fadeIn(100);

			$target
				.fadeOut(
					100,
					instateNew
				);

		},
		scrollThumbs = function() {

			var $container = $("#container"),
				$thumbs = $("#thumbs"),
				$thumb = $(this),
				totalWidth = $thumbs.width(),
				thumbX = $thumb.offset().left,
				containerX = $container.offset().left,
				newContainerX = (containerX - thumbX) + (totalWidth / 2);


			$container.animate(
				{
					left: (newContainerX < 0) ? newContainerX : 0
				},
				400
			);


		},
		preload = function() {

			(new Image()).src = $(this).addClass(options.firstRun ? "current" : "").prop("href");
			options.firstRun = false;

		},
		turnDown = function() {

			$(this)
				.fadeTo(0, 0.6);

		};

	return $(this)
		.each(preload)
		.click(pick)
	.not(".current")
		.each(turnDown)
	.end();

};
