﻿(function ($) {

    function resizeHugeImage(item, options) {

        var settings = { MaxWidth: 200, MaxHeight: 200 };

        $(item).each(function () {

            if (this.complete) //if already loaded

                proc.call(this);

            else //hook load event

                $(this).load(proc);

        });

        function proc() {

            $.extend(settings, options);

            var img = $(this);

            var nw = img.width(), nh = img.height();

            var HeightWidth = nh / nw;
            var WidthHeight = nw / nh;

            if (nw > settings.MaxWidth) {
                nw = settings.MaxWidth;
                nh = settings.MaxWidth * HeightWidth;
            }
            if (nh > settings.MaxHeight) {
                nw = settings.MaxHeight * WidthHeight;
                nh = settings.MaxHeight;
            }
            img.width(nw).height(nh);
        }
    }

    $.fn.extend({
        resizeImage: function (options) {
            return this.each(function () {
                resizeHugeImage(this, options);
            });
        }
    });
})(jQuery);
