﻿
(function ($) {
    $.fn.resize = function (options) {

        var settings = $.extend({
            scale: 1,
            maxWidth: null,
            maxHeight: null,
            minWidth: null,
            minHeight: null
        }, options);

        return this.each(function () {

            if (this ==null || this.tagName == null)
                return;

            if (this.tagName.toLowerCase() != "img") {
                // Only images can be resized
                return $(this);
            }

            var width = this.naturalWidth;
            var height = this.naturalHeight;
            if (!width || !height) {
                // Ooops you are an IE user, let's fix it.
                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;

            var fixX = 0;
            var fixY = 0;
            if (settings.minWidth != null) {
                if (newWidth < settings.minWidth) {
                    var t_w = newWidth / settings.minWidth;
                    newWidth = settings.minWidth;
                    newHeight = newHeight / t_w;
                    fixY = (1 - t_w) * newHeight;
                }
            }
            if (settings.minHeight != null) {

                if (newHeight < settings.minHeight) {
                    var t_h = newHeight / settings.minHeight;
                    newHeight = settings.minHeight;
                    newWidth = newHeight / t_h;
                    fixX = (1 - t_h) * newWidth;
                }
            }

            return $(this)
				.attr("width", newWidth)
				.attr("height", newHeight)
                .attr("style", "margin-left:-" + (fixX / 2) + "px;" + "margin-top:-" + (fixY / 2) + "px");
        });




    }
})(jQuery);

