﻿
var itemHeight = "";
var itemWidth = "";
var containerHeight = "";
var containerWidth = "";

function checkOrientation(theImage, check) {

    containerHeight = $(theImage).parents(check).css('height');
    containerWidth = $(theImage).parents(check).css('width');

    //remove 'px' from value
    containerHeight = containerHeight.substring(0, (containerHeight.length - 2));
    containerWidth = containerWidth.substring(0, (containerWidth.length - 2));

    itemHeight = $(theImage).height();
    itemWidth = $(theImage).width();

    if (itemWidth > itemHeight) {
        //alert('landscape');
        scaleImageAspect(theImage, 'height');
    } else {
        // alert('portrait');
        scaleImageAspect(theImage, 'width');
    }
}


function scaleImageAspect(theImage, dimensionToScale) {

    var targetWidth;
    var targetHeight;

    if (dimensionToScale == 'width') {
        // Height is > width to get here
        var scaling = containerWidth / itemWidth;

        targetWidth = itemWidth * scaling;
        targetHeight = itemHeight * scaling;

        if (targetHeight < containerHeight) {
            scaling = containerHeight / targetHeight;
            targetWidth = targetWidth * scaling;
            targetHeight = targetHeight * scaling;
        }

    } else if (dimensionToScale == 'height') {
        // width is > height to get here
        var scaling = containerHeight / itemHeight;

        targetWidth = itemWidth * scaling;
        targetHeight = itemHeight * scaling;

        if (targetWidth < containerWidth) {
            scaling = containerWidth / targetWidth;
            targetWidth = targetWidth * scaling;
            targetHeight = targetHeight * scaling;
        }
    }

    var topMargin = 0;
    var leftMargin = 0;
    var totalMargin = 0;


    if (targetHeight > containerHeight) {
        //need to centre vertically
        totalMargin = targetHeight - containerHeight;
        topMargin = totalMargin / 2;
        $(theImage).css({ 'margin-top': -topMargin });
    }

    if (targetWidth > containerWidth) {
        //need to centre horizontally
        totalMargin = targetWidth - containerWidth;
        leftMargin = totalMargin / 2;
        $(theImage).css({ 'margin-left': -leftMargin });
    }


    //don't resize on the fly as browser can resize other
    //dimension before script does, leading to errors
    //resize after all calculations complete

    theImage.width = targetWidth;
    theImage.height = targetHeight;

    $(theImage).css({ 'width': targetWidth });
    $(theImage).css({ 'height': targetHeight });


}

