﻿$(window).load(function() {

    if ($.browser.msie && parseInt($.browser.version, 10) <= 8) {

        var bgImgUrl = extractCssUrl($('body').css('background-image'));
        $('body').removeClass('bg-scale').append('<img src="' + bgImgUrl + '" id="iebg" />');

        var theWindow = $(window),
            $bg = $("#iebg"),
            aspectRatio = $bg.width() / $bg.height();

        function resizeBg() {

            if ((theWindow.width() / theWindow.height()) < aspectRatio) {
                $bg.css({ 'height': '100%', 'width': 'auto', 'margin-left': -$bg.width() / 2, 'left': '50%', 'margin-top': 0, top: '0px' });
            } else {
                $bg.css({ 'width': '100%', 'height': 'auto', 'margin-top': -$bg.height() / 2, 'top': '50%', 'margin-left': 0, left: '0px' });
            }

        }

        theWindow.resize(function() {
            resizeBg();
        }).trigger("resize");
        
        resizeBg();
    }

    function extractCssUrl(input) {
        // remove quotes and wrapping url()
        return input.replace(/"/g, "").replace(/url\(|\)$/ig, "");
    }

});
