
jQuery.fn.imageRatio = function(maxWidth, maxHeight){

	jQuery(this).load(function(){
		var currentImage = this;
		var src = this.src;
		var img = new Image();

		jQuery(this).attr("maxWidth", maxWidth);
		jQuery(this).attr("maxHeight", maxHeight);
		
		if(maxWidth == undefined || maxHeight == undefined){
			jQuery(this).attr("maxWidth", 0);
			jQuery(this).attr("maxHeight", 0);
		}

		jQuery(img).hide().load(function(){
			var w = this.width;
			var h = this.height;
			var r = w/h;

			var maxWidth = jQuery(currentImage).attr("maxWidth");
			var maxHeight = jQuery(currentImage).attr("maxHeight");
			
			if(maxWidth == 0 || maxHeight == 0){
				maxWidth = w;
				maxHeight = h;
			}

			function setWidth(){
				if(w >= maxWidth){
					w = maxWidth;
					h = w / r;
				}
			}
			function setHeight(){
				if(h >= maxHeight){
					h = maxHeight;
					w = h * r;
				}
			}
			if(w > h){
				setWidth();
				setHeight();
			}
			else{
				setHeight();
				setWidth();
			}

			currentImage.width = w;
			currentImage.height = h;
			currentImage.style.width = w;
			currentImage.style.height = h;
			//alert(currentImage.width + "x" + currentImage.height);
			jQuery(currentImage).fadeIn(500);
		});
		img.src = src;
	}).trigger("load");
}

