var hMainWnd=AkelPad.GetMainWnd();
var hEditWnd=AkelPad.GetEditWnd();
var oSys=AkelPad.SystemFunction();
var pScriptName=WScript.ScriptName;
var pSelText;
var pLinesArray;
var pTopL="©°";
var pTopR="©´";
var pBotL="©¸";
var pBotR="©¼";
var pHori="©¤";
var pVert="©¦";
var pGridHeader=pTopL;
var pGridFooter=pBotL;
var bColSel;

var nGridLength=0;

if (hMainWnd)
{
  if (AkelPad.IsAkelEdit())
  {
    if (AkelPad.SendMessage(hEditWnd, 3125 /*AEM_GETSEL*/, 0, 0))
    {
      bColSel = AkelPad.SendMessage(hEditWnd, 3127 /*AEM_GETCOLUMNSEL*/, 0, 0);

      if (!bColSel)
      {
        nSelStart=AkelPad.GetSelStart();
        nSelEnd  =AkelPad.GetSelEnd();

        SelCompliteLine(hEditWnd, nSelStart, nSelEnd);
      }

      pSelText=AkelPad.GetSelText();

      if (pLinesArray=pSelText.split("\r"))
      {
        for (i=0; i<pLinesArray.length; ++i)
        {
          if (pLinesArray[i].length > nGridLength)
            nGridLength=pLinesArray[i].length;
        }

        for (i=0; i<pLinesArray.length; ++i)
        {
          for (n=pLinesArray[i].length; n<nGridLength; ++n)
          {
            pLinesArray[i]+=" ";
          }
          pLinesArray[i]=pVert+pLinesArray[i]+pVert;
        }

        pSelText=pLinesArray.join("\r");

        for (i=0; i<nGridLength; ++i)
        {
          pGridHeader=pGridHeader+pHori;
          pGridFooter=pGridFooter+pHori;
        }
        pGridHeader=pGridHeader+pTopR;
        pGridFooter=pGridFooter+pBotR;

        pSelText=pGridHeader+"\r"+pSelText+"\r"+pGridFooter+"\r";

        AkelPad.ReplaceSel(pSelText);
      }
    }
    else AkelPad.MessageBox(hMainWnd, "No text selected.", pScriptName, 48 /*MB_ICONEXCLAMATION*/);
  }
  else AkelPad.MessageBox(hMainWnd, "Required AkelPad 4.x.x or higher", pScriptName, 48 /*MB_ICONEXCLAMATION*/);
}


//º¯Êý
function SelCompliteLine(hWnd, nMinSel, nMaxSel)
{
  var nMinLine;
  var nMaxLine;
  var nMinLineIndex;
  var nMaxLineIndex;
  var nMaxLineLength;

  if (nMinSel < nMaxSel)
  {
    nMinLine=AkelPad.SendMessage(hWnd, 1078 /*EM_EXLINEFROMCHAR*/, 0, nMinSel);
    nMaxLine=AkelPad.SendMessage(hWnd, 1078 /*EM_EXLINEFROMCHAR*/, 0, nMaxSel);
    nMinLineIndex=AkelPad.SendMessage(hWnd, 187 /*EM_LINEINDEX*/, nMinLine, 0);
    nMaxLineIndex=AkelPad.SendMessage(hWnd, 187 /*EM_LINEINDEX*/, nMaxLine, 0);
    nMaxLineLength=AkelPad.SendMessage(hWnd, 193 /*EM_LINELENGTH*/, nMaxSel, 0);

    if (nMaxLineIndex == nMaxSel) --nMaxLine;
    else if (nMaxLineLength) nMaxSel=nMaxLineIndex + nMaxLineLength + 1;

    nMinSel=nMinLineIndex;
    AkelPad.SetSel(nMinSel, nMaxSel);
    return nMaxLine - nMinLine + 1;
  }

  return 0;
}