$(function() {
	/* this is the index of the last clicked picture */
	var current = -1;
	/* number of pictures */
	var totalpictures = $('.img_view').size();
	/* speed to animate the panel and the thumbs wrapper */
	var speed 	= 500;
	/*
	when the user resizes the browser window,
	the size of the picture being viewed is recalculated;
	 */
	$(window).bind('resize', function() {
		var $picture = $('#wrapper').find('img');
		resize($picture);
	});
	
	var playTimer;
	
	$.fn.playGallery = function(){
		
		var $nextimage = $('#gallery div:nth-child('+parseInt(current+2)+') img:first');
		navigate($nextimage,'right');
	};
	
	$.fn.clearPlayTimer = function(){
		$("#pause").hide();
		$("#play").show();
		window.clearInterval(playTimer);
	};
	
	$("#play").click(function(){
		$(this).hide();
		$("#loading").show();
		playTimer = window.setInterval("$('#play').playGallery()", 6000);
		$("#pause").show();
	});
	$("#pause").click(function(){
		$(this).hide();
		$("#loading").hide();
		$('#pause').clearPlayTimer();
		$("#play").show();
	});
	$("#info").click(function(){
		if($(this).hasClass("info_no")){
			$(this).removeClass("info_no");
			$(this).addClass("info");
			$('#description').fadeIn(speed);
		}	
		else{
			$(this).removeClass("info");
			$(this).addClass("info_no");
			$('#description').fadeOut(speed);
		}
		
	});
	$("#navbar").css("margin-left",($(window).width()/2)-($("#navbar").width()/2));
	/*
	when hovering a thumb, animate it's opacity
	for a cool effect;
	when clicking on it, we load the corresponding large image;
	the source of the large image is stored as
	the "alt" attribute of the thumb image
	 */
	$('.img_view').bind('click',function(){
		$("body").css({"overflow":"hidden"});
		
		var $this   = $(this).find("img:first");
		var $this_parent = $(this).parent();
		if($this_parent.attr("class")=="gallery_horizontal_view")
			$this_parent=$(this);
		
		/* shows the loading icon */
		$('#loading').show();
		
		$('<img alt="">').load(function(){
			$('#loading').hide();
			if($('#wrapper').find('img').length) return;
			current 	= $this_parent.index();
			var $theImage   = $(this);
			/*
			After it's loaded we hide the loading icon
			and resize the image, given the window size;
			then we append the image to the wrapper
			*/
			resize($theImage);

			$('#wrapper').append($theImage);
			/* make its opacity animate */
			$theImage.fadeIn(800);

			/* and finally slide up the panel */
			$('#panel').animate({'height':'100%'},speed,function(){
				/*
				if the picture has a description,
				it's stored in the title attribute of the thumb;
				show it if it's not empty
				 */
				if($this.attr('title') && $this.attr('title')!=undefined)
					var title = '<div id="description_title">'+$this.attr('title')+'</div>';
				else
					title="";
				if($this.attr('data-ref'))
					var content = $this.attr('data-ref');
				else
					content="";
				$('#description').html(title+'<div id="description_counter">'+(current+1)+'/'+totalpictures+'</div><div id="description_content">'+content+'</div>');
				if($("#info").hasClass("info")){
					$('#description').show();}

				/*
				if our picture is the first one,
				don't show the "previous button"
				for the slideshow navigation;
				if our picture is the last one,
				don't show the "next button"
				for the slideshow navigation
				 */
				$("#navbar").fadeIn();
				$('#prev').fadeIn();
				$('#next').fadeIn();
				$("#play").fadeIn();
				$("#info").fadeIn();
				//Show Gallery Info
				$("#gallery_info").css("margin-left",($(window).width()/2)-($("#gallery_info").width()/2));
				$("#gallery_info").fadeIn(1500);
	
			});
		}).attr('src', $this.attr('alt'));
	});

	/*
	when hovering a large image,
	we want to slide up the thumbs wrapper again,
	and reset the panel (like it was initially);
	this includes removing the large image element
	 */
	$('#wrapper > img,#description').live('click',function(){
		$this = $(this);
		$('#description').empty().hide();
		/* and finally slide up the panel */
			$('#panel').animate({'height':'0px'},speed);			
			$this.remove();
			$('#prev').hide();
			$('#next').hide();
			$("#play").hide();
			$("#pause").hide();
			$("#info").hide();
			$("#navbar").hide();
			$('#pause').clearPlayTimer();
			$("body").css({"overflow":"auto"});		
	});

	/*
	when we are viewing a large image,
	if we navigate to the right/left we need to know
	which image is the corresponding neighbour.
	we know the index of the current picture (current),
	so we can easily get to the neighbour:
	 */
	$('#next').bind('click',function(){
		var $this           = $(this);
		$('#pause').clearPlayTimer();
		if(current==parseInt(totalpictures-1))
			current=-1;
		var $nextimage 		= $('#gallery div:nth-child('+parseInt(current+2)+') img:first');
		navigate($nextimage,'right');
	});
	$('#prev').bind('click',function(){
		var $this           = $(this);
		$('#pause').clearPlayTimer();
		if(current==0)
			current=parseInt(totalpictures);
		var $previmage 		= $('#gallery div:nth-child('+parseInt(current)+') img:first');
		navigate($previmage,'left');
	});

	/*
	given the next or previous image to show,
	and the direction, it loads a new image in the panel.
	 */
	function navigate($nextimage,dir){
		/*
		if we are at the end/beginning
		then it loops to the beginning/end
		 */
		if(dir=='left' && current==0)
			current=parseInt(totalpictures);
		if(dir=='right' && current==parseInt(totalpictures-1))
			current=-1;
		$('#loading').show();
		$('<img alt="">').load(function(){
			var $theImage = $(this);
			if( $('#play').is(':visible') ) {
				$('#loading').hide();
			}
			$('#description').fadeOut();

			$('#wrapper img').stop().fadeOut(500,function(){
				var $this = $(this);

				$this.remove();
				resize($theImage);
				$('#wrapper').append($theImage.show());
				$theImage.stop().fadeIn(800);
				
				if($nextimage.attr('title') && $nextimage.attr('title')!=undefined)
					var title = '<div id="description_title">'+$nextimage.attr('title')+'</div>';
				else
					var title="";
				if($nextimage.attr('data-ref') && $nextimage.attr('data-ref')!=undefined)
					var content = $nextimage.attr('data-ref');
				else
					var content="";
				$('#description').html(title+'<div id="description_counter">'+(current+1)+'/'+totalpictures+'</div><div id="description_content">'+content+'</div>');
				if($("#info").hasClass("info")){
					$('#description').show();}
			});
			/*
			increase or decrease the current variable
			 */
			if(dir=='right')
				++current;
			else if(dir=='left')
				--current;
		}).attr('src', $nextimage.attr('alt'));
	}

	/*
	resizes an image given the window size,
	considering the margin values
	 */
	function resize($image){
		var windowH      = $(window).height();
		var windowW      = $(window).width();
		$("#navbar").css({"margin-left":Math.ceil((windowW/2)-$("#navbar").width()/2)});
		var theImage     = new Image();
		theImage.src     = $image.attr("src");
		var imgwidth     = theImage.width;
		var imgheight    = theImage.height;
		if((imgwidth > windowW)||(imgheight > windowH)){
			if(imgwidth > imgheight){
				var newwidth = windowW;
				var ratio = imgwidth / windowW;
				var newheight = imgheight / ratio;
				theImage.height = newheight;
				theImage.width= newwidth;
				
				$("#description").width(newwidth);
				$("#description").css({"margin-left":Math.ceil((windowW-newwidth)/2)});
				if(newheight>windowH){
					var newnewheight = windowH;
					var newratio = newheight/windowH;
					var newnewwidth =newwidth/newratio;
					theImage.width = newnewwidth;
					theImage.height= newnewheight;
					$("#description").width(newnewwidth);
					$("#description").css({"margin-left":Math.ceil((windowW-newnewwidth)/2)});
				}
			}
			else{
				var newheight = windowH;
				var ratio = imgheight / windowH;
				var newwidth = imgwidth / ratio;
				theImage.height = newheight;
				theImage.width= newwidth;
				$("#description").width(newwidth);
				$("#description").css({"margin-left":Math.ceil((windowW-newwidth)/2)});
				if(newwidth>windowW){
					var newnewwidth = windowW;
					var newratio = newwidth/windowW;
					var newnewheight =newheight/newratio;
					theImage.height = newnewheight;
					theImage.width= newnewwidth;
					$("#description").width(newnewwidth);
					$("#description").css({"margin-left":Math.ceil((windowW-newnewwidth)/2)});
				}
			}
		}
		$image.css({'width':theImage.width+'px','height':theImage.height+'px'});
		$("#description").width(theImage.width);
		$("#description").css({"margin-left":Math.ceil((windowW-theImage.width)/2)});
	}
});
