function MM_preloadImages() {}

$(document).ready(function(){

	thumbImages = $('#product_detail_image img, #product_detail_images img');
	totalThumbs = thumbImages.length - 1;	
	currentKey = 1;	// Array key of jQuery selector object	
	
	var loadCounter = 0;
	
	if(thumbImages.length > 1) {
	
		thumbImages.each(function(i) {
			
			// Add all fullsize images to body
			var newSrc = $(this).attr('src').replace('/thumb/','/main/');
			$(this).attr('rel','image_'+i);
			$('body').append('<img src="' + newSrc + '" class="preload_image" style="display:none;"/>');
			
		});
			
		$('.preload_image').load(function(){
			(totalThumbs == loadCounter) ? findTallestImage() :	loadCounter++;
		});	
		
		$('.additional_image').click(function(){
			if(!$(this).hasClass('active')) {
				switchImage($(this),true, 250);
			}
		});	
		
		setFadeTimer();
	
	}
	
});

function setFadeTimer() {

	functionWithArgs = function() { switchImage(thumbImages.eq(currentKey)); };
	fadeTimer = setInterval (functionWithArgs, 4200);
	
}

function findTallestImage() {

	var heightArray = new Array();

	// Loop through, recording outerHeight to an array
	$('.preload_image').each(function(i) {						   
		heightArray[i] = $(this).outerHeight();                  	// Height with border + padding
	});
	
	heightArray.sort(function(a,b){return b - a});          	 	// Sort array numerically and descending
	
	// Only set height if the new max height is going to be bigger than it already is
	var currentDivHeight = $('#product_detail_info').height();	
	if(currentDivHeight <= heightArray[0]) {
		$('#product_detail_info').height(heightArray[0]);
	}

}

function switchImage(thumbImage,forceSwitch,fadeSpeed) {
	
	if(!fadeSpeed) {
		fadeSpeed = 2000;
	}
	
	if(forceSwitch) {
		$('#temp_image').stop(true,false).fadeOut('fast');
		$('#product_image_mask').stop(true,false).fadeOut('fast');
		currentKey = thumbImage.attr('rel').replace('image_','');
		clearTimeout(fadeTimer);
		setFadeTimer();
	}
	
	$('.additional_image').removeClass('active');
	thumbImage.addClass('active');
	
	currentKey = (currentKey < totalThumbs) ? parseInt(currentKey) + 1 : 0;	
		
	var fullSizeSource = thumbImage.attr('src').replace('/thumb/','/main/');
	
	// Remove any Temp Images
	$('#temp_image').remove();
	
	// Add New Temp Image
	$('#product_detail_image').prepend('<img src="'+fullSizeSource+'" id="temp_image"/>');
	
	// Add load function to temp image
	$('#temp_image').load(function(){
		
		// Fade in mask
		$('#product_image_mask').hide().fadeIn(fadeSpeed);
		
		// Fade in temp image
		$(this).hide().fadeIn(fadeSpeed,function(){		
			$('#primary_image').remove();
			$('#product_image_mask').hide();
			$(this).attr('id','primary_image');
		});
	
	});

}