function getThumbnailSize(width, height, maxWidth, maxHeight) {
	var newSize = {
		'height': height,
		'width': width
	};

	if(maxWidth < newSize.width) {
		newSize.width = maxWidth;
		newSize.height = Math.ceil((maxWidth * height) / width);
	}
	
	if(maxHeight < newSize.height) {
		newSize.height = maxHeight;
		newSize.width = Math.ceil((maxHeight * width) / height);
	}

	return newSize;
}

function resizeImage(img, maxWidth, maxHeight) {
	if(maxHeight == null)
		maxHeight = img.height();
	if(maxWidth == null)
		maxWidth = img.width();

	img.css("height", "auto");
	img.css("width", "auto");

	var imageSize = getThumbnailSize(img.width(), img.height(), maxWidth, maxHeight);
	
	// On applique les nouvelles dimensions
	img.css("height", imageSize.height + "px");
	img.css("width", imageSize.width + "px");
}

// Resize en fonction des paramètres maxWidth et maxHeight. Si non spécifié, en fonction des paramètres width et height de l'image
function jResize(imgs, maxWidth, maxHeight) {
	$(imgs).each(function() {
		var image = new Image();
		image.src = $(this).attr('src');
		
		if(image.complete)
			resizeImage($(this), maxWidth, maxHeight);
		else {
			$(this).load(function() {
				resizeImage($(this), maxWidth, maxHeight);
			});
		}
	});
}

// Resize en fonction des paramètres width et height (valeur max)
$(document).ready(function() {
	jResize("img[rel^='jResize']");
});
