var active_image = '#portfoliosque_active_image';
var timer = 'controlled';

/**
* Swap full color + black & white thumbnails
*/
function swap(obj) {
	if (obj.src.indexOf('_thumb_bw') !== -1) {
		obj.src = obj.src.replace('_thumb_bw', '_thumb');
	} else {
		obj.src = obj.src.replace('_thumb', '_thumb_bw');
	}
}

/**
* Return the image name without URL
*/
function return_full_image(misc_image) {
	var image_split = misc_image.split('/');

	var last = image_split.length;

	misc_image = image_split[last - 1];
	misc_image = misc_image.replace('_thumb_bw', '');
	misc_image = misc_image.replace('_thumb', '');

	return misc_image;
}

/**
* Setup thumbs
*/
$(document).ready(function () {
	/**
	* Fade out thumbnails
	*/
	$('img.portfolioesque-images').fadeTo(fade_speed, 0.5);

	/**
	* When they hover over an image...
	*/
	$('img.portfolioesque-images').css('cursor', 'pointer').hover(function () {
		/**
		* Stop current timer
		*/
		rotation(false);

		/**
		* Fade in to full opacity
		*/
		$(this).fadeTo(fade_speed, 1.0);

		var next_image = full_url + return_full_image(this.src);

		$(active_image).fadeOut(fade_speed, function() {
			$(active_image).load(function() {
				$(this).fadeIn(fade_speed);
			}).attr('src', next_image);
		});

	}, function(){
		$(this).fadeTo(fade_speed, 0.5, function() {
			rotation(true);
		});
	});

	// start initial rotation into the loop
	rotation(true); 
});

// rotation through the images into the main image
// start: true ? starts timer : stop timer? 
function rotation (start) {
	if (start == true) {
		$(document).everyTime(rotate_every, timer, function() {
			var active_image_src = $(active_image).attr('src');
			var images = $('.portfolioesque-images');

			/**
			* Go through the images
			*/
			for (var i = 0; i < images.length; i++) {
				/**
				* Get the current source (handle)
				* Get the full image from the current src
				*/
				var current_src = images[i].src;
				var full_image 	= return_full_image(current_src);

				/**
				* See if the current active image is the same as the image we're iterating on
				*
				* Yes: Go up another index++
				* No: Start at 0 on images
				*/
				if (return_full_image(active_image_src) == full_image) {
					if (i + 1 < images.length) {
						var new_active_full_image = images[i + 1].src;
					} else {
						var new_active_full_image = images[0].src;
					}

					$(active_image).fadeOut(fade_speed, function() {
						$(active_image).load(function() {
							$(this).fadeIn(fade_speed);
						}).attr('src', full_url + return_full_image(new_active_full_image));
					});

					break;
				}
			}
		}, '', true);
	} else {
		$(document).stopTime(timer);
	}
} 

/**
* Preload images
* (c) http://www.mattfarina.com/2007/02/01/preloading_images_with_jquery
*/
$.preload_images = function() {
	for(var i = 0; i<arguments.length; i++) {
		$("<img>").attr("src", arguments[i]);
	}
}
