
var ImageUtils = {
  // handle scaling of an img (jQuery object) based on its aspect ratio,
  // relative to the dimensions of its context (a container that holds the image)
	scaleImage: function(img, contextDimensions) {
		var ratioW, ratioH;

		ratioW = img.width() / contextDimensions.width;
		ratioH = img.height() / contextDimensions.height;
		
    // mark wide aspect ratio images with a css class "wide" 
		img[ratioW > ratioH ? "addClass" : "removeClass"]("wide");
	},
	// scale all the images within a context
	scaleGallery: function(context) {
		var contextDimensions;

		contextDimensions = {};
		contextDimensions.width = context.width();
		contextDimensions.height = context.height();

		context.find("img").each(function() {
			ImageUtils.scaleImage($(this), contextDimensions);
		});
	}
};

$(document).ready(function() {
	var gallery, getGalleryDimensions, resizeTimeout;
	
	gallery = $("#gallery");
	getGalleryDimensions = function() {
	  return {
	    width: gallery.width(),
			height: gallery.height()
	  }
	};
	
	ImageUtils.scaleGallery(gallery);
	
	gallery.cycle({
		fx:'fade',
		speed:'fast',
		timeout: 0, 
		next: '#gallery-nav .next', 
		prev: '#gallery-nav .prev',
		after: function(leavingItem, arrivingItem) {
		  var arriver = $(arrivingItem);
		  $(leavingItem).removeClass("cur");
		  arriver.addClass("cur");
			ImageUtils.scaleImage(arriver.find("img"), getGalleryDimensions());
		}
	});
	gallery.children().eq(0).addClass("cur");
	
	$(window).resize(function() {
		clearTimeout(resizeTimeout);
		resizeTimeout = setTimeout(function() {
			ImageUtils.scaleImage(gallery.find(".cur img"), getGalleryDimensions());
		}, 100);
	});
});
