var imgHeight, imgRatio, imgWidth;

function initBackground() {
	imgHeight = $('#background').height();
	imgWidth = $('#background').width();
	imgRatio = imgWidth / imgHeight;
	scaleBackground();
}

function scaleBackground() {
	var height = $(window).height();
	var width = $(window).width();
	var ratio = width / height;
	$('#backgroundContainer').css({height: height + 'px', width: width + 'px'});
	
	var multiplier = (imgRatio >= ratio) ? height / imgHeight : width / imgWidth;
	var newHeight = Math.ceil(imgHeight * multiplier);
	var newWidth = Math.ceil(imgWidth * multiplier);
	var marginLeft = (newWidth - width) ? Math.round((newWidth - width) * 0.5) : 0;
	var marginTop = (newHeight - height) ? Math.round((newHeight - height) * 0.5) : 0;
	$('#background').css({height: newHeight + 'px', margin: -marginTop + 'px 0 0 ' + -marginLeft + 'px', width: newWidth + 'px'}).show();
}

$(document).ready(function() {
	var rnd = Math.floor(Math.random() * 16) + 1;
	$('#background').hide().attr('src', '/images/texture' + rnd + '.jpg');
	$('#background').load(initBackground);
	$(window).resize(scaleBackground);
});