﻿(function ($) {
    $.fn.toBackground = function (anchorHeight, minWidth, maxWidth) {
        var bgImage = $(this); //get the image

        var imgWidth = 0;
        var imgHeight = 0;
        var aspectRatio = 0;

        $(window).load(function () {
            imgWidth = bgImage.width();
            imgHeight = bgImage.height();

            if (imgWidth == 0) {
                imgWidth = minWidth;
            }

            aspectRatio = imgWidth / imgHeight;
            setBGImageDimensions(bgImage); //convert to background immage
        });

        //register window resize event
        $(window).bind("resize", function () {
            setBGImageDimensions(bgImage);
        });

        function setBGImageDimensions(bgImage) {
            var winwidth = $(window).width();

            var h = Math.round(2 * ((winwidth / aspectRatio) - anchorHeight)); //calculate heigt so that image is high enough to be centered at the anchor point
            var w = Math.round(h * aspectRatio); //calculate width from new height

            if (h <= 0) { //this could happen if the anchor height is bigger than the image height
                w = minWidth;
                h = Math.round(w / aspectRatio);
            } else {
                //heigth of the image must be at least twice the anchor height.
                if (h < (2 * anchorHeight)) {
                    h = 2 * anchorHeight;
                    w = Math.round(h * aspectRatio);
                };

                //make sure the image is not wider than the maximum width
                if (w > maxWidth) {
                    w = maxWidth;
                    h = Math.round(w / aspectRatio);
                };
            };

            //set the width and height of the image
            bgImage.attr({
                width: w,
                height: h
            });

            //put the image in the background and center it around the anchor
            bgImage.css({
                'position': 'absolute',
                'top': -(Math.round((h / 2)) - anchorHeight),
                'left': '50%',
                'margin-left': -(Math.round(w / 2)),
                'z-index': -1
            });

            //hide the overflow if width of the image is bigger than the minimum width
            if (w <= minWidth) {
                $('body').css({ 'overflow': 'visible' });
            }
            else {
                $('body').css({ 'overflow': 'hidden' });
            };
        };
    };
})(jQuery);

