var canvas	= 0;		// canvas element
var context	= 0;		// context-object
var dummy	= 0;		// dummy canvas used for double-buffered rendering
var buffer	= 0;		// used for double-buffered rendering

var viewportWidth	= 0;
var viewportHeight	= 0;

// objects
var space = 0;

$(document).ready(function(){
	
	if ($.browser.msie)
	{
		$('div#layer_1').empty();
		$('div#fixed-nebulae').remove();
		
		alert('This site isn\'t viewable in Internet Explorer - go get a real web-browser!');
	}
	
	// initially, hide everything.
	$('div#layer_0').hide();
	$('div#layer_0').fadeIn('slow', function() {
		
		// callback
	});
});


// animation callback
var refreshInterval = (1000 / (33 + (1/3)));
window.requestFrame = ( function(callback) {
	
	return window.requestAnimationFrame ||
	window.webkitRequestAnimationFrame ||
	window.mozRequestAnimationFrame ||
	window.oRequestAnimationFrame ||
	window.msRequestAnimationFrame ||
	function(callback) { window.setTimeout(callback, 1000 / 60); };
	
})();

window.onload = function() {
	
	viewportWidth = window.innerWidth;
	viewportHeight = window.innerHeight;
	
	// set up canvas
	canvas = document.getElementById('canvas');
	canvas.width = viewportWidth;
	canvas.height = viewportHeight;
	
	context = canvas.getContext('2d');
	
	// set up buffer
	dummy = document.createElement('canvas');
	dummy.width = viewportWidth;
	dummy.height = viewportHeight;
	
	buffer = dummy.getContext('2d');
	
	// create space object
	space = new Space(buffer, viewportWidth, viewportHeight);
	
	// call first frame
	requestFrame( function() { update(); } );
};

window.onresize = function() {
	
	// handle resize
};

function update()
{
	var e = jQuery.Event();
	
	// update all objects
	space.updateSpace();
	
	// render the frame
	render();
	
	// request next frame
	requestFrame(function(){ update(); });
};

function render()
{
	// draw space
	space.drawSpace();
	
	// clear the context
	clearContext(context);
	
	// copy the buffer onto the context
	context.drawImage(dummy, 0, 0, canvas.width, canvas.height);
	
	// clear the buffer
	clearContext(buffer);
}
