/*
 * This function will scale the supplied image (<img> element)
 * DOWN to fit into the specified size maintaining proportions.
 *
 * Compatibility: tested with IE6, Firfox 1.5, Opera 8.5
 * Author: Artem Lipatov "artem@lipatov.net"
 * 
 * USAGE:
 *      (Note) - To achieve better layout one needs to specify width and height of
 *              the <img> element (as well as the enclosing element) equal to size parameter
 *
 *      <img src="imageName.jpg" width="150" height="150" onload="scaleImage(this, 150);" />
 *
 */
function scaleImage(image, size)
{
    // construct an Image instance and load the same source into
    // it. This is needed to get the original image dimension as
    // the <img> element might have width and height specified
    
    var tmp = new Image();
    tmp.src = image.src;

    if (tmp.width > 0 && tmp.height > 0)
    {
        // if the image fits by itself
        // don't scale. 
        if ( tmp.width < size && tmp.height < size )
        {
            image.width = tmp.width;
            image.height = tmp.height;
        }
        // scale
        else
        {    
            var w = tmp.width;
            var h = tmp.height;
            
            // scale horizontally
            if (w > h)
            {
                w = size;
                h = size * tmp.height / tmp.width;
            }
            // scale vertically
            else
            {
                h = size;
                w = size * tmp.width / tmp.height;
            }
            
            image.width = w;
            image.height = h;
        }
    }

    image.style.visibility = 'visible';
}
