/// Enclose selection
//           {
// text  ->    text
//           }

//Options
var pStartBracket="{";
var pEndBracket="}";
var pIndent="  ";

var hMainWnd=AkelPad.GetMainWnd();
var hWndEdit=AkelPad.GetEditWnd();
var oSys=AkelPad.SystemFunction();
var pScriptName=WScript.ScriptName;
var pFirstLineIndent;
var nSelStart;
var nSelEnd;
var pSelText;
var pLinesArray;
var nIndex;
var bNewLine=false;
var pResult;

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

  if (nSelStart != nSelEnd)
  {
    SelCompliteLine(hWndEdit, nSelStart, nSelEnd);
    nSelStart=AkelPad.GetSelStart();
    nSelEnd=AkelPad.GetSelEnd();
    pSelText=AkelPad.GetSelText();

    if (pLinesArray=pSelText.split("\r"))
    {
      pFirstLineIndent=pLinesArray[0].match(/[ \t]*/);

      for (nIndex=0; nIndex < pLinesArray.length; ++nIndex)
      {
        if (nIndex == pLinesArray.length - 1 && pLinesArray[nIndex] == "")
        {
          bNewLine=true;
          break;
        }
        if (pLinesArray[nIndex] != "")
          pLinesArray[nIndex]=pIndent + pLinesArray[nIndex];
      }
      pResult=pLinesArray.join("\r");

      pResult=pFirstLineIndent + pStartBracket + "\r" + pResult + (bNewLine?"":"\r") + pFirstLineIndent + pEndBracket + (bNewLine?"\r":"");
      AkelPad.ReplaceSel(pResult);
      AkelPad.SetSel(nSelStart, nSelStart + pResult.length);
    }
  }
  else AkelPad.MessageBox(hMainWnd, GetLangString(0), pScriptName, 48 /*MB_ICONEXCLAMATION*/);
}


//Functions
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;
    nMinSel=nMinLineIndex;

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

function GetLangString(nStringID)
{
  var nLangID;

  nLangID=oSys.Call("kernel32::GetUserDefaultLangID");
  nLangID=nLangID & 0x3ff; //PRIMARYLANGID

  if (nLangID == 0x4) //LANG_CHINESE
  {
    if (nStringID == 0)
      return "未选定文本。";
  }
  else
  {
    if (nStringID == 0)
      return "No text selected.";
  }
  return "";
}