// http://akelpad.sourceforge.net/forum/viewtopic.php?p=23904#23904
// Version: 2015-03-19
// Author: KDJ
//
// *** Select tab by pressing Ctrl/Shift/Alt+Number (MDI/PMDI) ***
//
// Usage:
//   Call("Scripts::Main", 1, "TabNumberByKeyboard.js")
//   Call("Scripts::Main", 1, "TabNumberByKeyboard.js", "Argument")
//
// Argument:
//   "A" - Alt (default)
//   "C" - Ctrl
//   "S" - Shift (only in combination with Ctrl and/or Alt)
//   can be: "C", "A", "CS", "CA", "CSA", "SA"
//
// Remarks:
//   After first call, the script resides in the memory.
//   Second script call, closes the script.
//   For autostart, in AkelPad.ini or registry CmdLineBegin/CmdLineEnd key, need to add eg:
//     /Call("Scripts::Main", 1, "TabNumberByKeyboard.js", "SC")

var hScript = AkelPad.ScriptHandle(WScript.ScriptName, 3 /*SH_FINDSCRIPT*/);

if (hScript && AkelPad.ScriptHandle(hScript, 13 /*SH_GETMESSAGELOOP*/))
{
  //script already is running, close it
  AkelPad.ScriptHandle(hScript, 33 /*SH_CLOSESCRIPT*/);
}
else if (AkelPad.IsMDI())
{
  var oSys     = AkelPad.SystemFunction();
  var hMainWnd = AkelPad.GetMainWnd();
  var bCtrl    = false;
  var bShift   = false;
  var bAlt     = false;
  var sArg;
  var hSubClass;
  var lpFrame;
  var nTab;

  if (WScript.Arguments.length)
  {
    sArg = WScript.Arguments(0).toUpperCase();

    if (sArg.indexOf("C") >= 0)
      bCtrl = true;
    if (sArg.indexOf("S") >= 0)
      bShift = true;
    if (sArg.indexOf("A") >= 0)
      bAlt = true;

    if (bShift && (! bCtrl) && (! bAlt))
    {
      bShift = false;
      bAlt   = true;
    }
  }
  else
    bAlt = true;

  hSubClass = AkelPad.WindowSubClass(2 /*WSC_EDITPROC*/, EditCallback, bCtrl ? 256 /*WM_KEYDOWN*/ : 260 /*WM_SYSKEYDOWN*/);

  if (hSubClass)
  {
    //Allow other scripts running
    AkelPad.ScriptNoMutex();

    //Message loop
    AkelPad.WindowGetMessage();

    AkelPad.WindowUnsubClass(2 /*WSC_EDITPROC*/);
  }
}

function EditCallback(hWnd, uMsg, wParam, lParam)
{
  if ((uMsg == 256 /*WM_KEYDOWN*/) && (wParam >= 0x30 /*0 key*/) && (wParam <= 0x39 /*9 key*/) && Ctrl())
  {
    if ((bShift == Shift()) && (bAlt == Alt()))
      FrameActivate(wParam);
  }
  else if ((uMsg == 260 /*WM_SYSKEYDOWN*/) && (wParam >= 0x30 /*0 key*/) && (wParam <= 0x39 /*9 key*/))
  {
    if (bShift == Shift())
      FrameActivate(wParam);
  }

  return 0;
}

function FrameActivate(nKey)
{
  nTab = ((nKey == 0x30) ? 10 : nKey - 0x30) - 1;

  if (lpFrame = AkelPad.SendMessage(hMainWnd, 1290 /*AKD_FRAMEFINDW*/, 8 /*FWF_BYTABINDEX*/, nTab))
    AkelPad.SendMessage(hMainWnd, 1285 /*AKD_FRAMEACTIVATE*/, 0, lpFrame);
}

function Ctrl()
{
  return Boolean(oSys.Call("User32::GetKeyState", 0x11 /*VK_CONTROL*/) & 0x8000);
}

function Shift()
{
  return Boolean(oSys.Call("User32::GetKeyState", 0x10 /*VK_SHIFT*/) & 0x8000);
}

function Alt()
{
  return Boolean(oSys.Call("user32::GetKeyState", 0x12 /*VK_MENU*/) & 0x8000);
}
