var path_ui;
var controller;
var view;
var level;

function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function finished()
{
	console.log( "Finished. Did we win? ", controller.won() );

	// Did the player win?
	if ( controller.won() )
	{
		win( level + 1 );
	}
	else
	{
		alert( "You died. Try again." );
		reset();
		path_ui.show();
		console.log( "Shown." );
	}
}

function resetUI()
{
	path_ui.reset();
	path_ui.showSand( controller.levels[level].sand );
}

function win( nextLevel )
{
	$( '#win' ).dialog({ modal: true,
            buttons: {
                OK: function() {
                    $( this ).dialog( "close" );
					window.location = "game.html?level=" + nextLevel;
                }
            }});
}

$( document ).ready( function() {
	level = getParameterByName( "level" );
	if ( !level && !parseInt( level ) )
		level = 0;
	else
		level = parseInt( level );

	if ( level == 6 )
	{
		var elem = 
			'<div>You have demonstrated skill.<br/>Your prize:<br/><br/>'
			+ '<img src="phone.jpg"/>'
			+ '</div>';
		
		$( elem ).dialog({
			modal: true,
			width: 700
		});
		
		return;
	}
		
	path_ui = new PathUI( '#pathContainer', 20, 20 );
	controller = new Controller( path_ui, level );
	view = new View( controller );

	init();
	animate();
});

function runGame()
{
	path_ui.hide();
	view.play();
}