(function ($) {
    $.fn.centeredBackground = function () {

        var backgroundImage = $(this);

        function resizeImage() {
            var imageWidth = backgroundImage.width();
            var imageHeight = backgroundImage.height();

            var browserWidth = $(window).width();
            var browserHeight = $(window).height();

            var ratioWidth = browserWidth / imageWidth;
            var ratioHeight = browserHeight / imageHeight;

            var diffWidth = ratioHeight * imageWidth;
            var diffHeight = ratioWidth * imageHeight;

            if (diffHeight > browserHeight) {
                backgroundImage.css({
                    width: browserWidth + 'px',
                    height: diffHeight + 'px'
                });
            } else {
                backgroundImage.css({
                    width: diffWidth + 'px',
                    height: browserHeight + 'px'
                });
            }

            // Center background image vertically.
            backgroundImage.css('top', (browserHeight - backgroundImage.height()) / 2);

            // Center background image horizontally.
            backgroundImage.css('left', (browserWidth - backgroundImage.width()) / 2);
        }

        resizeImage();

        $(window).resize(function () {
            resizeImage();
        });
    };
})(jQuery);
