(function($) {
	$.fn.simple_background_image = function(images_json, options) {
		
		//*var SpeedTest = function() {  
		  /* 
		  From:  http://techallica.com/kilo-bytes-per-second-vs-kilo-bits-per-second-kbps-vs-kbps/ 
		  256 kbps            31.3 KBps 
		  384 kbps            46.9 KBps 
		  512 kbps            62.5 KBps 
		  768 kbps            93.8 KBps 
		  1 mbps ~ 1000kbps   122.1 KBps 
		  */  
		/*};  
		SpeedTest.prototype = {  
		  imgUrl: "images/load_speed.png"    // Where the image is located at  
		  ,size: 3871                // bytes  
		  ,run: function( options ) {  
		  
			if( options && options.onStart )  
			  options.onStart();  
		  
			var imgUrl = this.imgUrl + "?r=" + Math.random();  
			this.startTime = (new Date()).getTime() ;  
		  
			var testImage = new Image();  
			var me = this;  
			testImage.onload = function() {  
			  me.endTime = (new Date()).getTime();  
			  me.runTime = me.endTime - me.startTime;  
		  
			  if( options && options.onEnd )  
				options.onEnd( me.getResults() );  
			};  
			testImage.src = imgUrl;  
		  }  
		  
		  ,getResults: function() {  
			if( !this.runTime )  
			  return null;  
		  
			return {  
			  runTime: this.runTime  
			  ,Kbps: ( this.size * 8 / 1024 / ( this.runTime / 1000 ) )  
			  ,KBps: ( this.size / 1024 / ( this.runTime / 1000 ) )  
			};  
		  }  
		}  */

		Array.prototype.shuffle = function ()
		{
			var i = this.length, j, temp;
			if ( i == 0 ) return;
			while ( --i ) {
				j = Math.floor( Math.random() * ( i + 1 ) );
				temp = this[i];
				this[i] = this[j];
				this[j] = temp;
			}
		};
		
		$body = $('body');
		$window = $(window);
		$document = $(document);
		$container = $('#container');
		$logo = $('#logo');
		$branding_white = $logo.find('.white');
		$branding_blue = $logo.find('.blue');
		
		var defaults = {
			delay			:	500,
			min_top			:	100,
			load_delay		:	2000,
			next_delay		:	10000,
			fade_delay		:	500,
			image_id_prefix	:	'',
			image_type		:	'all',
			blur			:	false,
			show_solution	:	false
		};

		//	Uses backbone's faster method if available because
		//	we need to do this everytime a link is clicked.
		if(typeof _ !== 'undefined' && typeof _.extend === 'function') {
			options = _.extend(defaults, options);
		} else {
			options = $.extend(defaults, options);
		}
		
		var methods = {	
		}
		
		
		//	Track the windows focus so we only change things while
		//  people are focused on it
		var window_focus = true;
		
		if (/*@cc_on!@*/false) { // check for Internet Explorer
			document.onfocusin = on_focus;
			document.onfocusout = on_blur;
		} else {
			window.onfocus = on_focus;
			window.onblur = on_blur;
		}
		
		function on_blur() {
			window_focus = false;
		}
		
		function on_focus() {
			window_focus = true;
		}
		
		
		//	Attach the image holder to the body document
		
		var holder = ich.simple_background_image_holder();
		$holder = $(holder);
		$body.prepend($holder);
		
		var images_length = 0;
		
		/*var st = new SpeedTest();  
		st.run({  
		  onStart: function() {  
			console.log('Before Running Speed Test');
			 
		  }  	  
		  ,onEnd: function(speed) {  
			console.log( 'Speed test complete:  ' + speed.Kbps + ' Kbps');  
			// put your logic here  
			if( speed.Kbps < 200 )  
			{  
			  console.log('Your connection is too slow');  
			}  
		  }  
		});*/  
		
		//	load the images when this script loads
		$.ajax({
			url:	images_json,
			dataType:	'json',
			success:	function(json_images){
				//	we have images, let's do something
				resize_background();
				json_images.shuffle();
				images_length = 0;
				
				var j = 0;
				var images = new Array();
				if (options.image_type == 'all') {
					
					for (var i = 0; i < json_images.length; i++)
					{
						
						if (json_images[i].img_src.indexOf('aero_2') < 0 && json_images[i].img_src.indexOf('aero_3') < 0 && json_images[i].img_src.indexOf('aero_4') < 0)
						{
							images[j++] = json_images[i];
							images_length ++;
						}
					}
					
					//images = json_images;
					//images_length = json_images.length;
				} else {
				for (var i = 0; i < json_images.length; i++)
					{
						
						if (json_images[i].img_src.indexOf(options.image_type) > -1)
						{
							images[j++] = json_images[i];
							images_length ++;
						}
					}
				}
					
				load_image(images,0);
			},
			error:		function(data){
				//	die gracefully
			}
		});
		
		
		function load_image(images,i)
		{
			var image = images[i];

				image.id = options.image_id_prefix + i;
				image.z_index = images_length - i;
				
				//	Blur content images
				/* if($container.children().length > 0)
				{
					blur_img = image.img_src.split('.j');
					image.img_src = blur_img[0] + '_blur.j' + blur_img[1];
				} */
				var image_holder = ich.simple_background_image(image);
				
				$image_holder = $(image_holder);
				
				$holder.append($image_holder);
				
				/*if(options.show_solution){
					$image_holder.find('.solution, .problem').show();
				}*/
				
				if($container.children().length < 1)
				{
					$image_holder.find('.solution, .problem').show();
				}
				
				$holder.find('div#'+i+' img').load(function(){
					$this = $(this);
					var i = $this.parent().attr('id');
					if (i == 0 && images_length > 1) setTimeout(function(){next_image(0)}, options.next_delay);
					if (i > 0) {
						 $this.parent().css({
						'display': 'none'
					}) 
					} else if (i == 0)
					{
						//	Clear the body background
						$body.css({
							background	:	'none'
							});
							
						$logo.css({
							background	:	'none'
						});
					}
					
				});
				
				
			i++;
			if (i < images_length) setTimeout(function(){load_image(images,i)},options.load_delay);
			
		}
		
		function next_image(current)
		{
			if(window_focus){
				if(images_length > 1)
				{
				$current = $holder.find('div#'+current);
				$current.css({ 'z-index': images_length+2});
				$next = $current.next();
				if ($next.length < 1) $next = $holder.find('div#' + 0);
				$next.css({ 'z-index': images_length+1, display:'block'});
				
				$current.fadeOut(options.fade_delay);

				if (++current >= images_length) current = 0;
				setTimeout(function(){next_image(current)},options.next_delay)
				}
			} else {
				setTimeout(function(){next_image(current)},1000);
			}
		}

		//	resizes the background to ensure the full body is covered
		function resize_background(options)
		{
			var defaults = {
				delay:	100,
				y_offset:	200
			}

			if(typeof _ !== 'undefined' && typeof _.extend === 'function') {
				options = _.extend(defaults, options);
			} else {
				options = $.extend(defaults, options);
			}

			var window_resize;

			$window.bind('resize',on_resize);

			do_resize();

			
			function on_resize(e)
			{
				if(typeof window_resize == "number")
				{
					window.clearTimeout(window_resize);
					delete window_resize;
				}
				window_resize = window.setTimeout(do_resize, defaults['delay']);
			}

			function do_resize()
			{
				if ($container.children().length > 0)
				{
					$holder.css({
						height:	Math.max($container.height() + parseInt($container.css('top')) + options.y_offset, $window.height())
					});
				} else {
					delete window_resize;
				}
				
			}

		}
		
	}

})(jQuery);
