// http://akelpad.sourceforge.net/forum/viewtopic.php?p=23454#23454
// Version: 2015-01-06
// Author: KDJ
// 
// *** Turn on/off LineBoard ruler ***
// 
// Usage:
//   Call("Scripts::Main", 1, "LineBoardRulerOnOff.js", "nHeight")
// 
// "nHeight"
//   Ruler height in pixels when visible. If < 1 or > 99 or ommited (and in plugin settings is 0), is set to default value 17.

if (! AkelPad.GetEditWnd())
  WScript.Quit();

var sPluginFile  = AkelPad.GetAkelDir(4 /*ADTYPE_PLUGS*/) + "\\LineBoard.dll";
var sPluginFunc = "LineBoard::Main";
var nArgHeight;
var nCurHeight;
var bPanelVisible;
var bRulerVisible;

if (WScript.Arguments.length)
  nArgHeight = parseInt(WScript.Arguments(0), 10);

if (isNaN(nArgHeight) || (nArgHeight < 1) || (nArgHeight > 99))
  nArgHeight = 0;

if (AkelPad.IsPluginRunning(sPluginFunc))
{
  bPanelVisible = IsPanelVisible();
  bRulerVisible = IsRulerdVisible();
  nCurHeight    = GetRulerHeight();

  if (bPanelVisible && bRulerVisible && nCurHeight)
    SetRulerHeight(-1);
  else
    ShowRuler();
}
else
{
  if (new ActiveXObject("Scripting.FileSystemObject").FileExists(sPluginFile))
  {
    if (AkelPad.CallW(sPluginFunc, 1) > 0)
    {
      bPanelVisible = IsPanelVisible();
      bRulerVisible = IsRulerdVisible();
      nCurHeight    = GetRulerHeight();

      ShowRuler();
    }
  }
  else
    WScript.Echo("File not exists: " + sPluginFile);
}

function IsPanelVisible()
{
  var lpVisible = AkelPad.MemAlloc(4 /*sizeof(BOOL)*/);
  var bVisible;

  AkelPad.CallW(sPluginFunc, 4, lpVisible);
  bVisible = AkelPad.MemRead(lpVisible, 3 /*DT_DWORD*/);
  AkelPad.MemFree(lpVisible);

  return bVisible;
}

function IsRulerdVisible()
{
  var lpHeight  = AkelPad.MemAlloc(4 /*sizeof(int)*/);
  var lpVisible = AkelPad.MemAlloc(4 /*sizeof(BOOL)*/);
  var bVisible;

  AkelPad.CallW(sPluginFunc, 2, lpHeight, lpVisible);
  bVisible = AkelPad.MemRead(lpVisible, 3 /*DT_DWORD*/);
  AkelPad.MemFree(lpHeight);
  AkelPad.MemFree(lpVisible);

  return bVisible;
}

function GetRulerHeight()
{
  var lpHeight = AkelPad.MemAlloc(4 /*sizeof(int)*/);
  var nHeight;

  AkelPad.CallW(sPluginFunc, 2, lpHeight);
  nHeight = AkelPad.MemRead(lpHeight, 3 /*DT_DWORD*/);
  AkelPad.MemFree(lpHeight);

  return nHeight;
}

function SetRulerHeight(nHeight)
{
  //if nHeight==-1, then invert ruler visibility
  AkelPad.CallW(sPluginFunc, 3, nHeight);
}

function ShowRuler()
{
  if (! bPanelVisible)
    AkelPad.CallW(sPluginFunc, 4); //show/hide panel

  if (! bRulerVisible)
    SetRulerHeight(-1);

  if ((! nCurHeight) || nArgHeight && (nArgHeight != nCurHeight))
    SetRulerHeight(nArgHeight ? nArgHeight : 17);
}
