(function ($) {
	$.fn.imageScale = function (options) {

		var settings = $.extend({
			scale: 1,
			maxWidth: null,
			maxHeight: null
		}, options);

		/*
		if ($("#imageScaleTooltipDiv").length == 0) { // Inject tooltip div if does not exist in DOM.
			jQuery(document.body).append('<div id="imageScaleTooltipDiv">This image has been scaled to fit. <br />' +
										 '<a href="" target="_blank">Click here to see the original image.</a></div>');
		}

		var tooltipDiv = $("#imageScaleTooltipDiv");
		var linkTag = $(tooltipDiv).children('a:first');

		// Style for tooltip div
		tooltipDiv.css({ 'position': 'absolute', 'display': 'none', 'background': 'white',
						'border': 'solid black 1px', 'padding': '5px', 'vertical-align': 'middle', });

		*/

		return this.each(function () {

			if (this.tagName.toLowerCase() != "img") {
				// Only images can be resized
				return $(this);
			}

			var width = this.naturalWidth;
			var height = this.naturalHeight;
			if (!width || !height) {
				// IE fix
				var img = document.createElement('img');
				img.src = this.src;

				width = img.width;
				height = img.height;
			}

			if (settings.scale != 1) {
				width = width * settings.scale;
				height = height * settings.scale;
			}

			var pWidth = 1;
			if (settings.maxWidth != null) {
				pWidth = width / settings.maxWidth;
			}
			var pHeight = 1;
			if (settings.maxHeight != null) {
				pHeight = height / settings.maxHeight;
			}
			var reduce = 1;

			if (pWidth < pHeight) {
				reduce = pHeight;
			} else {
				reduce = pWidth;
			}

			if (reduce < 1) {
				reduce = 1;
			}

			var newWidth = width / reduce;
			var newHeight = height / reduce;

			return $(this)
				.attr("width", newWidth)
				.attr("height", newHeight);
		});
	}
})(jQuery);

