// Initialise JQuery carousel
$(window).load(function () {

});
$(document).ready(function () {
	// Initialise gallery if there are more than 4 items.
	initGallery();
});	
function initGallery() {
	
	// Check if there are less than 4 items, add margin-left if so.
	if($(".thumbs").length < 4) {
		$(".thumbs ul").css('margin-left','5px');
	}
	
	// Check if there are less than 5 items, don't add the scroller in
	if($(".thumbs").length > 4) {
		// Add scroll buttons
		$('.scroller').prepend('<a href="#" class="scroll_left" title="Scroll left">Scroll Left</a>');	
		$('.thumbs').after('<a href="#" class="scroll_right" title="Scroll right">Scroll Right</a>');
	}
	
	// Replace the click events for the thumbs with the image loader behaviour
	replaceThumbOnClick();
	
	// Enable carousel
  // $(".thumbs").jCarouselLite({
  //  btnNext: ".scroll_right",
  //  btnPrev: ".scroll_left",
  //  visible: 4,
  //  circular: false
  // });
	
	// Setup gallery div CSS
	//$(".thumbs").css('width','440px');	
	//$(".thumbs").css('margin-bottom','5px');		
	//$(".thumbs ul").css('margin-left','0');

	// Preload preloader image
	imgLoader = new Image();
	imgLoader.src = tb_pathToImage;	
}
function replaceThumbOnClick() {
	// Replace on click events 
	$('a.show_image').click(function(){
		loadImage(this);
		this.blur();
		return false;
	});	
}
var tb_pathToImage = "/website/images/loading_animation.gif";
var firstImage = true;
var firstRun = true;
function loadImage(obj) {
	
	// Get src for new image
	src = $(obj).attr('href');
	
	// If first image then append overlay div
  // if(firstRun) {
  //  $('#gallery .inner').append('<div id="overlay_bg"></div>'); 
  //  firstRun = false;
  // }

	// Preload image
	imgPreloader = new Image();
	imgPreloader.onload = function() {
		// If first image then apply background image
    // if(firstImage) {
    //  $('#overlay_bg').css('backgroundImage','url('+src+')');
    //  //$('img.main_feature').attr('src',src);  
    //  $('#overlay_bg').fadeIn('slow');  
    //  firstImage = false;
    // }
    // else {
			// Load new image
			$('img.main_feature').attr('src',src);	
			$('#overlay_bg').fadeOut('slow');
			firstImage = true;			
		//}
	}
	imgPreloader.src = src;	
	
}
