var current = 0;
var gallery = new Array();
var page = 1;
var year = 0;

$(document).ready(function(){
	
	$("#overlay").css("opacity", 0.8);
	
	if( jQuery.url.segment(2) != null )
		page = jQuery.url.segment(2);
	
	if( jQuery.url.segment(1) != null )
		year = jQuery.url.segment(1);
	
	// external link
	$("a.ext-link")
		.click(function(){
			window.open( this.href );
			return false;
		});
	
	$("#overlay, #lightbox-close a")
		.click(function(){
			$("#overlay, #lightbox").fadeOut();
			return false;
		});
	
	$("#thumbs a")
		.each(function(i){
			
			// populate array
			gallery[i] = new Array();
			gallery[i]["thumb"] = jQuery("img",this).attr("src");
			gallery[i]["image"] = $(this).attr("href");
			gallery[i]["title"] = jQuery("img",this).attr("alt");
			gallery[i]["techn"] = $(this).attr("title");
			
			if( (i < (page*25)-25) || ( i+1>page*25 ) )
				$(this).hide();
			
		})
		.click(function(){
			// current
			current = $("#thumbs a").index(this);
			preload( current );
			return false;
		});
	
	$("#nav-left")
		.click(function(){
			current = current - 1;
			if( current < 0 )
				current = gallery.length - 1;
			preload( current );
		});
	
	$("#nav-right")
		.click(function(){
			current = current + 1;
			if( current == gallery.length )
				current = 0;
			preload( current );
		});
	
});

function show( id ) {
	
	$("#lightbox-load").hide();
	
	// information
	$("#lightbox-image").attr("src",gallery[current]["image"]).fadeIn();
	$("#lightbox-title").empty().append(gallery[current]["title"]);
	$("#lightbox-tech").empty().append(gallery[current]["techn"]);
	$("#lightbox-year").empty().append(year);
	
	$("#overlay, #lightbox").fadeIn();
	
}

function preload( id ) {
	
	var posTop = '50%';
	var posLeft = '0';
	var olWidth = '100%';
	var olHeight = '100%';
	
	var preloader = new Image();
	$("#lightbox-load").show();
	$("#lightbox-image").hide();
	preloader.onload = function() {
		
		$("#lightbox-container").animate({width:preloader.width,height:preloader.height},200);
		$("#lightbox-image").css("width",preloader.width);
		$("#lightbox-image").css("height",preloader.height);
		
		if( $("body").height() < preloader.height + 100 ) {
			olHeight = preloader.height + 110;
			posTop = '10';
		} else {
			posTop = ($("body").height()-preloader.height-110)/2;
		}
		
		if( $("body").width() < preloader.width + 140 ) {
			olWidth = preloader.width + 140;
			posLeft = '10';
		} else {
			posLeft = ($("body").width()-preloader.width-140)/2;
		}
		
		if( posTop < 10 )
			posTop = 10;
		
		$("#overlay").css("height",olHeight);
		$("#lightbox").animate({top:posTop,left:posLeft},200);
		
		show(current);
		
		preloader.onload = null;
		preloader = null;
		
	}
	preloader.src = gallery[current]["image"];
	
}

function paging() {
	
	alert( gallery.length );
	
}