// jQuery.imgAutoSize.js
// Tang Bin - http://planeArt.cn/ - MIT Licensed
(function ($) {
	var loadImg = function (url, fn) {
		var img = new Image();
		img.src = url;
		if (img.complete) {
			fn.call(img);
		} else {
			img.onload = function () {
				fn.call(img);
				img.onload = null;
			};
		};
	};
	
	$.fn.imgAutoSize = function (padding) {
		return this.find('img').each(function (i, img) {
			var maxWidth = $(this).parents('.img_center').innerWidth() - (padding || 0);
			var maxHeight = $(this).parents('.img_center').innerHeight() - (padding || 0);
			loadImg(this.src, function () {
				if (this.width > this.height) {
					if (this.width > maxWidth) {
						var height = maxWidth / this.width * this.height,
						width = maxWidth;
						img.width = width;
						img.height = height;
					};
				}
				else {
					if (this.height > maxHeight) {
						var width = maxHeight / this.height * this.width,
						height = maxHeight;
						img.width = width;
						img.height = height;
					};
				}
			});
		});
	};
	
})(jQuery);
$(".img_center").imgAutoSize(4);