// http://akelpad.sourceforge.net/forum/viewtopic.php?p=3370#3370
// Version: 1.6
// Author: Shengalts Aleksander aka Instructor
//
//
// Description(1033): Close all unnamed/unexisted MDI/PMDI documents.
// Description(1049): Закрыть все безымянные/несуществующие документы MDI/PMDI.
//
// Arguments:
// -CloseUnnamed=false   -Close document without name (default is true).
// -CloseUnexisted=true  -Close document if file is deleted (default is false).
// -Prompt=true          -Prompt save document (default is false).
//
// Usage:
// Call("Scripts::Main", 1, "CloseUnnamedAll.js", `-CloseUnnamed=false -CloseUnexisted=true`)

//Arguments
var bCloseUnnamed=AkelPad.GetArgValue("CloseUnnamed", true);
var bCloseUnexisted=AkelPad.GetArgValue("CloseUnexisted", false);
var bPrompt=AkelPad.GetArgValue("Prompt", false);

//Variables
var hMainWnd=AkelPad.GetMainWnd();
var oSys=AkelPad.SystemFunction();
var lpFrameInit=0;
var lpFrameCur=0;
var bFrameClose=false;
var pFile;
var bWatchFile=false;

if (AkelPad.IsMDI())
{
  //Turn off watch file
  if (bWatchFile=AkelPad.SendMessage(hMainWnd, 1222 /*AKD_GETMAININFO*/, 147 /*MI_WATCHFILE*/, 0))
    AkelPad.SendMessage(hMainWnd, 1219 /*AKD_SETMAININFO*/, 147 /*MIS_WATCHFILE*/, false);

  for (;;)
  {
    if (!lpFrameCur) lpFrameCur=AkelPad.SendMessage(hMainWnd, 1288 /*AKD_FRAMEFIND*/, 1 /*FWF_CURRENT*/, 0);
    if (!lpFrameInit) lpFrameInit=lpFrameCur;

    //Is frame must be closed
    pFile=AkelPad.GetEditFile(0);
    if ((bCloseUnnamed && !pFile) ||
        (bCloseUnexisted && pFile && !IsFileExist(pFile)))
    {
      bFrameClose=true;
    }

    if (bFrameClose)
    {
      //Close MDI frame
      if (!bPrompt && AkelPad.GetEditModified(0))
        AkelPad.SendMessage(hMainWnd, 1229 /*AKD_SETMODIFY*/, 0, false);
      if (!AkelPad.Command(4318 /*IDM_WINDOW_FRAMECLOSE*/))
        break;
      if (lpFrameInit == lpFrameCur)
        lpFrameInit=0;
      lpFrameCur=0;
      bFrameClose=false;
    }
    else
    {
      //Next MDI frame
      lpFrameCur=AkelPad.Command(4316 /*IDM_WINDOW_FRAMENEXT*/);
      if (!lpFrameCur || lpFrameCur == lpFrameInit)
        break;
    }
  }

  //Turn on watch file
  if (bWatchFile)
    AkelPad.SendMessage(hMainWnd, 1219 /*AKD_SETMAININFO*/, 147 /*MIS_WATCHFILE*/, true);
}

function IsFileExist(pFile)
{
  if (oSys.Call("kernel32::GetFileAttributes" + _TCHAR, pFile) == -1)
    return false;
  return true;
}
