$(document).ready(function() {
    set_background();
    
    $(window).resize(function(e) {
        set_background();
    });
});

function set_background() {
    win = $(window);
    img = $('div#background img');
    bg  = $('div#background');
    
    if(win.height() /* (win.height() * 1.7778) */ < win.width()) {
        img.height(win.width() * 0.5625);
        
        if(img.height() < win.height()) {
            set_background_by_height(win, img, bg);
        }
        else {
            set_background_by_width(win, img, bg);
        }
    }
    else {
        img.width(win.height() * 1.7778);
        
        if(img.width() < win.width()) {
            set_background_by_width(win, img, bg);
        }
        else {
            set_background_by_height(win, img, bg);
        }
    }
}

function set_background_by_width(win, img, bg) {
    img.width(win.width());
    img.height(win.width() * 0.5625);
    
    bg.css('top', '-' + ((img.height() - win.height()) / 2) + 'px');
    bg.css('left', '0px');
    bg.css('height', (((img.height() - win.height()) / 2) + win.height()) + 'px');
    bg.css('width', win.width() + 'px');
}

function set_background_by_height(win, img, bg) {
    img.height(win.height());
    img.width(win.height() * 1.7778);
    
    bg.css('left', '-' + ((img.width() - win.width()) / 2) + 'px');
    bg.css('top', '0px');
    bg.css('width', (((img.width() - win.width()) / 2) + win.width()) + 'px');
    bg.css('height', win.height() + 'px');
}
