﻿jQuery.fn.ac_resizeimg = function(maxWidth, maxHeight) {
    var width = jQuery(this).width();
    var height = jQuery(this).height();

    // Check if the current width is larger than the max
    if (width > maxWidth) {
        var ratio = maxWidth / width;   // get ratio for scaling image
        jQuery(this).css("width", maxWidth); // Set new width
        jQuery(this).css("height", height * ratio);  // Scale height based on ratio
        height = height * ratio;    // Reset height to match scaled image
        width = maxWidth;    // Reset width to match scaled image
    }

    // Check if current height is larger than max
    if (height > maxHeight) {
        var ratio = maxHeight / height; // get ratio for scaling image
        jQuery(this).css("height", maxHeight);   // Set new height
        jQuery(this).css("width", width * ratio);    // Scale width based on ratio
        width = width * ratio;    // Reset width to match scaled image
    }
    return jQuery;
};

function ac_initresize(jFilter, maxWidth, maxHeight) {
    var imgs = jQuery.makeArray($(jFilter));

    // Check for incompletes first so we don't miss anything. If we did ready4Resize first, and there happened to be
    // some images that completed after we checked for ready4Resize, but before we checked for incompletes, we'd miss them.
    var incompletes = jQuery.grep(imgs, function(n, i) {
        return !n.complete;
    });

    // Now see if there are any that are fully loaded and need to be resized.
    var ready4Resize = jQuery.grep(imgs, function(n, i) {
        return n.complete && (n.width > maxWidth || n.height > maxHeight);
    });

    // I know I could do this without the for loop by just calling jQuery(ready4Resize) but the thumbnail images weren't
    // coming out right (on ProductImages.aspx, for example) and some were ending up with the dimensions of other thumbs that
    // were resized first. I suspect that the width and height vars of jQuery.fn.ac_resizeimg are being treated globally and
    // so simultaneous calls to function are causing the wrong dimensions to be used.  Since I don't know how to prevent that,
    // I decided to just use this for loop instead and resize them one at a time. - SB - 08/24/2009
    for (var i = 0; i < ready4Resize.length; i++) {
        jQuery(ready4Resize[i]).ac_resizeimg(maxWidth, maxHeight);
    }

    // Queue another check if there were any still pending.
    if (incompletes.length > 0) {
        setTimeout("ac_initresize('" + jFilter + "', " + maxWidth + ", " + maxHeight + ")", 100);
    }
}
