// http://akelpad.sourceforge.net/forum/viewtopic.php?p=1346#1346
// Description(1033): Spell check using Microsoft Word
// Description(1049): Проверка орфографии используя MS Word
// Version: 1.4 (2015.01.20)
// Author: VladSh
// Initial code: © Instructor

var pSelText;
var hMainWnd = AkelPad.GetMainWnd();
var nCursor = -1;

if (hMainWnd) {
   var pScriptName = WScript.ScriptName;
   
   pSelText = AkelPad.GetSelText();
   if (!pSelText) {
      nCursor = AkelPad.GetSelStart();
      pSelText = AkelPad.GetTextRange(0, -1);
   }
   
   if (pSelText.charCodeAt(0) != 0)
   {
      var Word = new ActiveXObject("Word.application");
      if (Word)
      {
         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;
					var oSys = AkelPad.SystemFunction();
					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);

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

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 == 3)
         return "插入纠正后的文本?";
   }
   else
   {
      if (nStringID == 0)
         return "You must first install Microsoft Word 97 or higher.";
      if (nStringID == 1)
         return "The text is absent.";
      if (nStringID == 3)
         return "Insert corrected text?";
   }
   return "";
}