// Global variables 

var dbug      = 0;             // Debug 1=on 0=off
var whoIam    = "";            // The login user
var otp       = 12345;         // One Time password
var myName    = "";            // The login user on the screen
var myPass    = "";            // The login password
var thePass   = "";            //           password encrypted
var theComp   = "*DEMO";       // Initial company
var theName   = "DEMO/TEST";   // Initial company name
var theShort  = "IBIS";        // Initial short name
var encryptString = "EncryptionString";
var myLang    = "English";     // The language of choice
var oldLang   = "Anglais";     // The previously selected language
var urlLogin  = "sys/getMenu.php?param=";   // The server-side script 
var urlChoice = "sys/getOption.php?param="; // The server-side script 
var urlLang   = "sys/getLang.php?param=";   // The server-side script 
var urlFill   = "sys/getFill.php?param=";   // The server-side script 
var http      = getHTTPObject();        // We create the HTTP Object
var isWorking = false;         // Not waiting for HttpRequest
var xmlOpt    = "";            // Used to parse HttpRequest XML stream
var xmlDesc   = "";
var xmlAct    = "";
var optValue  = "";            // Selected option
var theHref   = "";            // Menu selected option
  
// Set text sizes of headings based on the global parameter textSizes
// set in tocParas and the browser:

var isIE = navigator.appName.toLowerCase().indexOf("explorer") > -1;
var mdi = (isIE) ? textSizes[1]:textSizes[3];
var sml = (isIE) ? textSizes[2]:textSizes[4];

// oldCurrentNumber keeps a headings ordering string (or number) 
// in case the ToC should change (tocChange > 0)
// but the content's location should remain unchanged (i.e. noLink == 1). 
// In those cases the heading preceeded by oldCurrentNumber has to remain
// highlighted (otherwise the heading preceeded by currentNumber has to
// be highlighted).
var oldCurrentNumber   = ""; 
var oldLastVisitNumber = "";
// nCols has the number of indents in the largest ToC index number 
// (the number of dots plus one) for controlling the levels
var nCol  = 0;
var nCols = 1;
// toDisplay: Array to keep the display status for each heading.
var toDisplay = new Array();

function getMenu() {
  if (!isWorking && http) {
     isWorking = true;
     whoIam = document.getElementById("uname").value;
     myPass = document.getElementById("pass").value;
     if (myPass != "") {
        thePass = encrypt(myPass);
        document.getElementById("pass").value = "";
        }
     http.open("get", urlLogin + escape(whoIam) + "|" + escape(thePass) +
               "|" + escape(myLang) + "|" + escape() + "|" + escape(theComp) + "|", true);
     http.onreadystatechange = handleHttpResponse;
     http.send(null);
     }
  }

function clearAll() {
  whoIam = "";
  otp = 12345;
  thePass = "";
  theComp = "*DEMO";
  theHref = "";
  theTarget = "goodbye.html";
  theName = "";
  myPass = "";
  printer = ">>:/dev/null:";
  tagDelay = 1;
  myName = "";
  theShort = "IBIS Inc";
  tocTab[0][1] = theShort;
  document.getElementById("uname").value = "";
  document.getElementById("pass").value = "";
  makeCookie();
//alert("Login: " + whoIam + ", Company: " + theComp + "(" + theName + ") , Printer: " + printer + ", " + myLang);
  getMenu();
//newDisplay();
//fillColumn(theHref, theTarget);
  }

function getStatus() {
  var center = document.getElementById("center");
  center.innerHTML += "<HR>Login: " + whoIam + ", Company: " + theComp + " (" + theName + ")<BR>Printer: " + printer + "(" + tagDelay + "), " + myLang;
  }

function reJig() {
  oldCurrentNumber   = ""; 
  oldLastVisitNumber = "";
  nCol  = 0;
  nCols = 1;
  toDisplay = new Array();
  // Set the system up from data in the TOC cookie, if there is one.
  myCookie = getCookie("TOC");
  if (myCookie) {
     tocData = myCookie.split("|");
     if (tocData.length > 6) {
        oldLang = myLang;
        myLang = unescape(tocData[0]);
        whoIam = unescape(tocData[1]);
        thePass = unescape(tocData[2]);
        theComp = unescape(tocData[3]);
        theName = unescape(tocData[4]);
        theShort = unescape(tocData[5]);
        printer = unescape(tocData[6]);
        tagDelay = unescape(tocData[7]);
        myName = whoIam;
        }
     }
  document.getElementById("uname").value = myName;
  var pname = printer.split(":");
  document.getElementById("pname").innerHTML = pname[1];
//makeCookie();
//alert("Login: " + whoIam + ", Company: " + theComp + "(" + theName + ") , Printer: " + printer + ", " + myLang);
//setCookie("TOC", myLang + "|" + whoIam + "|" + thePass + "|" + theComp + "|" + theName + "|" + theShort + "|" + escape(printer) + "|");
  name = document.getElementById('name');
  body = document.getElementById('left');
  body.setAttribute("bgcolor", backColor);
  div = document.getElementById('mid');
  div.innerHTML = "";
  // We fetch a new menu from the server and build it's array
  http.open("get", urlLogin + escape(whoIam) + "|" + escape(thePass) +
     "|" + escape(myLang) + "|" + escape() + "|" + escape(theComp) + "|", true);
  http.onreadystatechange = handleHttpResponse;
  http.send(null);
//getMenu();
  divLeft  = document.getElementById("left");
  divRight = document.getElementById("right");
  divHead  = document.getElementById("header");
  divFoot  = document.getElementById("footer");
  divCont  = document.getElementById("center");
  divLeft.style.backgroundColor = backColor;
  divRight.style.backgroundColor = backRColor;
  divHead.style.backgroundColor = backTColor;
  divFoot.style.backgroundColor = backTColor;
  divCont.style.backgroundColor = backCColor;
//fillColumn("#clear#", theTarget); 
  }

// ***************************************
// A function to redisplay the menu 
// ***************************************
function reDisplay(currentNumber,tocChange,noLink,e) {
   // Display flags are initialised so all the top level headings are displayed
   for (ir=0; ir<tocTab.length; ir++) {
      nCol = tocTab[ir][0].split(".").length;
      if (nCol == 1) { toDisplay[ir] = (nCol == 1) }
   }
   // Input parameters:
   // currentNumber: Hierarchical order (or number) of the heading to display
   // This controls the change of the ToC depending on the second parameter
   // tocChange and the content's URL depending on the third parameter noLink. 
   // tocChange: Controls how to change the ToC.
   //    0 = No change,
   //    1 = Change with automatic collapsing of expanded headings that
   //        are not on the path to the current heading,
   //    2 = Change without automatic colapsing 
   // noLink: Controls whether the content's URL shall be changed to the value
   // given by the 3rd element of an tocTab's entry (= 0) or not (= 1).
   // e: The event that triggered the function call.
   // If it is set it must be the event object.
   // If there is an event that triggered the function call, check the
   // control key depending on the browser used. 
   // If it is pressed and tocChange is greater than 0 tocChange is set to 2
   // so the ToC changes without automatic collapsing: 
   if (e) {
      // ctrlKeyDown = (isIE) ? e.ctrlKey : (e.modifiers==2);
      ctrlKeyDown = e.ctrlKey;
      if (tocChange && ctrlKeyDown) tocChange = 2;
   }
   // Initialize the ToC window's document and displaying the title on it's top.
   // The ToC is performed by a HTML table:
   div = document.getElementById('mid');
   div.innerHTML = "";
   tbl = document.createElement('table');
   div.insertBefore(tbl, null);
   tbl.border = "0";
   tbl.cellspacing = "1";
   tbl.cellpadding = "0";
   row = tbl.insertRow(tbl.rows.length);
   cell = row.insertCell(row.cells.length);
   cell.colSpan = nCols + 1;
   cell.innerHTML = "<a href=\"javaScript:history.go(0)\" onMouseDown=\"parent.reDisplay('" + tocTab[0][0] + "',0,0)\" style=\"font-family: " + fontTitle + "; font-weight:bold; font-size:" + textSizes[0] + "em; color: " + titleColor + "; text-decoration:none\">" + tocTab[0][1] + "</a>";
   // This is for defining the number of columns of the ToC table and the width of the last one. The first cells of each following row shall be empty or contain the heading symbol, the last ones are reserved for displaying the heading's text:
   row = tbl.insertRow(tbl.rows.length);
   for (k = 0; k < nCols; k++) {
      cell = row.insertCell(row.cells.length);
      cell.innerText = " ";
   }
   cell = row.insertCell(row.cells.length);
   cell.setAttribute("width", "240");
   cell.innerText = " ";
   //	currentLevel = the level of the current heading:
   var currentNumArray = currentNumber.split(".");
   var currentLevel = currentNumArray.length-1;
   // currentIndex = Current heading's index in the tocTab array:
   var currentIndex = null;
   for (i=0; i<tocTab.length; i++) {
      if (tocTab[i][0] == currentNumber) {
         currentIndex = i;
         break;
      }
   }
   // If currentNumber was not found in tocTab: No action.
   if (currentIndex == null) return false;
   // currentIsExpanded = Expand/Collapse-state of the current heading:
   currentIsExpanded = false;
   if (currentIndex < tocTab.length-1) {
      nextLevel = 99;
      for (j=1; (tocTab.length > currentIndex+j ) && ( currentLevel < nextLevel ) ; j++) {
         nextLevel = tocTab[currentIndex+j][0].split(".").length-1;
         if ( ( nextLevel > currentLevel ) && ( toDisplay[currentIndex+j] ) ) currentIsExpanded = true;
      }
   } 
   // Determining the new URL and target (if given) of the current heading
   theHref = (noLink) ? "" : tocTab[currentIndex][2];
   theTarget = tocTab[currentIndex][3];
   if (tocTab[currentIndex][2] == "Menu") {
      theHref = (noLink) ? "" : tocTab[currentIndex][3];
      }
   // ***************************************
   // 1st loop over the tocTab entries: Determining which heading to display:
   // ***************************************
   for (i=1; i<tocTab.length; i++) {
      // Nothing to do if the tocChange parameter is set to 0. If it is set to 1 or 2:
      if (tocChange) {
         thisNumber = tocTab[i][0];
         thisNumArray = thisNumber.split(".");
         thisLevel = thisNumArray.length-1;
         // isOnPath = this heading is on the path to the current heading in the
         // ToC hierarchy or a sibling of such a heading:
         isOnPath = true;
         if (thisLevel > 0) {
            for (j=0; j<thisLevel; j++) {
               isOnPath = (j>currentLevel) ? false : isOnPath && (thisNumArray[j] == currentNumArray[j]);
            }
         } 
         // By the following, the headings on the path to the current heading
         // and the siblings of such  headings (isOnPath==true, see above) will
         // be displayed anyway. 
         // If the tocChange parameter is set to 1 no other heading will be displayed.
         // If it is set to a number greater than 1 the headings that have been 
         // displayed before will additionally be displayed again.  
         toDisplay[i] = (tocChange == 1) ? isOnPath : (isOnPath || toDisplay[i]);
         // Now let's perform the expand/collapse mechanism: 
         // If the heading is a descendant of the current heading it's next display
         // depends on whether the current heading was expanded or collapsed. 
         // If it was expanded the descendants have not to be displayed this time,
         // otherwise only the children have to be displayed but not the grandchildren,
         // great-grandchildren etc.. 
         // Remember that currentIsExpanded says whether the current heading was
         // expanded or not. The if-clause is a criteria for being a descendant
         // of the current heading. If it's a descendant and
         // thisLevel == currentLevel+1 it's a child.
         if (thisNumber.indexOf(currentNumber+".")==0 && thisLevel > currentLevel) { 
            if (currentIsExpanded) toDisplay[i] = false;
            else toDisplay[i] = (thisLevel == currentLevel+1); 
         }
      } 
   } // End of loop over the tocTab
   // ***************************************
   // 2nd loop over the tocTab entries: Displaying the headings:
   // ***************************************
   var scrollY=0, addScroll=tocScroll; 
   for (i=1; i<tocTab.length; i++) {
      if (toDisplay[i]) {
         thisNumber = tocTab[i][0];
         thisNumArray = thisNumber.split(".");
         thisLevel = thisNumArray.length-1;
         isCurrent = (i == currentIndex);
         // Setting the heading's symbol depending on whether this heading is expanded
         // or not or if it is a leaf. It is expanded if any of the next level
         // headings has to be displayed: 
         if (i < tocTab.length-1) {
            nextLevel = 99;
            img = "leaf";
            for (j=1; ( tocTab.length > i+j ) && ( thisLevel < nextLevel ) ; j++) {
               nextLevel = tocTab[i+j][0].split(".").length-1;
               if (img != "minus") { 
                  if (thisLevel < nextLevel) {
                     img =  ((toDisplay[i+j]) ? "minus" : "plus");
                  }
               }
            }  
         } 
         else img = "leaf"; // The last heading is always a leaf.
         // If the scoll parameter is set true than increment the scrollY value:
         if (addScroll) scrollY+=((thisLevel<2)?mdi:sml)*25;
         if (isCurrent) addScroll=false;
         // thisTextColor = the text color of this heading
         if (img=="leaf") {
            if (noLink) 
               img = (thisNumber==oldCurrentNumber) ? "leafc":((thisNumber==oldLastVisitNumber) ? "leafp":"leaf");
            else
               img = (thisNumber==currentNumber) ? "leafc":((thisNumber==oldCurrentNumber) ? "leafp":"leaf"); 
         }
         if (noLink)
            thisTextColor = (thisNumber==oldCurrentNumber) ? currentColor:((thisNumber==oldLastVisitNumber) ? lastVisitColor:normalColor);
         else thisTextColor = (thisNumber==currentNumber) ? currentColor:((thisNumber==oldCurrentNumber) ? lastVisitColor:normalColor);
         // Now writing this ToC line, i.e. a table row...:			
         row = tbl.insertRow(tbl.rows.length);
         if (tocTab[i][1] == "Separator") {
            cell = row.insertCell(row.cells.length);
            cell.colSpan = nCols + 1;
            cell.innerHTML = "<HR/>";
            }
         else {
            // ...first some empty cells for the line indent depending on the level of this heading...:
            for ( k = 1; k <= thisLevel; k++) {
               cell = row.insertCell(row.cells.length);
               cell.innerText = " ";
            }
            // ...then the heading symbol and the heading text each with a javaScript link caling just this function reDisplay again: 
            cell = row.insertCell(row.cells.length);
            cell.setAttribute("valign", "top");
            cell.innerHTML = "<a href=\"javaScript:history.go(0)\" onMouseDown=\"parent.reDisplay('" + thisNumber + "'," + tocBehaviour[0] + "," + tocLinks[0] + ",event)\"><img src=\"toc/images/" + img + ".gif\" width=13 height=12 border=0></a>";
            cell = row.insertCell(row.cells.length);
            cell.colSpan = nCols-thisLevel;
            cell.innerHTML = "<a href=\"javaScript:history.go(0)\" onMouseDown=\"parent.reDisplay('" + thisNumber + "'," + tocBehaviour[0] + "," + tocLinks[1] + ",event)\" style=\"font-family: " + fontLines + ";" + "; font-size:" + mdi + "em; color: " + thisTextColor + "; text-decoration:none\">" + ((showNumbers)?(thisNumber+" "):"") + tocTab[i][1] + "</a>";
            }
      }
   } // End of loop over the tocTab
   // ***************************************
   // Closing the ToC document, scrolling its frame window and displaying
   // new content in the content frame or in the top window if required 
   // ***************************************
   // Updating the global variables oldCurrentNumber and oldLastVisitNumber. See above for its definition
   if (!noLink) { 
      oldLastVisitNumber = oldCurrentNumber;
      oldCurrentNumber = currentNumber;
   }
   // Scrolling the ToC if required
   if (tocScroll) scroll(0,scrollY);
   // Setting the top or content window's location if required
   if (dbug) document.getElementById('center').innerHTML = tocTab.join("<BR/>\n");
   if (theHref != "") {
      if (theTarget == "blank") {
//       document.getElementById("center").innerHTML = "&nbsp;";
         document.getElementById("right").innerHTML = " ";
         }      
      else fillColumn(theHref, theTarget); 
      }
   }

function fillColumn(theHref, theTarget) {
  if (!isWorking && http) {
     http.open("GET", urlFill + escape(otp) + "|" + escape(whoIam) + "|" + escape(thePass) + "|" + escape(theHref) + "|" + escape(theTarget) + "|" + escape(theComp), true);
     http.onreadystatechange = handleHTMLResponse;
     http.send(null);
     }
  }

function getOption() {
  alert("opt-test");
  if (!isWorking && http) {
     optValue = document.getElementById("option").value;
     http.open("GET", urlChoice + escape(otp) + "|" + escape(whoIam) + "|" + escape(thePass) + "|" + escape(myLang) + "|" + escape(optValue), true);
     http.onreadystatechange = handleHttpResponse;
     }
  }

function makeCookie() {
   setCookie("TOC", myLang + "|" + whoIam + "|" + thePass + "|" + theComp + "|" + theName + "|" + theShort + "|" + escape(printer) + "|" + escape(tagDelay) + "|", oneHour());
   }

function getLang() {
  alert("langtest");
  if (!isWorking && http) {
     oldLang = myLang;
     myLang = getElementById("lang").value;
     makeCookie();
     http.open("GET", urlLang + escape(otp) + "|" + escape(whoIam) + "|" + escape(thePass) + "|" + escape(myLang), true);
     http.onreadystatechange = handleHttpResponse;
     }
  }

function parseXML(node, show) {
   if (node.nodeName == "menu") {
      tocTab = tocTab.splice(0,1); ir = 1;
      if (show) { document.getElementById("center").innerHTML = ""; }
      }
   if (node.hasChildNodes && node.childNodes[0].nodeType != 3) {
      for (var n = 0; n < node.childNodes.length; n++) {
         parseXML(node.childNodes[n], show); }
      }
   else {
      if (show) {
         var divCent = document.getElementById("center");
         divCent.innerHTML = divCent.innerHTML + "<BR>" + node.nodeName + "=" + node.childNodes[0].nodeValue;
         }
      if (node.nodeName == "option") {
         xmlOpt = node.childNodes[0].nodeValue; }
      if (node.nodeName == "description") {
         xmlDesc = node.childNodes[0].nodeValue; }
      if (node.nodeName == "action") {
         xmlAct = node.childNodes[0].nodeValue; 
         if (xmlAct.substr(0,5) == "Menu=") {
            xmlAlt = xmlAct.substr(5); xmlAct = "Menu"; xmlLink = 1; }
         else { xmlAlt = ""; xmlLink = 0; }
         tocTab[ir] = new Array (xmlOpt, xmlDesc, xmlAct, xmlAlt, xmlLink); 
         ir++;
         }
      if (node.nodeName == "login") {
         whoIam = node.childNodes[0].nodeValue;
         alert(whoIam + ", you are now logged in");
         makeCookie();
         }
      if (node.nodeName == "company") {
         theComp = node.childNodes[0].nodeValue;
         makeCookie();
         }
      if (node.nodeName == "name") {
         theName = node.childNodes[0].nodeValue;
         makeCookie();
         }
      if (node.nodeName == "short") {
         theShort = node.childNodes[0].nodeValue;
         makeCookie();
         tocTab[0][1] = theShort;
         }
      if (node.nodeName == "printer") {
         printer = node.childNodes[0].nodeValue;
         var pname = printer.split(":");
         document.getElementById("pname").innerHTML = pname[1];
         makeCookie();
         }
      if (node.nodeName == "tagdelay") {
         tagDelay = node.childNodes[0].nodeValue;
         makeCookie();
         }
      }
   }
    
function handleHTMLResponse() {
  if (http.readyState == 4) { // Split the response into an array 
     if (http.status == 200) {
        theHTML = http.responseText;
        allHTML = theHTML.split("|||");
        if (allHTML[1]) document.getElementById("right").innerHTML = allHTML[1];
        newHTML = allHTML[0];
        if (newHTML == "") { newHTML = " "; }
        newScript = "";
        i = 0;
        do {
           uHTML = newHTML.toUpperCase();
           i = uHTML.indexOf("</SCRIPT>");
           if (i > 1) {
              newScript = newHTML.substr(0, i + 9);
              newHTML = newHTML.substring(i + 9);
              }
           uHTML = newScript.toUpperCase();
           j = uHTML.indexOf('SRC="'); 
           if ( j > 0) {
              newScript = newScript.substring(j + 5);
              i = newScript.indexOf('"');
              if (i > 1) { newScript = newScript.substr(0, i); }
              scripts = document.getElementsByTagName("script");
              unfound = true;
              for (i = 0; i < scripts.length; i++) {
                 if (scripts[i].src.match(newScript)) { 
                    unfound = false; break; }
                 }
              if (unfound) { dhtmlLoadScript(newScript); }
              }
           } while (i > 0);
        if (newHTML) document.getElementById("center").innerHTML = newHTML;
        if (allHTML[1]) document.getElementById("right").innerHTML = allHTML[1];
        if (allHTML[2]) {
           doit = allHTML[2].split("=");
           if (doit[0] == "#function") {
              isWorking = false;
              if (doit[1] == "clearAll") { clearAll(); }
              if (doit[1] == "getStatus") { getStatus(); }
              return;
              }
           }
        }
     else {
        alert("Problem retrieving the XML data:\n" + hhtp.statusText);
        }
     isWorking = false;
     }
  }
    
function handleHttpResponse() {
  if (http.readyState == 4) { // Split the response into an array 
     if (http.status == 200) {
        var xmlDocument = http.responseXML;
        var x = http.responseText;
        if (x.substr(0,5) == "ERROR") {
           alert(x);
           isWorking = false;
           return;
           }
//      alert(http.responseText);
        if (dbug) {
           x = http.responseText;
        // a = x.split("</"); x = a.join("#");
           a = x.split("<");  x = a.join(" #");
        // a = x.split(">");  x = a.join("#");
           document.getElementById("center").innerHTML = x;
           }
        parseXML(xmlDocument, dbug);
        if (dbug) { alert("pause"); }
        isWorking = false;
        newDisplay();
        }
     else {
        alert("Problem retrieving the XML data:\n" + hhtp.statusText);
        }
     }
  }

function newDisplay() {
   nCol  = 0;
   nCols = 1;
   for (ir=0; ir<tocTab.length; ir++) {
      nCol = tocTab[ir][0].split(".").length;
      if (nCol > nCols) nCols = nCol;
      toDisplay[ir] = nCol==1;
      }
   reDisplay('Top', 0, 0, 0);
   }

function getHTTPObject() { 
  var xmlhttp;
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
     try { xmlhttp = new XMLHttpRequest(); }
     catch (e) { xmlhttp = false; }
     }
  return xmlhttp;
  }
