var backgroundToShow;


(function(c){var h=[];c.loadImages=function(a,d){a instanceof Array||(a=[a]);for(var e=a.length,f=0,g=e;g--;){var b=document.createElement("img");b.onload=function(){f++;f>=e&&c.isFunction(d)&&d()};b.src=a[g];h.push(b)}}})(jQuery);

function getPath(url) {
  var path = url.match(/.*\.funfactory\.\w+(.*)/);
  return path ? path[1] : url;
}

function showBackground(url) {
  if ((typeof url) == "undefined" || (!url && url !== '')) {
    url = backgroundToShow;
  }

  jQuery('div#hd-container:first')
    .find('img').attr('src', url).end()
    .fullBG({width: 1960, height: 1260});
}
    
function getBackground() {  
  return jQuery('div#hd-container img:first').attr('src');
}

function setBackground(backgrounds, noOverwrite) {    
  if (backgrounds === null) {
    showBackground('');
    return;
  }

  var lowRes  = backgrounds[0];
  var highRes = backgrounds[1];    
  
  var currentBackground = getBackground();
  
  var customBackground = !!!currentBackground.match(/white.png/);

  if(customBackground && noOverwrite) return;

  var currentPath = getPath(currentBackground);
  // Do nothing if background is already shown
  if(getPath(highRes) == currentPath || getPath(lowRes) == currentPath) {    
    return;
  }  
  jQuery.loadImages(lowRes, function() {    
    showBackground(lowRes);
    backgroundToShow = highRes;
    jQuery.loadImages(highRes, function() {
      showBackground();
    });
  });  
}

/////////////////////////////////////////////////////////////////////////////

(function($) {
	$.fn.fullBG = function(settings) {
	var config = {
		'width':  0,
		'height': 0
	};
	if (settings) {    
	  $.extend(config, settings);
	  config.width = parseInt(config.width, 10); 
  	config.height = parseInt(config.height, 10);
	}
	
	var bgImage=this.find('img');
	var bgContainer=this;
	
	if(bgImage.length===0){
	  //could be intercepted if there is something to do when 
	}
	
	//integrity check
	if(!config.width || !config.height){
		config.width=bgImage.width();
		config.height=bgImage.height();
	}
	
	//initial css settings
  bgImage.css({
    'minWidth':'0px'
  });
	bgContainer.css({
		'height':'auto',
		'width':'auto'
	});
	var resize= function(){
    var win = $(window);
       
    bgContainer.css({
     'width': win.width()+'px',
     'height': win.height()+'px'
    });
		
		var nuWidth = win.width();
    var factor = nuWidth/config.width;
		
		var nuHeight = Math.floor(config.height*factor);
		
    if(nuHeight < win.height()){
      nuHeight = win.height();
      factor = nuHeight/config.height;
      nuWidth = Math.floor(config.width*factor);
    }
    bgImage.css({
     'width':nuWidth+'px',
     'height':nuHeight+'px'
    });
		
	};
	
  resize();
  $(window).bind('resize', resize);
	
	return this;
   };
 })(jQuery);

