 
     if KD.isLoggedIn()
       @emit 'AppManagerWantsToShowAnApp', appInstance, appView, appOptions
+      @setLastActiveIndex appInstance
       callback? appInstance
     else
       KD.getSingleton('router').handleRoute '/', replaceState: yes

    @unregister appInstance
    callback()

  get:(name)-> @appControllers[name]?.first or null

  getByView: (view)->

    appInstance = null
    for name, apps of @appControllers
      apps.forEach (appController)=>
        if view.getId() is appController.getView?()?.getId()
          appInstance = appController

    return appInstance

  getFrontApp:-> @frontApp

  setFrontApp:(@frontApp)->

  register:(appInstance)->

    name = appInstance.getOption "name"
    @appControllers[name] ?= []
    @appControllers[name].push appInstance
    @setListeners appInstance

  unregister:(appInstance)->

    name  = appInstance.getOption "name"
    index = @appControllers[name].indexOf appInstance

    if index >= 0
      @appControllers[name].splice index, 1
      if @appControllers[name].length is 0
        delete @appControllers[name]
      appInstance.destroy()


    appView?.once "KDObjectWillBeDestroyed", =>
      @unregister appInstance

  setLastActiveIndex:(appInstance)->

    return unless appInstance

    if optionSet = @appControllers[appInstance.getOption "name"]
      index = optionSet.instances.indexOf appInstance
      if index is -1 then optionSet.lastActiveIndex = null
      else optionSet.lastActiveIndex = index



