$(function() {
	// Preload Function
	var $bkgrnd	= $('.top'),
		$bkgrnd_images		= $bkgrnd.find('img'),
		$bkgrnd_loading		= $('#bkgrnd_loading');
	$.fn.preload = function(options) {
		var opts 	= $.extend({}, $.fn.preload.defaults, options);
		o			= $.meta ? $.extend({}, opts, this.data()) : opts;
		var c		= this.length,
			l		= 0;
		return this.each(function() {
			var $i	= $(this);
			$('<img/>').load(function(i){
				++l;
				if(l == c) o.onComplete();
			}).attr('src',$i.attr('src'));	
		});
	};
	$.fn.preload.defaults = {
		onComplete	: function(){return false;}
	};
	
	//preload the images				
	$bkgrnd_images.preload({
		onComplete	: function(){
			$bkgrnd_loading.hide();
			init();
		}
	});
	
	//shows the first image and initializes events
	function init(){
		var $bkgrnd	= $('.bkgrnd'),
			$bkgrnd_images		= $bkgrnd.find('img'),
			$bkgrnd_img			= $bkgrnd_images.eq(0),
			total				= $bkgrnd_images.length,
			current				= 0,
			
			//$slides 			= $('.slides'),
			//$slides_divs		= $slides.find('div'),
			
			//$loopedSlider		= $('.loopedSlider'),
			//$larghezza			= $(window).width()*(3/4),
			$bkgrnd_loading		= $('#bkgrnd_loading'),
			dim = getImageDim($bkgrnd_img);
		
		//set the returned values and show the image
		$bkgrnd_img.css({
			width	: dim.width,
			height	: dim.height,
			left	: dim.left,
			top		: dim.top
		}).fadeIn();
		/*
		$slides_divs.css({
				width	: $larghezza
			}).fadeIn();
		
		$loopedSlider({
				width	: $larghezza
			}).fadeIn();
		*/	
		//resizing the window resizes the $bkgrnd_img
		$(window).bind('resize',function(){
			var dim	= getImageDim($bkgrnd_img);
			$bkgrnd_img.css({
				width	: dim.width,
				height	: dim.height,
				left	: dim.left,
				top		: dim.top
			});
		
		});
	}
	
	//animate the image to fit in the viewport
	function resize($img){
		var w_w	= $(window).width(),
			w_h	= $(window).height(),
			i_w	= $img.width(),
			i_h	= $img.height(),
			r_i	= i_h / i_w,
			new_w,new_h;
		
		if(i_w > i_h){
			new_w	= w_w;
			new_h	= w_w * r_i;
			
			if(new_h > w_h){
				new_h	= w_h;
				new_w	= w_h / r_i;
			}
		}	
		else{
			new_h	= w_w * r_i;
			new_w	= w_w;
		}
		
		$img.animate({
			width	: new_w + 'px',
			height	: new_h + 'px',
			top		: '0px',
			left	: '0px'
		},350);
	}
	
	//get dimentions of the image, 
	//in order to make it full size and centered
	function getImageDim($img){
		var w_w	= $(window).width(),
			w_h	= $(window).height(),
			r_w	= w_h / w_w,
			i_w	= $img.width(),
			i_h	= $img.height(),
			r_i	= i_h / i_w,
			new_w,new_h,
			new_left,new_top;
		
		if(r_w > r_i){
			new_h	= w_h;
			new_w	= w_h / r_i;
		}
		else{
			new_h	= w_w * r_i;
			new_w	= w_w;
		}

		return {
			width	: new_w + 'px',
			height	: new_h + 'px',
			left	: 0,//(w_w - new_w) / 2 + 'px'
			top		: 0//(w_h - new_h) / 2 + 'px'
		};
	}
	
});
