(function($) {
	var ImageUtils = {
		// set max width and height constraints on an img (jQuery object)
		// to prevent it from being scaled past its real size
		constrainToOriginalSize: function(img) {
			var w, h;
			$("<img/>")
				.attr("src", img.attr("src"))
				.load(function() {
					w = this.width;
					h = this.height;
					img.css({
						"max-width": w,
						"max-height": h
					});
				});
		},
		
		// 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
		// optionally constrain them to not exceed their original sizes
		scaleGallery: function(context, constrainToOriginalSize) {
			var contextDimensions;

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

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

	$(document).ready(function() {
		var gallery, getGalleryDimensions, resizeTimeout;

		gallery = $("#gallery");
		getGalleryDimensions = function() {
			return {
				width: gallery.width(),
				height: gallery.height()
			}
		};
		
		ImageUtils.scaleGallery(gallery, true);

		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);
		});
	});
}(this.jQuery));
