﻿/**
* --------------------------------------------------------------------
* jQuery-Plugin "resizeImage"
* Version: 1.0, 20/07/2009
* by Daniel <xin.qin@tri-media.com>
*
* --------------------------------------------------------------------
* @example jQuery("#imagesId").resizeImageByScale({ "maxWidth": 410, "maxHeight": 248 });
* @desc resize all images size
*
* --------------------------------------------------------------------
*/
(function($) {
    $.fn.resizeImageByScale = function(options) {
        var defaults = { "maxWidth": 100, "maxHeight": 100 };

        $.extend(defaults, options);

        return this.each(function() {
            var obj = $(this);
            var t = new Image();
            $(t).load(function() {
                var t1 = this; //DOM element
                var toheight = defaults.maxHeight;
                var towidth = defaults.maxWidth;

                var aWidth = Math.round((t1.width / towidth) * 10000);
                var aHeight = Math.round((t1.height / toheight) * 10000);

                if (aWidth < aHeight) {
                    toheight = defaults.maxHeight;
                    towidth = Math.round(t1.width * defaults.maxHeight / t1.height);
                }
                else {
                    towidth = defaults.maxWidth;
                    toheight = Math.round(t1.height * defaults.maxWidth / t1.width);
                }

                obj.css({ "width": towidth, "height": toheight });
            }).attr("src", obj.attr("src"));
        });
    }
})(jQuery);