(function($){

	$.background = function(projects){
	
		$bg = $('<div id="stretch_background"/>');
		
		$bg.css({
			"z-index": -9999,
			position: "fixed",
			left: 0,
			top: 0,
			overflow: "hidden",
			display: "block"
		});
		$bg.prependTo("body");
		var $img = $('<img/>');
		$img.css({
			opacity: 0,
			position: "relative"
		}).appendTo($bg);
		var total_projects = projects.length;
		var preloader = [];
		var counter = 0;
		var que = [];
		var ratio;
		var loaded = false;
		var root = ("onorientationchange" in window) ? $(document) : $(window);
		$(window).bind('do_resize',function(){
			do_resize(true);
		});
		for(var i in projects)
		{
			preloader[counter] = $('<img/>').attr("rel",i).load(function(){
				var _index = $(this).attr("rel");
				que.push(_index);
				projects[_index]['ratio'] = this.width / this.height;
				if(que.length == 1){
					loaded = true;
					next_project();
				}
			});
			preloader[counter].attr("src",projects[i]['image']);
			counter++;
		}
		
		var bussy = false;
		function do_resize(overwrite)
		{
			bgCSS = {left: 0, top: 0}
                bgWidth = root.width();
                bgHeight = bgWidth / ratio;

                // Make adjustments based on image ratio
                // Note: Offset code provided by Peter Baker (http://ptrbkr.com/). Thanks, Peter!
                if(bgHeight >= root.height()) {
                    bgOffset = (bgHeight - root.height()) /2;
                    $.extend(bgCSS, {top: "-" + bgOffset + "px"});
                } else {
                    bgHeight = root.height();
                    bgWidth = bgHeight * ratio;
                    bgOffset = (bgWidth - root.width()) / 2;
                    $.extend(bgCSS, {left: "-" + bgOffset + "px"});
                }
                $img.width( bgWidth ).height( bgHeight ).css(bgCSS);
		}
		
		var _cp = 0;
		var current_project;
		function next_project()
		{
			if(!$('body').hasClass('playing_video')){
				var current_project = projects[que[_cp]];
				//do_resize(true);
				$img.animate({
					opacity: 0
				}, 300,function(){
					ratio = current_project['ratio'];
					$img.load(function(){
						do_resize(true);
						$img.animate({
							opacity: 1
						},500,function(){
						});
					});
					$img.attr("src",current_project['image']);				
				});
				_cp++;
				if(_cp >= total_projects){
					_cp = 0;
				}
			}
			setTimeout(function(){
				//next_project();
			},7000);
		}
		
		$(window).resize(do_resize);

	}
	
})(jQuery);
