$(document).ready(function() {
	
	var viewWidth, viewHeight, image, imageWidth, imageHeight, menu;
	
	image = $('#image img');
	imageWidth = image.attr('width');
	imageHeight = image.attr('height');
	menu = $('#menu');
	
	scale();
	
	$('#preloadedimages').each(function() {
		var img = new Image();
		img.src = this.src;
	});
	
	$(window).resize(function(){
		var newViewWidth = ($.browser.msie) ? document.documentElement.clientWidth : window.innerWidth;
		var newViewHeight = ($.browser.msie) ? document.documentElement.clientHeight : window.innerHeight;
		if (viewWidth != newViewWidth || viewHeight != newViewHeight) { scale(); }
	});
	
	function updateViewportSize () {
		viewWidth = ($.browser.msie) ? document.documentElement.clientWidth : window.innerWidth;
		viewHeight = ($.browser.msie) ? document.documentElement.clientHeight : window.innerHeight;	
	}
	
	function scale () {
		updateViewportSize();
		var bodypadding = 22;
		var menuspacer = 2;
		var logowidth = 155;
		var menuheight = 1;
		var maxWidth = viewWidth - bodypadding - (logowidth * 2);
		var maxHeight = viewHeight - bodypadding - menuheight - menuspacer;
		size = imageResize(imageWidth, imageHeight, maxWidth, maxHeight);
		menu.css({
			'width' : (size[0] + logowidth),
			'left' : Math.round(((viewWidth - size[0]) / 2) - logowidth),
			'top' : Math.round((bodypadding / 2)  + menuspacer + size[1])
		});
		image.parent('div#image').css({
			'width' : size[0],
			'left' : Math.round(viewWidth - size[0]) / 2,
			'top' : Math.round(bodypadding / 2)
		});
		image.attr('width', size[0]);
		image.attr('height', size[1]);
	}
	
	function imageResize (width, height, maxWidth, maxHeight) {
		var newWidth = parseInt(width);
		var newHeight = parseInt(height);
		var maxWidth = Math.abs(parseInt(maxWidth));
		var maxHeight = Math.abs(parseInt(maxHeight));
		if (newWidth > maxWidth) { newWidth = maxWidth; newHeight = Math.abs(newWidth/(width/height)); }    
		if (newHeight > maxHeight) { newHeight = maxHeight; newWidth = Math.abs(newHeight/(height/width)); }
		newWidth = Math.round(newWidth);
		newHeight = Math.round(newHeight);
		return new Array(newWidth, newHeight);
	}
	
});
