// JavaScript Document

$(document).ready(function() {
	// fade in default image
	$('#main_image img').css('display','none').fadeIn('normal');
	
	// fade out inactive thumbnails
	$('ul.gallery li.active').siblings().css({display:'none',opacity:'0.6'}).fadeIn(500);
	
	// thumbnails hover effects
	$('ul.gallery li').hover(function() {
			$(this).not('.active').fadeTo('fast',1);
			$(this).not('.active').css('position', 'relative').css('left', 0).css('top', 0); // Fixes Safari 2 rendering issue
		}, function() {
			$(this).not('.active').fadeTo('fast',0.6);
		}
	);
	
	// thumbnails click function
	$('ul.gallery li').click(function() {
												 
		// set class for clicked thumbnail to active
		$(this).addClass('active');
		
		// fade out and remove active classes on all other thumbnails								 
		$(this).siblings().removeClass('active').fadeTo('fast',0.6);
		
		// get image source reference from the thumbnail link and store in a variable
		var img = $(this).children('a').attr('href');
		// get image caption from the title attribute of the image tag
		var caption = $(this).children('a').children('img').attr('title');
		
		// fade out and hide the previous image
	$('#main_image img').fadeTo("slow", 0);	
		// and the caption
		$('#main_image .caption').fadeOut().hide();
		
		preload = new Image(); 

		preload.src = img;
		
//alert(preload.src);

function display () {
		$('#main_image img').attr('src',img);
		$('#main_image img').fadeTo("slow", 1);	
}

function IsImageOk(imagine) {

if (!imagine.complete) { return false; }

if (typeof imagine.naturalWidth != "undefined" && imagine.naturalWidth == 0) { return false; }

return true;
};

var i=0;
function retry () {
if (!IsImageOk(preload)) {
//	alert("bad");
		if (i < 10) {
		t=setTimeout(retry,500);
		i++;
//		alert (i);
		}
	}	
	else { 
//	alert ("good");
		if (i != 0) { display(); }
		else { q=setTimeout(display,700); }
		

	}

};

retry();

		
		// set the new image source file and fade in the new image



		// set the caption text
		$('#main_image .caption').text(caption).fadeIn();
		
	});
	
});

// preload images
//$(window).load(function () {
//	for(var i = 1; i<16; i++) {
//		$("<img>").attr("src", '/images/lone-madsen/photos/lone-madsen-' + i + '.jpg');
//	}
//});
