$(function() {
	setBackground();
	setTimeout(setBackground, 500);
	$(window).resize(function() { setBackground(); });
});

function setBackground() {
	imageWidth 	= $('.background img').width();
	imageHeight	= $('.background img').height();
	windowWidth	= $(window).width();
	windowHeight= $(window).height();
	ratioView	= windowWidth / windowHeight;
	srcImage 	= $('.background img').attr('rel');
	srcImage	 = srcImage.split('.');
	
	if(ratioView > 1.3) {
		$('.background img').attr('src','/images/' + srcImage[0] + '_widescreen.' + srcImage[1]);		
	} else {
		$('.background img').attr('src','/images/' + srcImage[0] + '.' + srcImage[1]);
	}
	
	ratioWidth	= windowWidth / imageWidth;
	ratioHeight	= windowHeight / imageHeight;
	
	if(ratioWidth > 1 || ratioHeight > 1) {
		if(ratioWidth > 1 && ratioHeight > 1) {
		// Both ratiWidth AND ratioHeight bigger then 1
			if(ratioWidth > ratioHeight) {
				newHeight 	= imageHeight * ratioWidth;
				newWidth	= imageWidth * ratioWidth;
				$('.background img').css({height:newHeight,width:newWidth});
			} else {
				newHeight 	= imageHeight * ratioHeight;
				newWidth	= imageWidth * ratioHeight;
				$('.background img').css({height:newHeight,width:newWidth});
			}
		} else if(ratioWidth > 1) {
		// Ratio width is bigger ratioheight NOT
		newHeight 	= imageHeight * ratioWidth;
		newWidth	= imageWidth * ratioWidth;
		$('.background img').css({height:newHeight,width:newWidth});
		} else {
		// Ratio height bigger than 1
		newHeight 	= imageHeight * ratioHeight;
		newWidth	= imageWidth * ratioHeight;
		$('.background img').css({height:newHeight,width:newWidth});
		}
	} else if(ratioWidth > ratioHeight) {
	// RatioWidth bigger than ratioHeight but under 1
	newHeight 	= imageHeight * ratioWidth;
	newWidth	= imageWidth * ratioWidth;
	$('.background img').css({height:newHeight,width:newWidth});
	} else {
	// RatioHeight bigger than RatioWidth but under 1
	newHeight 	= imageHeight * ratioHeight;
	newWidth	= imageWidth * ratioHeight;
	$('.background img').css({height:newHeight,width:newWidth});
	}
}
