﻿/// <reference path="jquery.js"/>
(function($) {
    $.fn.scaleImage = function(setting) {
        var ps = $.extend({}, $.fn.scaleImage.defaults, setting);
        return this.each(function() {
            var t = $(this);
            var src = $(this).attr("rel")
            var img = new Image();
            img.src = src;
            var autoScaling = function() {
                if (ps.scale) {
                    if (img.width > 0 && img.height > 0) {
                        if (img.width / img.height >= ps.width / ps.height) {
                            if (img.width > ps.width) {
                                t.width(ps.width);
                                t.height((img.height * ps.width) / img.width);
                            } else {
                                t.width(img.width);
                                t.height(img.height);
                            }
                        }
                        else {
                            if (img.height > ps.height) {
                                t.height(ps.height);
                                t.width((img.width * ps.height) / img.height);
                            } else {
                                t.width(img.width);
                                t.height(img.height);
                            }
                        }
                    }
                }
            }
            //$(this).attr("src", "");
            var loadpic = $(this).attr("alt")
            if (ps.valigncenter) var lineheight = t.parent().height();
            var loading = $("<span style='font-size:12px; line-height:" + lineheight + "px;'>" + loadpic + "</span>");
            t.hide();
            t.after(loading);
            $(img).load(function() {
                autoScaling();
                loading.remove();
                t.attr("src", this.src);
                if (ps.valigncenter) {
                    var martop = (t.parent().height() - t.height()) / 2 + "px";
                    t.css('margin-top', martop);
                }
                t.show();
            });

        });
    }
    $.fn.scaleImage.defaults =
    {
        scale: true,
        width: 200,
        height: 200,
        valigncenter: true
    }
})(jQuery);