// http://akelpad.sourceforge.net/en/plugins.php#Scripts
// Version: 1.3
// Author: Shengalts Aleksander aka Instructor
//
// Description(1033): Spell check using Microsoft Word.
// Description(2052): 使用 Microsoft Word 来检查拼写。

//变量
var Word=new ActiveXObject("Word.application");
var hMainWnd=AkelPad.GetMainWnd();
var hWndEdit=AkelPad.GetEditWnd();
var oSys=AkelPad.SystemFunction();
var pScriptName=WScript.ScriptName;
var pSelText=AkelPad.GetSelText();

if (hWndEdit)
{
  if (Word)
  {
    if (pSelText)
    {
      var oSpellDoc;
      var pMessage;
      var pTextIn;
      var pTextOut;

      Word.Visible=false;
      Word.Options.SuggestSpellingCorrections=true;

      if (oSpellDoc=Word.Documents.Add())
      {
        oSpellDoc.Content.Text=pSelText;
        Word.ActiveWindow.WindowState=2;  //wdWindowStateMinimize
        if (parseInt(Word.Version) >= 15)
        {
          //MS Word 2013 and higher
          Word.Visible=false;
          oSys.Call("user32::SetForegroundWindow", oSpellDoc.ActiveWindow.Hwnd);
        }

        pTextIn=oSpellDoc.Content.Text;
        if (Word.Options.CheckGrammarWithSpelling == true)
          oSpellDoc.CheckGrammar();
        else
          oSpellDoc.CheckSpelling();
        pTextOut=oSpellDoc.Content.Text;

        oSpellDoc.Close(false);
      }
      Word.Quit(true);
      Word=0;

      if (pTextIn == pTextOut)
      {
        AkelPad.MessageBox(hMainWnd, GetLangString(2), pScriptName, 64 /*MB_ICONINFORMATION*/);
      }
      else
      {
        if (AkelPad.MessageBox(hMainWnd, GetLangString(3), pScriptName, 36 /*MB_ICONQUESTION|MB_YESNO*/) == 6 /*IDYES*/)
        {
          AkelPad.ReplaceSel(pTextOut.substr(0, pTextOut.length - 1), -2);
        }
      }
    }
    else AkelPad.MessageBox(hMainWnd, GetLangString(1), pScriptName, 48 /*MB_ICONEXCLAMATION*/);
  }
  else AkelPad.MessageBox(hMainWnd, GetLangString(0), pScriptName, 48 /*MB_ICONEXCLAMATION*/);
}
if (Word) Word.Quit(true);


//Functions
function GetLangString(nStringID)
{
  var nLangID=AkelPad.GetLangId(1 /*LANGID_PRIMARY*/);

  if (nLangID == 0x4) //LANG_CHINESE
  {
    if (nStringID == 0)
      return "您首先必须安装 Microsoft Word 97 或更高版本。";
    if (nStringID == 1)
      return "未选定文本。";
    if (nStringID == 2)
      return "未做任何拼写纠正。";
    if (nStringID == 3)
      return "要插入纠正后的文本吗?";
  }
  else
  {
    if (nStringID == 0)
      return "You must first install Microsoft Word 97 or higher.";
    if (nStringID == 1)
      return "No text selected.";
    if (nStringID == 2)
      return "No spelling corrections made.";
    if (nStringID == 3)
      return "Insert corrected text?";
  }
  return "";
}
