jQuery(document).ready(function(){


    initBackground();

});

function initBackground()
{
    var background = jQuery('<div />');

    var useFixed = isPositionFixedSupported();
	background.attr('id', 'backgroundLayer');
    background.css({
        position: (useFixed) ? 'fixed' : 'absolute',
        top: '0px',
        left: '0px',
        minWidth: '960px',
        width: '100%',
        height: '100%',
        zIndex: '1'
    });

    var image = jQuery('<img src="images/background.jpg" alt="" />');
    image.css({
        width: '100%',
        height: '100%'
    });

    background.append(image);

    if (!useFixed)
    {
        jQuery(document).ready(function(){ fixBackground(); });
        jQuery(window).bind('scroll resize load', function(){ fixBackground(); } );
    }


    jQuery(document.body).append(background);

    window.sheepBackground = background;


    // setup content background if needed
    if ( jQuery('.mainContainer').css('background-image') == 'none' )
    {
        var contentBackground = jQuery('<div />');

        contentBackground.addClass('contentBackground');
        contentBackground.css({
            position: 'absolute',
            top: '0px',
            left: '0px',
            width: '990px',
            height: '100%',
            opacity: '0.77',
            zIndex: '-1'
        });

        jQuery('.mainContainer').prepend( contentBackground );

    }


}

function fixBackground()
{
    if (typeof window.sheepBackground == 'undefined')
    {
        return;
    }

    var backgroundCss = {
        height: jQuery(window).height()   + 'px',
        width:  jQuery(window).width()    + 'px',
        top: jQuery(window).scrollTop()   + 'px',
        left: jQuery(window).scrollLeft() + 'px'
    };

    var imgCss = {
        height: jQuery(window).height()   + 'px',
        width:  jQuery(window).width()    + 'px'
    };


    window.sheepBackground.css(backgroundCss);
    window.sheepBackground.find('img').css(imgCss);


    jQuery('.contentBackground').css('height', jQuery('.mainContainer').height() + 'px');

}


function isPositionFixedSupported ()
{
  var isSupported = null;
  if (document.createElement) {
      var el = document.createElement("div");
      if (el && el.style) {
          el.style.position = "fixed";
          el.style.top = "10px";
          var root = document.body;
          if (root && root.appendChild && root.removeChild) {
              root.appendChild(el);
              isSupported = el.offsetTop === 10;
              root.removeChild(el);
          }
      }
  }
  return isSupported;
}
