(function($){

	$.background = function(projects, name_selector, title_selector, body_selector){
	
		var _body = $(body_selector),
		_name = $(name_selector),
		_title = $(title_selector),
		$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);
		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()
		{
			current_project = projects[que[_cp]];
			//do_resize(true);
			$img.animate({
				opacity: 0
			}, 500,function(){
				ratio = current_project['ratio'];
				$img.attr("src",current_project['image']);
				do_resize(true);
				_body.html(current_project['body']);
				_name.html(current_project['name']);
				_title.html(current_project['title']);
				do_resize(true);
				$img.animate({
					opacity: 1
				},500,function(){
				});
			});
			_cp++;
			if(_cp >= total_projects){
				_cp = 0;
			}
			
			setTimeout(function(){
				next_project();
			},10000);
		}
		
		$(window).resize(do_resize);

	}
	
})(jQuery);

