$(function(){
	$('#overlay, #overlayContent, .dynamicContent').hide();
	$.ajaxSetup({cache: false});
	$('div.close a').click(function(){
		$('#overlay').hide();
	});
					
	//Get image with ajax
	$('a.imageLink').live('click',getImage);
	$('img.imageLink').bind('click',getImage);
		
});
function getImage(){
	$('#overlay').show();
	$('#overlay div.dynamicContent').fadeOut();
	$('#overlay div.dynamicContent').html('<div id="imageContainer"><img src="images/ajax-loader.gif" /></div>')
	
	$.get('response.php',{'image': true , 'id' : $(this).attr('data') },function(response){	
		var windowWidth = $(window).width();
		var windowHeight = $(window).height();
						
		$('#overlay .dynamicContent').html(response);							
		$('#overlay .dynamicContent').fadeIn(function(){				
			if($('#overlay .dynamicContent img').height() + 100 > windowHeight){
				var aspect = $('#overlay .dynamicContent img').width() / $('#overlay .dynamicContent img').height();
				var newHeight = (windowHeight - 115);
				var newWidth = newHeight * aspect;
				var oldOffsetX = (windowWidth - $('#overlay .dynamicContent img').width()) /2 ;
				var diff = ($('#overlay .dynamicContent img').height() - newHeight) /2;
						
				$('#overlay .dynamicContent img').css({'height': newHeight});
				$('#overlay .dynamicContent div#imageContainer img').css({'width': newWidth});
				$('#overlay .dynamicContent div#imageContainer').css({'width': newWidth+10});
				var imageHeight = newHeight;
				var imageWidth = newWidth;
			} else {
				var imageWidth = $('#overlay .dynamicContent img').width();
				var imageHeight = $('#overlay .dynamicContent img').height();
			}
			$('#overlay .dynamicContent img, #overlay .dynamicContent #imageTitle').fadeIn('fast');
							
			var offsetClose = imageWidth - 20;
			var offsetX = (windowWidth - imageWidth) /2 ;
			var offsetY = imageHeight;
								
			//$('div.previousImage').css({'left': function(){return offsetX}, 'top' : function(){return offsetY}});
			//$('div.nextImage').css({'right': function(){return offsetX}, 'top' : function(){return offsetY}});
			//$('div.close a').css('margin-left',function(){return offsetClose}).bind('click',function(){
			$('div.close a, div#overlay').bind('click',function(){
				$('#overlay, .dynamicContent').hide();
			}).fadeIn('fast',function(){
				$('div.previousImage a, div.nextImage a').bind('click',getImage).fadeIn('fast');
			});				
		});
	});
}
