const gPageItems = 10;

function actionBack()
{
  assert(gCurrentMenu, "need menu");
  assert(gMenuStack.length > 0, "need menu stack");
  var i = gMenuStack.indexOf(gCurrentMenu);
  assert(i >= 0, "gCurrentMenu.selectedItem not in gCurrentMenu.items");
  assert(i == gMenuStack.length - 1, "gCurrentMenu is not the last menu in gMenuStack");
  if (i == 0)
    return; // already at lop level
  gMenuStack.pop(); // remove last entry == gCurrentMenu
  gCurrentMenu = gMenuStack[gMenuStack.length - 1]; // make (new) last entry the current menu

  displayMenu(gCurrentMenu);
}

function actionDown(count)
{
  assert(gCurrentMenu, "need menu");
  assert(gCurrentMenu.selectedItem, "need selected item");
  var i = gCurrentMenu.items.indexOf(gCurrentMenu.selectedItem);
  assert(i >= 0, "selected item not in list of items of current menu");
  i = Math.min(i + count, gCurrentMenu.items.length - 1);
  gCurrentMenu.selectItem(gCurrentMenu.items[i]);
}

function actionUp(count)
{
  assert(gCurrentMenu, "need menu");
  assert(gCurrentMenu.selectedItem, "need selected item");
  var i = gCurrentMenu.items.indexOf(gCurrentMenu.selectedItem);
  assert(i >= 0, "selected item not in list of items of current menu");
  i = Math.max(i - count, 0);
  gCurrentMenu.selectItem(gCurrentMenu.items[i]);
}

function actionFirst()
{
  assert(gCurrentMenu, "need menu");
  assert(gCurrentMenu.items.length > 0, "need menu items");
  gCurrentMenu.selectItem(gCurrentMenu.items[0]);
}

function actionLast()
{
  assert(gCurrentMenu, "need menu");
  assert(gCurrentMenu.items.length > 0, "need menu items");
  gCurrentMenu.selectItem(gCurrentMenu.items[gCurrentMenu.items.length - 1]);
}

function actionLaunch()
{
  assert(gCurrentMenu, "need menu");
  assert(gCurrentMenu.selectedItem, "need selected item");
  var item = gCurrentMenu.selectedItem;
  var func = item.func;
  if ( ! func || typeof(func) != "function")
  {
    errorNonCritical("No function for this menu item found");
		return;
  }

  func(item.id);
}
