﻿
function ib_fit2(img, master)
{
    //defer until images are loaded
    if ($.browser.version.substr(0, 1) == 7)
    {
        addOnloadHandler(function () { ib_fit2OL(img, master); });
    }
    else
    {
        ib_fit2OL(img, master);
    }
}

function addOnloadHandler(func)
{
    if (window.onload)
    {
        var windowOnload = window.onload;
        window.onload = function (evt)
        { windowOnload(evt); func(evt); } 
    }
    else
    {
        window.onload = function (evt) { func(evt); } 
    }
}

function ib_fit2OL(img, master)
{

    if (img.src == null || img.src.length == 0)
    {
        //alert('empty src image');
    }
    else
    {
        var masterDiv = document.getElementById(master);

        myImage = new Image()
        //myImage.src = "";
        myImage.src = img.src;

        var width = myImage.width;
        var height = myImage.height;
        var targetWidth = masterDiv.offsetWidth
        var targetHeight = masterDiv.offsetHeight


        if (width > 0 && height > 0 && targetHeight > 0 && targetWidth > 0)
        {
            var X = targetWidth / width;
            var Y = targetHeight / height;

            // how much to scale down by if anything
            var Scale = Math.min(X, Y);

            var finalHeight = parseInt(height * Scale);
            var finalWidth = parseInt(width * Scale);

            var deltaWidth = targetWidth - finalWidth;
            var deltaHeight = targetHeight - finalHeight;

            // within tolerance of 10px?
            if (deltaWidth <= 10)
            {
                deltaWidth = 0;
                finalWidth = targetWidth;
            }

            if (deltaHeight <= 10)
            {
                deltaHeight = 0;
                finalHeight = targetHeight;
            }

            img.style.width = finalWidth + 'px';
            img.style.height = finalHeight + 'px';
            img.style.left = '0px';
            img.style.top = '0px';

            if (deltaWidth > 0)
            {
                img.style.left = (deltaWidth / 2) + 'px';
            }

            if (deltaHeight > 0)
            {
                img.style.top = (deltaHeight / 2) + 'px';
            }
        }
    }
}


