/**
 * jQuery.fullBg
 * Version 1.0
 * Copyright (c) 2010 c.bavota - http://bavotasan.com
 * Dual licensed under MIT and GPL.
 * Date: 02/23/2010
**/
(function ($) {
    $.fn.fullBg = function () {
    	var bgImgSel = [];
    	$(this).each(function(){
    		if (!$(this).attr('id')) {
    			$(this).attr('id', 'random_id_'+String(Math.random()).substr(2));
    		}
    		bgImgSel.push('#'+$(this).attr('id'));
    	});
    	bgImgSel = bgImgSel.join(',');
        var bgImg = $(this);
        var topOffset = 73;
        bgImg.addClass('fullBg');
        var bgOldHeight = false;
        var bgOldWidth = false;

        function resizeImg(resize) {
        	$('body').css({width:'100%',overflow:'hidden'});
        	bgImg = $(bgImgSel);
            var imgwidth = bgImg.width();
            var imgheight = bgImg.height();
            //var winwidth = $(window).width();
            //var winheight = $(window).height()-topOffset;

            var winwidth = bgOldWidth;
            var winheight = bgOldHeight;
            if ((bgOldWidth == false) || (resize)) {
            	//winwidth = bgOldWidth = Math.min($(window).width(), $('#wrapper').width());
            	winwidth = bgOldWidth = $('#wrapper').width();
            }
            if ((bgOldHeight == false) || (resize)) {
            	//winheight = bgOldHeight = Math.min($(window).height(), $('#wrapper').height())-topOffset;
            	winheight = bgOldHeight = $('#wrapper').height()-topOffset;
            }
            
            var widthratio = winwidth / imgwidth;
            var heightratio = winheight / imgheight;
            var widthdiff = heightratio * imgwidth;
            var heightdiff = widthratio * imgheight;
            
            if (heightdiff > winheight) {
            	var centerX = (winwidth-widthdiff)/2;

                bgImg.css({
                    width: widthdiff + 'px',
                    height: winheight + 'px',
                    top: topOffset + 'px',
                    left: centerX + 'px'
                });
            } else {
            	var centerY = (winheight-heightdiff)/2+topOffset;
                bgImg.css({
                    width: winwidth + 'px',
                    height: heightdiff + 'px',
                    top: centerY + 'px',
                    left: 0
                });
            }
        	$('body').css({width:'auto',overflow:'visible'});
        }
        resizeImg();
        $.fn.fullBgUpdate = resizeImg;
        $(window).resize(function () {
            resizeImg(true);
            //setBGHeight();
        });
    };
})(jQuery);
