var page = 1;
var item = 0;

if( jQuery.url.segment( jQuery.url.segment() - 2 ) == 'gpage' )
	page = jQuery.url.segment( jQuery.url.segment() - 1 );

$(document).ready(function(){
	
	$("#player").css( "opacity", 0.5 );
	
	if( page > 1 ) 
		item = (page * 6) - 6;
	
	$("#player, #popup-close")
		.click(function(){
			$("#player, #popup").fadeOut();
			return false;
		});
	
	$("#popup-prev, #popup-next")
		.click(function(){
			return false;
		});
	
	$("#image-list a")
		.click(function(){
			current = $("#image-list a").index( this ) + item;
			preload( current );
			return false;
		});
		
	$("#popup-prev")
		.click(function(){
			current = current - 1;
			if( current < 0 )
				current = gallery.length - 1;
			preload( current );
		});
	
	$("#popup-next")
		.click(function(){
			current = current + 1;
			if( current == gallery.length )
				current = 0;
			preload( current );
		});
	
});

function show( id ) {
	
	$("#popup-image").attr("src",gallery[current]["url"]).fadeIn();
	$("#player, #popup, #popup-image").fadeIn();
	
}

function preload( id ) {
	
	var posTop = '50%';
	var posLeft = '0';
	var olWidth = '100%';
	var olHeight = '100%';
	
	var preloader = new Image();
	$("#popup-image").hide();
	preloader.onload = function() {
		
		$("#popup-image").css("width",preloader.width);
		$("#popup-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( posTop < 10 )
			posTop = 10;
			
		$("#player").css("height",olHeight);
		$("#popup").animate({top:posTop,left:posLeft},200);
		
		show(current);
		
		preloader.onload = null;
		preloader = null;
		
	}
	
	preloader.src = gallery[current]["url"];
	
}
