/// Rename current editing file

// Modified by Infocatcher
// version: 2011-01-01

//Variables
var fso=new ActiveXObject("Scripting.FileSystemObject");
var hMainWnd=AkelPad.GetMainWnd();
var oSys=AkelPad.SystemFunction();
var pScriptName=WScript.ScriptName;
var pFileFullName=AkelPad.GetEditFile(0);
if(!pFileFullName)
{
  AkelPad.MessageBox(hMainWnd, GetLangString(2), pScriptName, 48 /*MB_ICONEXCLAMATION*/);
  WScript.Quit();
}
var pFileName=fso.GetFileName(pFileFullName);
var pFileDir=pFileFullName.replace(/[^\\\/]*$/, "");
var pText="";

if (hMainWnd)
{
  while(true) {
    pText=AkelPad.InputBox(hMainWnd, pScriptName, GetLangString(0), pFileName);
    if(!pText)
      break;
    pNewFileFullName = pFileDir + "\\" + pText;
    if(fso.FileExists(pNewFileFullName) || fso.FolderExists(pNewFileFullName))
      AkelPad.MessageBox(hMainWnd, GetLangString(1).replace("%S", pText), pScriptName, 48 /*MB_ICONEXCLAMATION*/);
    else
      break;
  }

  if (pText && pText != pFileName)
  {
    var nFlags=0;
    var nCodePage=AkelPad.GetEditCodePage(0);
    var nBOM=AkelPad.GetEditBOM(0);

    var lpPoint = AkelPad.MemAlloc(8 /*sizeof(POINT)*/, true);
    if(lpPoint) {
      var hWndEdit = AkelPad.GetEditWnd();
      AkelPad.SendMessage(hWndEdit, 1245 /*EM_GETSCROLLPOS*/, 0, lpPoint);
      var columnSel = AkelPad.SendMessage(hWndEdit, 3127 /*AEM_GETCOLUMNSEL*/, 0, 0);
      var ss = AkelPad.GetSelStart();
      var se = AkelPad.GetSelEnd();

      //Close editing file
      if(AkelPad.SendMessage(hMainWnd, 273 /*WM_COMMAND*/, 4324 /*IDM_WINDOW_FILECLOSE*/, 0)) {
        //Rename file
        try {
          fso.MoveFile(pFileFullName, pNewFileFullName);
        }
        catch(e) {
          var err = e;
          pNewFileFullName = pFileFullName;
        }

        //Open file
        AkelPad.OpenFile(pNewFileFullName, nFlags, nCodePage, nBOM);

        hWndEdit = AkelPad.GetEditWnd();
        AkelPad.SetSel(ss, se);
        columnSel && AkelPad.SendMessage(hWndEdit, 3128 /*AEM_UPDATESEL*/, 0x1 /*AESELT_COLUMNON*/, 0);
        AkelPad.SendMessage(hWndEdit, 1246 /*EM_SETSCROLLPOS*/, 0, lpPoint);
      }

      AkelPad.MemFree(lpPoint, true);
      if(err)
        throw err;
    }
  }
}

//Functions
function GetLangString(nStringID)
{
  var nLangID;

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

  if (nLangID == 0x4) //LANG_CHINESE
  {
    if (nStringID == 0)
      return "新名称:";
    if (nStringID == 1)
      return "文件 \u201c%S\u201d 已经存在!";
    if (nStringID == 2)
      return "文件未保存!";
  }
  else
  {
    if (nStringID == 0)
      return "New name:";
    if (nStringID == 1)
      return "File \u201c%S\u201d already exists!";
    if (nStringID == 2)
      return "File not saved!";
  }
  return "";
}