var gameLoadWeight = 0.2; // Weight assigned to the initial game loading on the progress bar
var networkTimeoutDelay = 2000; // If no update occurs during this time, the connection is reset
var networkTimeoutMaxProgress = 0.9; // Progress above which the connection is never reset
var networkTimeout; // The timeout used to reset the connection
var downloadProgress = 0; // The total download progress
var game = {};
var gameInstanceUrl = "";

function Initialize(url)
{
  gameInstanceUrl = url;
  return LoadInstance();
}
function LoadInstance()
{
  return gameInstance = UnityLoader.instantiate("gameContainer", gameInstanceUrl, {onProgress: UnityProgress});
}

function UnityProgress(gameInstance, progress) {
  if (!gameInstance.Module)
    return;
  // Initialize
  if (progress == 0)
  {
    game.logo = $("#logo");
    game.progress = $("#progress");
    game.empty = $("#progress .empty");
    game.full = $("#progress .full");
    game.progressText = $("#progress_text");
    game.errorText = $("#error_text");
    game.container = $("#gameContainer");
    game.container[0].style.backgroundImage = "";
    downloadProgress = 0;
  }
  
  // Hide the logo
  if (progress == 1)
    game.logo.fadeOut(3000, function() { });
  UpdateProgress(progress * gameLoadWeight, "");
  // Network timeout
  if (progress < networkTimeoutMaxProgress && progress > 0)
    networkTimeout = setTimeout(function(){ console.log("Network timeout!"); LoadInstance(); }, networkTimeoutDelay);
}

function UpdateProgress(progress, progressText)
{
  // Reset the network timeout
  if (networkTimeout)
    clearTimeout(networkTimeout);
  networkTimeout = null;
  // Update the progress bars
  if (progress > downloadProgress)
    downloadProgress = progress;
  game.full[0].style.width = (100 * downloadProgress) + "%";
  game.empty[0].style.width = (100 * (1 - downloadProgress)) + "%";
  game.progressText.text(progressText);
  // End
  if (progress == 1)
  {
    game.progress.fadeOut(1000, function() { });
    game.progressText.fadeOut(500, function() { });
  }
}

// Display a network error
function NetworkError(error)
{
  game.errorText.text("");
}