// http://akelpad.sourceforge.net/forum/viewtopic.php?p=30468#30468
// Version: 2016-02-01
// Author: KDJ
//
// *** Prevents overwrite selection ***
// 
// Usage:
//   Call("Scripts::Main", 1, "NoOverwriteSelection.js", "-msg=true")
// 
// Argument (optional):
//   -msg - if false, message box is not displayed (default is true)
//
// Remarks:
//   After first call, the script resides in the memory. Second script call, closes it.
//   If the script is running, you can not overwrite selection. Can delete selection (DEL key or Menu->Edit->Delete).
//   For autostart, in AkelPad.ini or registry CmdLineBegin/CmdLineEnd key, need to add eg:
//     /Call("Scripts::Main", 1, "NoOverwriteSelection.js", "-msg=false")

var bMsg     = AkelPad.GetArgValue("msg", true);
var hMainWnd = AkelPad.GetMainWnd();
var hScript  = AkelPad.ScriptHandle(WScript.ScriptName, 3 /*SH_FINDSCRIPT*/);
var hSubClassMain;
var hSubClassEdit;

if (hScript && AkelPad.ScriptHandle(hScript, 13 /*SH_GETMESSAGELOOP*/))
{
  //script already is running, close it
  AkelPad.ScriptHandle(hScript, 33 /*SH_CLOSESCRIPT*/);

  if (bMsg)
    AkelPad.MessageBox(hMainWnd, "Prevention of overwrite selection is turned off.", WScript.ScriptName, 0x40 /*MB_ICONINFORMATION*/);
}
else if (hSubClassMain = AkelPad.WindowSubClass(1 /*WSC_MAINPROC*/, MainCallback, 273 /*WM_COMMAND*/))
{
  if (hSubClassEdit = AkelPad.WindowSubClass(2 /*WSC_EDITPROC*/, EditCallback, 256 /*WM_KEYDOWN*/, 258 /*WM_CHAR*/))
  {
    if (bMsg)
      AkelPad.MessageBox(hMainWnd, "Prevention of overwrite selection is turned on.", WScript.ScriptName, 0x40 /*MB_ICONINFORMATION*/);

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

  AkelPad.WindowUnsubClass(1 /*WSC_MAINPROC*/);
}

function MainCallback(hWnd, uMsg, wParam, lParam)
{
  var nCmd;

  if (uMsg == 273 /*WM_COMMAND*/)
  {
    nCmd = wParam & 0xFFFF;

    if ((nCmd == 4153 /*IDM_EDIT_CUT*/) ||
        (nCmd == 4155 /*IDM_EDIT_PASTE*/) ||
        (nCmd >= 4164 /*IDM_EDIT_INSERT_TAB*/) && (nCmd <= 4173 /*IDM_EDIT_DELETE_FIRST_CHAR_MENU*/) ||
        (nCmd >= 4175 /*IDM_EDIT_UPPERCASE*/)  && (nCmd <= 4180 /*IDM_EDIT_LOOPCASE*/) ||
        (nCmd == 4183 /*IDM_EDIT_INSERTDATE*/) ||
        (nCmd >= 4191 /*IDM_EDIT_PASTEANSI*/)  && (nCmd <= 4196 /*IDM_EDIT_AUTOINDENT*/))
    {
      if (AkelPad.GetSelStart() != AkelPad.GetSelEnd())
        AkelPad.WindowNoNextProc(hSubClassMain);
    }
  }

  return 0;
}

function EditCallback(hWnd, uMsg, wParam, lParam)
{
  if (uMsg == 256 /*WM_KEYDOWN*/)
  {
    if (wParam == 0x08 /*VK_BACK*/)
    {
      if (AkelPad.GetSelStart() != AkelPad.GetSelEnd())
        AkelPad.WindowNoNextProc(hSubClassEdit);
    }
  }
  else if (uMsg == 258 /*WM_CHAR*/)
  {
    if (AkelPad.GetSelStart() != AkelPad.GetSelEnd())
      AkelPad.WindowNoNextProc(hSubClassEdit);
  }

  return 0;
}
