
var gMenuStack = new Array(); // menu levels (array) -> Menu
var gCurrentMenu = null; // {Menu}, always same as last item in gMenuStack

/**
 * Menu
 *   title {String}
 *   items {Array of MenuItem}
 *   selectedItem {MenuItem}
 */
function Menu(title)
{
  assert(typeof(title) == "string", "Need title");
  this.title = title;
  this.items = new Array(); // of MenuItem
  this.selectedItem = null;
  this._loaded = false;
}
Menu.prototype =
{
  addMenuItem : function(menuitem)
  {
    assert (menuitem instanceof MenuItem, "Need a MenuItem as param");
    this.items.push(menuitem);

    if (this._loaded)
      createMenuItemElement(menuitem);
    if ( ! this.selectedItem)
      this.selectItem(menuitem)
  },
  /**
   * convenience function: creates MenuItem objects and adds it
   */
  createMenuItem : function(title, id, func)
  {
    var menuitem = new MenuItem(title, id, func);
    this.addMenuItem(menuitem);
  },
  selectItem : function(newSelection)
  {
    assert(newSelection instanceof MenuItem, "Need a MenuItem as param");
    if (newSelection == this.selectedItem)
      return;
    debug("selected item " + newSelection.title);

    var oldSelectedItem = this.selectedItem;
    this.selectedItem = newSelection;

    if (this._loaded && this == gCurrentMenu)
      updateSelectionDisplay(oldSelectedItem, this.selectedItem);
  },
  /**
   * Load this menu, will cause the menu to be displayed.
   * Call this when you have added all the menuitems that you want displayed.
   * (TODO delayed load)
   * 
   * Don't call this on Back button and similar, i.e. call it only once per Menu object.
   */
  load : function()
  {
    assert( ! this._loaded, "already loaded");
    //for (var i = 0; i < gMenuStack.length; i++)
    //  assert(gMenuStack[i] != this, already loaded");

    gMenuStack.push(this);
    gCurrentMenu = this;
    if (this.items[0])
     this.selectedItem = this.items[0];
    this._loaded = true;

    displayMenu(this);
  },
  __end : null
}

/**
 * MenuItem
 *   title {String}
 *   id {String}
 *   func {Function}
 *   element {DOM Element}
 */
function MenuItem(title, id, func)
{
  assert(typeof(title) == "string", "Need title");
  assert( ! func || typeof(func) == "function", "Need function");

  this.title = title;
  this.id = id;
  this.func = func;
  this.element = null;
}

/* Need the following functions implemented, in another file:
function setTitle(title)
function displayMenu(menu)
function createMenuItemElement(menuitem)
function updateSelectionDisplay(oldSelectedItem, newSelectedItem)
function scrollToItem(menuitem)
function keyHandler(aEvent)
*/
