//
// ***************************
// *** Start of AlgFunc.js ***
// ***************************
//
  function LogMsg(msg) {
    return;

    if (gEditMode == "SERVER") {

      // Nop

    } else {

      var currentDate = new Date();
      var cd = currentDate.toTimeString();
      cd = cd.substr(0, 8);

      var Fsa    = new ActiveXObject("Scripting.FileSystemObject");
      var LogFile = "m:\\orde\\" + gAcronym + "\\work\\js.log";

      var FileA = Fsa.OpenTextFile(LogFile, 8, true); // 8 = Open for Appending

  //    FileA.WriteLine("- "+document.location);
  //    FileA.WriteLine("- "+msg);

      FileA.WriteLine(cd + " " + msg);
      FileA.Close();
    };

  }; // end of function LogMsg

  function GetUserId() {
    // Retrieve gUserid using a prompt

    var UserId = window.parent.gUserId;

    if (UserId != undefined) { // already set; note: no quotes around undefined!!
      return UserId;
    };

    UserId = prompt("Give UserId to be allowed to edit");

    if (UserId == "") {                    // (void) entered
      alert("Note: Editting not allowed without specifying userid"+
            "\n Press Edit to try again");
    } else if (UserId == null) {           // Cancel pressed
      alert("Note: Editting not allowed without specifying userid"+
            "\n Press Edit to try again");
      UserId = ""; // editing not allowed
    } else {
      UserId = UserId.toUpperCase();
      window.parent.gUserId = UserId;

    }; // end of if

    return UserId;

  }; // end of function

  function setTopSiteRoot() {
    /*
      Sets the root map of the Site in the top page
      (typically index.htm, but also can be indextest.htm)
      Corresponds to the map "Site" of an Orde! environment

      Note that the contents of "location" differs between
      - www.dreamware.nl/index.htm
      - www.dreamware.nl            though index.htm is loaded,
                                    it is not included in location
    */

    var loc;

    loc = location.toString();
    loc = loc.split("?")[0];       /* Strip off data that was passed */

    if (loc.indexOf(".htm") == "-1") { // typically "www.dreamware.nl"
      topSiteRoot = loc;
    } else {
      loc = loc.substring(0,loc.lastIndexOf("/"));
      topSiteRoot = loc;
    };

    return loc;

  }; // end of function setTopSiteRoot;

  function getSiteRoot() {
    /*
      Purpose: return the location of the site root
      Assumption: it is always called from a page other than the top of the site
      If called from an url that was not loaded as part of the site,
      the url format is assumed to be: topSiteRoot/xxx/yyy.htm
    */

    // alert(parent.location);
    // alert(typeof(parent.topSiteRoot));

    if (typeof(parent["topSiteRoot"]) === "undefined") { // opened directly
      var loc = location.toString();
      loc = loc.split("?")[0];       // Strip off data that was passed, if any
      loc = loc.substring(0,loc.lastIndexOf("/"));
      loc = loc.substring(0,loc.lastIndexOf("/"));
      return loc;
    } else {
      return parent.topSiteRoot;
    };
  }; // end of function getSiteRoot

  function testSiteRootNew() {
    var tl = new Array();
    tl[0] = "www.dreamware.nl/index.htm";
    tl[1] = "www.dreamware.nl/stt/id.htm";
    tl[2] = "www.dreamware.nl/index.htm";
    tl[3] = "www.dreamware.nl";
    tl[4] = "www.dreamware.nl/other.htm";
    tl[5] = "orde/xxx/site/index.htm";
    tl[6] = "orde/xxx/site/stt/id.htm";
    tl[7] = "orde/xxx/site/index.htm";
    tl[8] = "orde/xxx/site";
    tl[9] = "orde/xxx/site/other.htm";

    var msg = "";
    for (i = 0; i < tl.length; i++) {
      msg += "\n" + tl[i] + ": " + setTopSiteRoot(tl[i]);
    };

    alert(msg);

  };

  function GetSiteRoot() {
    return getSiteRoot();
  }; // End of GetSiteRoot

  function OpenUrl(form, stt, id, target, linktype) {
    // - Assumes a form with just one listbox (Select block)
    // - Url is formed out of "stt" and the selected item in the listbox
    // - Url can be an instance
    // - The page is opened in the frame "target"
    // alert(form.name);

    var val, sel, url;

    var loc = getSiteRoot();

    if (form == "") {
      if (id == "") {
        val = "none";
      } else {
        val = id;
      };
    } else {
      sel = form.elements[0].selectedIndex;
      val = form.elements[0].options[sel].value;
    };

    if (val != "none") {
      // in this case gStt equals "struct"
      if (linktype == "index") {
        url = loc+"/"+val+"/index1.htm";
        url = url.toLowerCase();
        if (target == "") {
          window.open(url, "instance");
        } else {
          window.open(url, target);
        }; // end of if target
      } else {
        url = loc+"/"+stt+"/"+val+".htm";
        url = url.toLowerCase();
        if (target == "") {
          target = window.self.name;
          window.open(url, target);
        } else {
        window.open(url, target);
        }; // en of if target
      }; // end of if linktype
    }; // end of if val

  }; // end of function OpenUrlOnSelect

  function OpenUrlOnClick(url, newStt, target) {
    // Open "url" depending on current window and on newStt in
    // - instance window
    // - reflink window
    // - index window

    url = url.toLowerCase() + "?launchedBy=" + gStt + "." + gId;
    // alert(url+" "+target+" "+window.name+" "+newStt+" "+gStt);

    if (target == "") {
      if (window.name == "instance") {
        if (gStt == "VIEW") {          // from home always to instance
          target = "instance";
          FocusInstance();
          window.open (url, target);
        } else if (newStt == gStt) {   // zoom in instance window
          target = "instance";
          FocusInstance();
          window.open (url, target);
        } else {                       // change of Stt
          target = "reflink";
          ShowReflink(url);
          // FocusReflink();
        };
      } else if (window.name == "index") {   // zoom in instance window
        target = "instance";
        FocusInstance();
        window.open (url, target);
      } else if (window.name == "zoom") {   // zoom in zoom window
          ShowReflink(url);
      } else if (window.name == "iframe") {   // zoom in zoom window
          ShowReflink(url);
      } else {                         // remain always in reflink window
        target = "reflink";
        window.open (url, target);
        // FocusReflink();
      };
    } else {                           // a target was specified
      if (target == "index") {
          window.open (url, target);
      } else if (target == "instance") {
          FocusInstance();
          window.open (url, target);
      } else if (target == "reflink") {
        //  FocusReflink();
          ShowReflink(url);
      } else {
          ShowReflink(url);
        ;
      };
    };

    // window.open (url, target);

  }; // End of OpenUrlOnClick

  function ShowReflink(srczoom) {

    var loc        = GetSiteRoot();
    var imagesize  = "width=800,height=600";
    imagesize      = "";
    var windowsize = "width=900,height=675";
    var windowparm = "left=100,"     +
                     "top=40,"       +
                     "toolbar=no,"   +
                     "menubar=no,"   +
                     "location=no,"   +
                     "scrollbars=no,"+
                     "resizable=yes," +
                     "status=no";

    var onclick = 'OnClick="JavaScript:window.close()"';
    var onmouse = '' // 'OnMouseOver="JavaScript:window.close()"';

    var fram = "zoom";
    var newwindow = window.open("",fram,windowsize+","+windowparm);
    var newsrc = loc + "/" + srczoom.substr(3); // + "?launchedBy=" + gStt + "." + gId;

    // var css;
    // css = '<Link Rel="stylesheet" Href="../view/orde.css" Type="text/css" />' ;
    // css += '<Link Rel="stylesheet" Href="../view/debweb.css" Type="text/css" />';

    var bodyopen     = "<body" +
                       " " + 'Style="background-color: white;"' +
                       ">";
    var bodyclose    = "</body>";
    var buttonstring = "<Button" +
                       " " + onclick +
                       " " + 'Style="text-align: center; background-color: silver; width: 100%;"' +
                       ">" + "Sluit venster" + // " frame: " + fram
                       "</Button>";
    // var iframestring = "<IFrame" +
    var iframestring = '<IFrame Name="iframe"' +
                       " " + 'Src="' + newsrc + '"' +
                       " " + 'Width="100%" Height="90%"' +
                       ">" + "</Iframe>";

    var line = bodyopen +
               "<Center>" +
               buttonstring +
               "</Center>" +
               iframestring +
               buttonstring +
               bodyclose;

    newwindow.document.write(line);
    newwindow.document.close();
    newwindow.focus();

  }; // End of ShowReflink
  function FocusReflink() {
    return;
    // var cols2New = "20%,20%,60%"
    var cols2New = "20%,0%,80%"
    window.parent.document.getElementById("fscols2").cols = cols2New;
    window.parent.document.getElementById("inst").style.display = "none";
    window.parent.document.getElementById("refl").style.display = "";
    };

  function FocusInstance() {
    return;
    // var cols2New = "20%,60%,20%"
    var cols2New = "20%,80%,0%"
    window.parent.document.getElementById("fscols2").cols = cols2New;
    window.parent.document.getElementById("inst").style.display = "";
    window.parent.document.getElementById("refl").style.display = "none";
    };

  function OpenUrlOnMouse(url, target) {
    // Open "url" in "target"
    // If "target" == (void) Then
    //   Open "url" in "reflink" only when in "instance"
    //
    url = url.toLowerCase();

    if (target == ""){
      if (window.name == "instance") {
        // window.open (url, "reflink");
        ShowReflink(url);
      };
    } else {
      window.open (url, target);
    };

  }; // End of OpenUrlOnMouse

  function xOpenUrlOnClickOld(url, target) {
    // Open "url" in "target"
    // If "target" == (void) Then
    //   Open "url" in "instance" unless when in "reflink"
    //

    url = url.toLowerCase();

    if (target == "")
    {
      if (window.name == "reflink") {
        window.open (url, "reflink");
      } else {
        window.open (url, "instance");
      }; // end of if window.name
    } else {
      window.open (url, target);
    }; // end of if target

  }; // end of function xOpenUrlOnClickOld

  function ShowImg(srcinstance, imgparms, usemap, srcreflink, srczoom) {

    var width, onclick;

    /*
    window.alert("SrcInstance: "+srcinstance+"\n"+
                 "ImgParms   : "+imgparms+"\n"+
                 "UseMap     : "+usemap+"\n"+
                 "SrcReflink : "+srcreflink)
    */

    if (srcreflink == "") {
      srcreflink = srcinstance;
      // width = 'Width="200"';
      width = "";
    } else {
      width = "";
    };

    if (srczoom == "") {
      onclick = "";
    } else {
      onclick = 'OnClick="ShowZoom('+"'"+srczoom+"'"+')"';
    };

    if (window.name == "instance") {
      document.write('<IMG SRC="'+srcinstance+'"'+
                     ' '+imgparms+' '+usemap+' '+onclick+'/>');
    } else {
      if (window.name == "navigate") {
        document.write('<IMG SRC="'+srcinstance+'"'+
                       ' '+imgparms+' '+usemap+' '+onclick+'/>');
      } else {
        document.write('<IMG SRC="'+srcreflink+'"'+
                       ' '+width+' '+onclick+'/>');
      }; // end of if window.name navigate
    }; // end of if window.name instance
  }; // end of function ShowImg


  function ShowZoom(srczoom) {

    var loc        = getSiteRoot();
    var imagesize  = "width=800,height=600";
    imagesize      = "";
    var windowsize = "width=800,height=600";
    var windowparm = "left=100,top=40,"+
                     "toolbar=no,scrollbars=no,"+
                     "resizable=yes,status=no";

    var onclick = 'OnClick="JavaScript:window.close()"';

    var newwindow = window.open("","zoom",windowsize+","+windowparm);

    var imgstring = "<Img Src="+loc+"/"+srczoom+" "+imagesize+" "+onclick+">";

    newwindow.document.write(imgstring);

    newwindow.document.close();
    newwindow.focus();

  }; // End of ShowZoom

  function OpenPage(form, stt, frame) {
    // - Assumes a form with just one Select block
    // - Opens page of stt for selected item in fram
    // alert(form.name);

    var loc = getSiteRoot();
    var sel = form.elements[0].selectedIndex;
    var val = form.elements[0].options[sel].value;

    var newfile = loc+"/"+stt+"/"+val+".htm";
    newfile = newfile.toLowerCase();

    if (val != "none") {
      window.open(newfile, frame);
    };
  }; // end of function OpenPage

  function OpenNewForEdit(stt, seq, target) {

    LogMsg("OpenNewForEdit-Start, window.parent.gUserId: "+window.parent.gUserId);

    gUserId = GetUserId();

    LogMsg("OpenForEdit-AfterGetUserId, window.parent.gUserId: "+window.parent.gUserId);

    if (gUserId == "") {
      alert("Editting not allowed without specifying userid");
      return; //
    };

    // prompt for an id

    var NewId = prompt("Give Id of a new instance of "+gStt+": "+gSttText);

    // ToDo: validation?

    if (NewId == "") {                    // (void) entered
      alert("Note: Editting not possible without specifying an id"+
            "for "+gStt+": "+gSttText+
            "\n Press New to try again");
      NewId = ""; // editing not allowed
      return;
    } else if (NewId == null) {           // Cancel pressed
      alert("Note: Editting not possible without specifying an id"+
            "for "+gStt+": "+gSttText+
            "\n Press New to try again");
      NewId = ""; // editing not allowed
      return;
    } else {
      NewId = NewId.toUpperCase();
    }; // end of if

    // next checking whether NewId really new

    var IdListbox =  document.forms[0].elements[0];

    var isExisting = "No";
    var CurId
    var n =  IdListbox.options.length;
    for (var iOption = 0; iOption < n; iOption++) {
      CurId = IdListbox.options[iOption].value
      if (CurId.toUpperCase() == NewId) {
        isExisting = "Yes";
        break;
      }; // end of if
    }; // end of for

    if (isExisting == "Yes") {
      alert("The id you specified already exists"+
            "\n Press New to try again");

      return;
    };

    window.parent.gId        = NewId;
    window.parent.gEditFrame = target;

    OpenForEdit(stt, NewId, seq, target);

  }; // end of function OpenNewForEdit

  function OpenForEdit(stt, id, seq, target) {

    LogMsg("OpenForEdit-Start, window.parent.gUserId: "+window.parent.gUserId);

    gUserId = GetUserId();

    LogMsg("OpenForEdit-AfterGetUserId, window.parent.gUserId: "+window.parent.gUserId);

    if (gUserId == "") {
      alert("Editting not allowed without specifying userid");
      return; //
    };

    window.parent.gId        = id;
    window.parent.gEditFrame = target;

    // Remark: the "" makes a real string, otherwise it appears that it remains
    // as a variable that points to the location of the current document;
    // then the store ability does not work any more

//    window.parent.gHtmPage   = "" + document.location;


    var parm = "width=800,height=600,left=100,top=40,"+
               "toolbar=no,scrollbars=yes,resizable=yes,status=yes";
    var page = "_" + stt + seq + ".htm";
    window.open(page, target, parm);

  }; // end of function OpenForEdit

  function SubmitForEdit(stt, id, seq, target) {

    LogMsg("OpenForEdit-Start, window.parent.gUserId: "+window.parent.gUserId);

    gUserId = GetUserId();

    LogMsg("OpenForEdit-AfterGetUserId, window.parent.gUserId: "+window.parent.gUserId);

    if (gUserId == "") {
      alert("Editting not allowed without specifying userid");
      return; //
    };

    window.parent.gId        = id;
    window.parent.gEditFrame = target;

    // Remark: the "" makes a real string, otherwise it appears that it remains
    // as a variable that points to the location of the current document;
    // then the store ability does not work any more

//    window.parent.gHtmPage   = "" + document.location;

    var ReqForm  = document.ReqForm ;
    ReqForm.ReqStt.value = stt;
    ReqForm.ReqId.value  = id;
    ReqForm.submit();

  }; // end of function SubmitForEdit

  function ToggleOrdeAtt(divid) {
    // Assumes
    // - <P Class="OrdeAtt yyy" OnClick="ToggleOrdeAtt(DivId)"> ... </P>
    // - <Span Id="xxx_plus"> (+) </Span>
    // - <Span Id="xxx_minus"> (-) </Span>
    // - <Div Id="xxx"> .. </Div>
    //

    var div        = divid
    var spanplus   = divid + "_plus"
    var spanminus  = divid + "_minus"

    var curdisplay = document.getElementById(div).style.display

    if (curdisplay == "none" ) {
      document.getElementById(div).style.display       = "";
      document.getElementById(spanminus).style.display = "";
      document.getElementById(spanplus).style.display  = "none";
    } else {
      document.getElementById(div).style.display       = "none";
      document.getElementById(spanminus).style.display = "none";
      document.getElementById(spanplus).style.display  = "";
    }; // end of if

  }; // end of function ToggleOrdeAtt

// =================
// "Local" functions
// =================

function ReRead() {

  var reqAction = "!ReRead";
  var reqText   = "ReRead the site";

  if (window.parent.topEngineRuns == "Remote") {
    //; send asynchronously request to server
    httpPost(reqAction, reqText);
  } else {
    WriteToQueue(reqAction);
  };

  window.parent.gControlMsg = "ReRead started";
  window.open("controlmsg.htm","navigate");

  }; // end of function StartReRead

function Refresh() {

  var reqAction = "!Refresh";
  var reqText   = "Refresh the site";

  if (window.parent.topEngineRuns == "Remote") {
    //; send asynchronously request to server
    // alert(reqAction + "|" + reqText);
    httpPost(reqAction, reqText);
  } else {
    WriteToQueue(reqAction);
  };

  window.parent.gControlMsg = "Refresh started";
  window.open("controlmsg.htm","navigate");

  }; // end of function StartReRead

function checkEngine() {

  var reqAction = "!CheckEngine";
  var reqText   = "Check whether the Orde! engine is running";

  if (window.parent.topEngineRuns == "Remote") {
       alert("Check engine");
    // httpPost(reqAction, reqText);
    xmlhttpPost('', 'xxx', '2');
  } else {
    WriteToQueue(reqAction);
  };

  window.parent.gControlMsg = "CheckEngine done";
  window.open("controlmsg.htm","navigate");

  }; // end of function StartReRead

function StopEngine() {

  var reqAction = "Stop";
  var reqText   = "Stop the Orde! engine";

  if (window.parent.topEngineRuns == "Remote") {
    //; send asynchronously request to server
    httpPost(reqAction, reqText);
  } else {
    WriteToQueue(reqAction);
  };

  window.parent.gControlMsg = "Stop command issued";
  window.open("controlmsg.htm","navigate");

  }; // end of function StopEngine

function StartEngine() {

  // ToDo: implement heart beat function in Orde! engine
  //       then it is possible to determine whether the engine is running

  StopEngine(); // for sure

  window.setTimeout(";", 500);

  var sCmdLine = WorkPath + "\\" + Acronym + "_site.bat";
  var sCurDir  = WorkPath;

  var Pid = StartProcess(sCmdLine, sCurDir);

  window.parent.gControlMsg = "Engine started as " + sCmdLine + " with Pid " + Pid;
  window.open("controlmsg.htm","navigate");

  }; // end of function StartEngine

  function StartProcess(sCmdLine, sCurDir) {

    // oProcess: object representing the Win32_Process class
    // oMethod : object representing the Create method

    // oInPar  : object representing input parameters of the method
    // oOutPar : object representing output parameters of the method

    var oProcess            = GetObject("winmgmts://./root/cimv2:Win32_Process");
    var oMethod             = oProcess.Methods_("Create");
    var oInPar              = oMethod.inParameters.SpawnInstance_();
    oInPar.CommandLine      = sCmdLine;
    oInPar.CurrentDirectory = sCurDir;
    var oOutPar             = oProcess.ExecMethod_("Create", oInPar);

    return oOutPar.ProcessId;

  }; // end of function StartProcess

function WriteToQueue(command) {

  var Fsa    = new ActiveXObject("Scripting.FileSystemObject");

  var currentDate = new Date();
  var currentMsec = currentDate.valueOf();        // date in milliseconds

  var QueueItem  = QueuePath + "\\" + "l_" + currentMsec + ".Txt";

  if (Fsa.FolderExists(QueuePath) == false) {
    Fsa.CreateFolder(QueuePath);
  }; // end of if

  if (Fsa.FileExists(QueueItem) == true) {
    Fsa.DeleteFile(QueueItem);
  }; // end of if

  var FileA = Fsa.CreateTextFile(QueueItem, true);

  // FileA.WriteLine("!ReadFile " + SaveFile);
  FileA.WriteLine(command);
  FileA.Close();

  MvhSleep();

}; // end of function WriteToQueue

  function MvhSleep() {
    // wait 1 second
    var msec = 50;

    // alert("end of wait for "+msec+" milli seconds");
    window.setTimeout(";", msec);
  }; // end of function MvhSleep

  function putText(x, y, high) {
    var txt;
    if (y == "") {
      txt = x;
    } else {
      txt = x + "@" + y;
    };
    if (high == "B") {
      txt = "<B>" + txt + "</B>";
    };
    document.write(txt);
  };
//
// *************************
// *** End of AlgFunc.js ***
// *************************
//
  function getSearchData() {
    // this routine comes from "JavaScript en DHtml cookbook, paragraph 7.6"
      var results = new Object( );
      if (location.search.substr) {
          var input = unescape(location.search.substr(1));
          if (input) {
              var srchArray = input.split("&");
              var tempArray = new Array( );
              for (var i = 0; i < srchArray.length; i++) {
                  tempArray = srchArray[i].split("=");
                  results[tempArray[0]] = tempArray[1];
              }
          }
      }
      return results;
  };

