// JavaScript Document

var config = {
	autoplay : true,
	slidelength : 6000,
	fadelength : 1000,
	thumbnails_per_page : 7, //This refers to the number of thumbnails that fit into the thumbnail viewport (which is paginated)
	link_to_full_image : true,
	medium_img_suffix : "_thumb", // What is appended to the base filename to get the thumbnail version of the image
	medium_img_suffix : "_view", // What is appended to the base filename to get the medium version of the image
	full_img_suffix : "_full", // What is appended to the base filename to get the larger version of the image
	thumbnail_width : 59 //Width of a thumbnail including padding and margins (to do: actually work this out using code)
}

// Non Configurable
var params = {
	active_thumb : null, //jQuery object of the thumbnail that was last activated (i.e. clicked when clicking was available)
	thumbs : null, //jQuery object: collection all thumbnails
	available : true
}

$(function(){
	if($("#gal_thumbs a").length > 0){
		defineGallery();
	};
});

function defineGallery(){

	//Define Outline
	$("#gal_thumbs").append("<div class=\"outline\"></div>");
	outline = $("div.outline");
	
	$("#gal_thumbs").wrapInner("<div></div>");
	
	//Define slides
	params.thumbs = $("#gal_thumbs a");
	params.length = $(params.thumbs).length; 
	
	//Add the page selector buttons
	params.thumb_pages = Math.ceil(params.length/config.thumbnails_per_page);
	
	$("#gal_pages").html('<div></div>');
	for(i=0; i<params.thumb_pages; i++){
		$("#gal_pages>div").append('<a href="">Page'+i+'</a>');
	}
	$("#gal_pages>div").append('<div class="clearBoth" />');
	$("#gal_pages a").each(function(i){
		var i;
		$(this).bind("click", function(){
			$(params.thumbs).eq(i*(config.thumbnails_per_page)).trigger("click");
			return false;
		});
	});
	
	//Align the page buttons in the middle
	params.gal_strip_width = $("#gal_strip").width();
	$("#gal_pages").width(params.gal_strip_width);
	sampleAWidth = $("#gal_pages a").get(params.thumb_pages-1).offsetLeft;
	$("#gal_pages").css({position:"relative",left: ((params.gal_strip_width-sampleAWidth)/2) });
	
	$("#gal_thumbs>div").width($(params.thumbs).length * config.thumbnail_width);

	//Add parameters to each slide thumbnail
	$(params.thumbs).each(function(i,e){
		
		file_parts = this.href.split(".");
		file_extention = file_parts[file_parts.length - 1];
		file_name = this.href.substr(0,this.href.length-file_extention.length-1);
		var re = new RegExp(config.medium_img_suffix + '$');
		base_file_name = file_name.replace(re, "");
		full_file_name = base_file_name + config.full_img_suffix + "." + file_extention;
		

		//Insert slide placeholder for each thumbnail
		$("#gal_viewport").append("<a href=\""+full_file_name+"\" class=\"idx_"+i+"\"></a>");
		viewport_img = $("#gal_viewport a").eq(i);
		$(viewport_img).addClass("not_loaded");
		$(viewport_img).data("thumbnail_img", $(this)); //Add this slide's counterpart in the viewport, relative to this group
		$(this).data("viewport_img", viewport_img); //Add this slide's counterpart in the viewport, relative to this group
		$(this).data("index", i); //Add this slide's index, relative to this group
		$(viewport_img).click(function(){//Add a lightbox trigger to this slide's link in the viewport
			
			params.available = false;
			$.slimbox( 
				$(this).attr("href"),
				"",
				{
					onclose:
					function(){
						params.available = true;
					}
				}
			);
			
			return false;
		});
		//Add action to slide thumbs
		$(this).click(function(){
			if(params.available){
				if (typeof(params.interval) == "number") clearInterval(params.interval);//Clear any existing intervals
				params.interval = setInterval(function(){$("#gal_right").click();},config.slidelength);
				params.available = false; //Set clicker availability to false
				viewport = $(this).data("viewport_img"); //The corresponding viewport image to the thumb just clicked
				$("#gal_viewport a.out").removeClass("out");
				$("#gal_viewport a.in").removeClass("in").addClass("out");//Flip the currently in viewport image to out
				$(viewport).addClass("in");
				$("#gal_viewport a.in").css({opacity:0});
				$("#gal_viewport a.in").animate({opacity:1},config.fadelength);
				
				if( $(viewport).hasClass("not_loaded") ){
					loadImages_r(viewport);					
				}
				thumbnail_page = Math.floor($(this).data('index')/config.thumbnails_per_page);
				$("#gal_pages a").removeClass("active").eq(thumbnail_page).addClass("active");
				
				thumbnail_viewport_width = $("#gallery #gal_thumbs").width();
				animateTo = -((thumbnail_viewport_width+2)*thumbnail_page);
				$("#gal_thumbs>div").animate({left:animateTo},config.fadelength);
				
				//Check to see if the viewport image we want is loaded
				fast_move_to($("img",this), function(){ params.available = true; }); //Start the outline animation, use the callback to set availability when animation finished
				params.active_thumb = this; //Tell the application that the thumb that was just clicked is the active one
			}
			return false;//Prevent events from bubbling up and link being fired
		});
		
	});
	//Set actions for right button
	$("#gal_right").click(function(){
		thisThumb = $(params.active_thumb).data("index");
		nextThumb = (thisThumb+1) % params.length;
		$(params.thumbs).eq( nextThumb ).trigger("click");		
		return false;
	});
	//Set actions for left button
	$("#gal_left").click(function(){
		thisThumb = $(params.active_thumb).data("index");
		nextThumb = (thisThumb-1) % params.length;
		nextThumb = (nextThumb < 0)?params.length-1:nextThumb;
		$(params.thumbs).eq( nextThumb ).trigger("click");		
		return false;
	});
	
	
	//Trigger first action automatically
	$(params.thumbs).eq(0).trigger("click");
	
	
};

function fast_move_to(target, callback){
	parentObj = $(target).get(0).parentNode.parentNode;
	parent_offset = $(parentObj).offset();
	target_offset = $(target).offset();
	target_offset.left = target_offset.left - parent_offset.left;
	target_offset.top = target_offset.top - parent_offset.top;
	target_width = $(target).width();
	target_height = $(target).height();
	target_css = {width: target_width-1,height: target_height,left: target_offset.left+1,top: target_offset.top};	

	if(params.active_thumb != null){//If the outline is now active on the stage
		$(outline).animate(target_css, config.fadelength, "swing", function(){ 
			onFinish();
		});	
	} else {
		$(outline).css(target_css);
		onFinish();
	}
	
	function onFinish(){
		callback(target, outline);				
	}
}


//This function calls itself recursively until there are no more images to load
function loadImages_r(next_to_load){
	//Autoloader
	if(typeof(next_to_load) == "undefined"){//If we haven't been asked to load a specific image, just load the next one
		next_to_load = $("#gal_viewport a.not_loaded").eq(0);
	}
	
	//Try to load the image if it isn't already (i.e. class != loaded)
	//This if statement allows errored images to be tried again - this is by design
	//The autoloader will only try to load images that are "not_loaded"
	if( !($(next_to_load).hasClass("loaded") || $(next_to_load).hasClass("loading")) ){
		$(next_to_load).removeClass("not_loaded").removeClass("error").addClass("loading");
		
		var thumbnail_img = $(next_to_load).data("thumbnail_img");
		src = $(thumbnail_img).attr("href");
		$(next_to_load).append("<img src=\""+src+"\" >");
		$("img", next_to_load).bind("load", function(){
			e = $(this).get(0).parentNode;							
			$(e).removeClass("loading");
			$(e).addClass("loaded");
			//$(e).append(i);
			loadImages_r();			
		});
		$("img", next_to_load).bind("error", function(){
			$(this).hide();
			e = $(this).get(0).parentNode;			
			$(e).removeClass("loading");
			$(e).addClass("error");
			loadImages_r();
		});
	}
	
}

