var	image = {},
	viewport ={},
	t = setInterval(switchImage, 6000);
	

$(function(){
	$(".imageContainer").css('height', $(window).height() - 180);
	
	$(window).bind('resize', function() {
		$(".imageContainer").css('height', $(window).height() - 180);
		// Get image sizes
		image.width = $(".imageContainer img").width();
		image.height = $(".imageContainer img").height();
		image.aspectRatio = image.height / image.width;
		   			   
		//get gallery viewport dimensions
		viewport.width = $('.imageContainer').width();
		viewport.height = $('.imageContainer').height();
		
		var tempHeight;
		   //process image
		   if(image.width > viewport.width){
		   		tempHeight = viewport.width * image.aspectRatio;	
		   		if (tempHeight > viewport.height){
		   			tempHeight = viewport.height;
		   		}
		   } else {
		   	tempHeight = viewport.height;
		   }		   
		   $(".imageContainer img").attr('height', tempHeight);
		   positionLeft = Math.round(($(".imageContainer").width() - $(".imageContainer img").width())/2);
		   console.log(positionLeft);
		   $(".imageContainer img").css ('left', positionLeft);
	});
	
	switchImage();
	
	//setInterval(switchImage, 5000);
});

function switchImage() {
	$(".imageContainer img").fadeOut(1500, function(){
		$(this).remove();
	});
	var totalImages = galleryarray.length,
	    randomIndex = Math.floor(Math.random()*totalImages),
	    usedImages = new Array(),
	    currentImage = galleryarray.splice(randomIndex,1),
	    imgLoad = $("<img style='display: none;' />");
		imgLoad.attr("src","images/gallery/" + currentImage);
		imgLoad.unbind("load");
		
		imgLoad.bind("load", function () {	
		   // Get image sizes
		   image.width = this.width;
		   image.height = this.height;
		   image.aspectRatio = image.height / image.width;
		   			   
		   //get gallery viewport dimensions
		   viewport.width = $('.imageContainer').width();
		   viewport.height = $('.imageContainer').height();
		   			   
		   var tempHeight;
		   //process image
		   if(image.width > viewport.width){
		   		tempHeight = viewport.width * image.aspectRatio;	
		   		if (tempHeight > viewport.height){
		   			tempHeight = viewport.height;
		   		}
		   } else {
		   	tempHeight = viewport.height;
		   }		   
		   $(this).attr('height', tempHeight);
		   
		   calculatedWidth = tempHeight / image.aspectRatio;
		   positionLeft = Math.round((viewport.width - calculatedWidth)/2);
		   $(this).css('left', positionLeft);
		   
		   $(".imageContainer").append(this);
		   $(".imageContainer img").fadeIn(1500);
		   
		});

		usedImages.push(currentImage);	    
		
}

