jQuery.fn.morphgallery = function() 
{
	return this.each(
	function()
	{
		var animationTime = 500;
		var parent = $(this);
		var currentImageNr = 0;
		var preloadImage = new Image();
		
		$('.next-image', parent).css('cursor', 'pointer');

		preloadImage.src = photos[currentImageNr];	
		
		setCounter();
		
		$(preloadImage).bind('load', function()
		{
			removeOpacity();

			$('.next-image', parent).css('background-image','url(' + photos[currentImageNr] + ')').width(preloadImage.width).height(preloadImage.height).css('opacity','0');
			
			$('.current-image', parent).animate({width:preloadImage.width, height:preloadImage.height}, animationTime,
			function(e) 
			{
				$('.current-image', parent).css('background-image','url(' + photos[currentImageNr] + ')');
				$('.next-image', parent).css('opacity','1');
			});
			
			$('.next-image', parent).animate({opacity:'1'}, animationTime);
			
			$('#navigation-loader').hide();
			
			setCounter();
		});
		
		function loadImage()
		{
			setOpacity();			
			
			$('#navigation-loader').show();
			
			if(currentImageNr == photos.length - 1)
			{
				$("#next-photo").hide();
			}
			else
			{
				$("#next-photo").show();
			}
			
			if(currentImageNr == 0)
			{
				$("#previous-photo").hide();
			}
			else
			{
				$("#previous-photo").show();
			}
			
			preloadImage.src = photos[currentImageNr];
		}
		
		function setOpacity()
		{
			$('.current-image', parent).css('filter', 'alpha(opacity=50)');	
			$('.current-image', parent).css('-moz-opacity', '.5');	
			$('.current-image', parent).css('opacity', '.5');	
		}
		
		function removeOpacity()
		{
			$('.current-image', parent).css('filter', 'none');	
			$('.current-image', parent).css('-moz-opacity', '1');	
			$('.current-image', parent).css('opacity', '1');	
		}
		
		function setCounter()
		{
			var totalPhotosNumber = $(photos).size();
			var currentImageNumber = currentImageNr + 1;
			
			$('#photos-counter').text(currentImageNumber + '/' + totalPhotosNumber);
		}
		
		$("#previous-photo").click(function(e)
		{
			currentImageNr <= 0 ? 0 : currentImageNr--;
			
			if(currentImageNr > 0)
			{
				loadImage();
			}
			
			return false;
		});
		
		$("#next-photo").click(function(e)
		{
			currentImageNr >= photos.length - 1 ? photos.length - 1 : currentImageNr++;
			loadImage();
			
			return false;
		});	
		
		$($('.next-image', parent)).click(function(e)
		{
			currentImageNr >= photos.length - 1 ? photos.length - 1 : currentImageNr++;
			loadImage();
			
			return false;
		});	
	});
};


