// -----------------------------------------------------------
// - uicontroller.js
// -
// - UIController is een klasse die verantwoordelijk is voor 
// - het laden van controllers in de UI.
// - Controllers worden slechts één maal geladen.
// - Bij het opstarten wordt de UIController slechts éénmaal
// - geladen. Daarom gebruiken we hier geen prototype methods.
// -----------------------------------------------------------

// De controllers zelf implementeren altijd een method "Toon()" en een method "Verberg()"
// Controllers worden ge�nstantieerd als anonieme functions.

// CLASS UIController
function UIControllerCollection()
{
    this._activeControllers = new Array();
       
    this._me = this;
}

UIControllerCollection.prototype.LoadController = function(controllerName, userCallback)
{
    var foundController = false;
    var controllerObject = null;

    for(var i in this._activeControllers)
    {
        if(this._activeControllers[i].Name == controllerName)
        {
            var me = this;
            controllerObject = this._activeControllers[i];
            foundController = true;
            if(userCallback)
            {
                setTimeout(function() {userCallback(me._activeControllers[i]);}, 10);
            }
            break;
        }
    }

    if(!foundController)
    {
        var controllerFile = CONTROLLER_PATH + controllerName + CONTROLLER_SUFFIX;
        var me = this;
      $.ajax({
        type: "GET",
        url: controllerFile,
        dataType: "html",
        success: function(data) {var controllerObject = me.HandleLoadController(data, controllerName);if(userCallback) {userCallback(controllerObject)};},
        error: this.handleLoadControllerError
      });
    }
}

UIControllerCollection.prototype.GetActiveController = function(controllerName)
{
    for(var i in this._activeControllers)
    {
        if(this._activeControllers[i].Name == controllerName)
        {
            controllerObject = this._activeControllers[i];
            return controllerObject;
        }
    }

    return null;
}

UIControllerCollection.prototype.HandleLoadController = function(controllerData, controllerName)
{
  try
  {
    eval(controllerData);
  }
  catch(controllerError)
  {
    alert("Could not initialize controller. " + controllerError);
  }
  return UIController.GetActiveController(controllerName);
}

UIControllerCollection.prototype.HandleLoadControllerError = function(XMLHttpRequest, textStatus, errorThrown)
{
    alert(textStatus);
}

UIControllerCollection.prototype.AutoShowControllerView = function(controllerObject)
{
    controllerObject.Show();
}

UIControllerCollection.prototype.RegisterController = function(controllerName, controllerObject)
{
  controllerObject.Name = controllerName;
  UIController._activeControllers.push(controllerObject);
}

var UIController = new UIControllerCollection();
