var activeChildNode;
var bTreeFrameLoaded;
var bTitleFrameLoaded;
var actSearchPos;           // Aktueller Stücklisteneintrag für Suche
var srchIndex;              // Suchindex
var findwords;              // Suchbegriffe  


cPocketPC = 'Microsoft Pocket Internet Explorer';
cDocTypeTrans = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">';
cUTF8 = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">";
cPSS_CSS = "<link rel=\"stylesheet\" type=\"text/css\" href=\"pss.css\">\n";

cCatalogMain = 'catalogmain.htm';
cCatalogPPC = 'catalogppc.htm';
cSearch = 'search.htm';
cBasket = 'basket.htm';

function treeframeLoaded()
{
  bTreeFrameLoaded = 1;
}

function titleframeLoaded()
{
  if (activeChildNode)
    drawTitleframe(1);
}

// called by the HTML document once loaded first loading the user data, and then drawing the tree.
function start()
{
  loadData();
  activeChildNode = treeData[1];
  drawTree();
}

function dodrawTree()
{
  bTreeFrameLoaded = 0;
  treeframe.location.href = "blanktree.htm";
  timeOutId = setTimeout("drawTree()", 100);
}


// starts the recursive tree drawing process by first writing the root node, and then all subordinate branches.
function drawTree()
{
  if (bTreeFrameLoaded == 0)
  {
    timeOutId = setTimeout("drawTree()", 100);
  }
  else
  {
    var targetFrame;
    var imageString;

    // Auf welchen Frame wird gezeichnet
    outputFrame = treeframe.window.document;

    // HTML-Header
    outputFrame.open("text/html");
    outputFrame.writeln(cDocTypeTrans);
    outputFrame.writeln("<html>\n<head>");
    outputFrame.writeln(cUTF8);
    outputFrame.writeln(cPSS_CSS);
    outputFrame.writeln("</head>");
    outputFrame.writeln("<body bgcolor='" + webStyle.backgroundColor + "' background='" + webStyle.backgroundImage +
                        "' link='" + webStyle.linkColor + "' alink='" + webStyle.aLinkColor + "' vlink='" + webStyle.vLinkColor + "'>");
    outputFrame.writeln("<font face=\"" + TreeFont + "\" size=\"" + TreeFontSize + "\" color='" + webStyle.textColor + "'>");
    outputFrame.write(prefixHTML + "\n" + webStyle.UseTreeTag);

    // Unterscheidung Frameset oder nicht
    if (treeData[1].target == '')
      targetFrame = defaultTargetFrame;
    else
      targetFrame = treeData[1].target;

    // Icon?
    if (treeData[1].icon == "")
      imageString = defaultImageURL + 'globe.png';
    else
      imageString = defaultImageURL + treeData[1].icon;

    // Root-Knoten
    outputFrame.write("<a href=\"javascript:" + "parent.loadDataFrame('" + treeData[1].id +
                      "','" + treeData[1].ver + "'," + treeData[1].seq +
                      ",0)\" >\n" + "<img src='" + imageString +
                      "' width=16 height=16 align=top border=0 alt='" + treeData[1].url +
                      "'>&nbsp;");

    if (activeChildNode == treeData[1])
      outputFrame.write("<b>" + treeData[1].name + "</b>");
    else
      outputFrame.write(treeData[1].name);
    outputFrame.writeln("</a>" + webStyle.LineBreak);

    // Unterknoten ausgeben
    drawBranch(treeData[1].id, treeData[1].ver, 1, "");

    // Abschluss von Seite
    outputFrame.write(webStyle.UseTreeEndTag + "\n" + suffixHTML + "\n");
    outputFrame.write("</font>\n</body>\n</html>");
    outputFrame.close();
    window.status="";
  }

  if (navigator.appName == cPocketPC)
    titleframe.location.href = "blanktitle.htm";
}

// function to recursively draw all visable nodes in the tree structure.
function drawBranch(startNode, startNodeVer, startNodeSeq, structureString)
{
  var currentIndex = 1;

  // Unterknoten bestimmen
  var children = extractChildrenOf(startNode, startNodeVer, startNodeSeq);

  while (currentIndex <= children.length)
  {
    outputFrame.write(structureString);

    // Zielframe
    if (children[currentIndex].target == '')
      var targetFrame = defaultTargetFrame;
    else
      var targetFrame = children[currentIndex].target;

    if ((children[currentIndex].type == 'link') || (children[currentIndex].type == 'root'))
    {
      if (currentIndex != children.length)
        outputFrame.write(GetImageTag("linenotlast", 1));
      else
        outputFrame.write(GetImageTag("linelast", 1));

      if (children[currentIndex].icon == "")
        var imageString = defaultImageURL + defaultLinkIcon;
      else
        var imageString = defaultImageURL + children[currentIndex].icon;

      outputFrame.write("<a href=\"javascript:" + "parent.loadDataFrame('" + children[currentIndex].id +
                        "','" + children[currentIndex].ver + "'," + children[currentIndex].seq +
                        ",0)\" ><img src='" + imageString + "' width=16 height=16 align=top border=0 alt='" +
                        children[currentIndex].url + "'>&nbsp;");

      if (children[currentIndex] == activeChildNode)
        outputFrame.write("<b>" + children[currentIndex].name + "</b>");
      else
        outputFrame.write(children[currentIndex].name);

      outputFrame.writeln("</a>" + webStyle.LineBreak);
    }
    else
    {
      var newStructure = structureString;

	if (currentIndex != children.length)
      {
        if (children[currentIndex].open == 0)
        {
          outputFrame.write(GetTreeNavCode(children[currentIndex], 1, "plusnotlast"));
          outputFrame.write(GetListNavCode(children[currentIndex], 0));
        }
        else
        {
          outputFrame.write(GetTreeNavCode(children[currentIndex], 0, "minusnotlast"));
          outputFrame.write(GetListNavCode(children[currentIndex], 0));
          newStructure = newStructure + GetImageTag("vertline", 1);
          drawBranch(children[currentIndex].id, children[currentIndex].ver, children[currentIndex].seq, newStructure);
        }
      }
      else
      {
        if (children[currentIndex].open == 0)
        {
          outputFrame.write(GetTreeNavCode(children[currentIndex], 1, "pluslast"));
          outputFrame.write(GetListNavCode(children[currentIndex], 0));
        }
	  else
        {
          outputFrame.write(GetTreeNavCode(children[currentIndex], 0, "minuslast"));
          outputFrame.write(GetListNavCode(children[currentIndex], 0));
          newStructure = newStructure + GetImageTag("blank", 1);
          drawBranch(children[currentIndex].id, children[currentIndex].ver, children[currentIndex].seq, newStructure);
        }
      }
    }
    currentIndex++;
  }
}

function GetImageTag(imageFile, AddExtension)
{
  var htmlCode = "<img src='" + defaultImageURL + imageFile;
  if (AddExtension == 1)
    htmlCode = htmlCode + ".png";
  htmlCode = htmlCode + "' width=19 height=16 align=top>";

  return htmlCode;
}

function GetTreeNavCode(children, openMode, imagePrefix)
{
  var usedIcon;
  var htmlCode;

  if (openMode == 1)
  {
    if (children.iconClosed == "")
      usedIcon = "folder_close.png"
    else
      usedIcon = children.iconClosed;
  }
  else
  {
    if (children.iconOpen == "")
      usedIcon = "folder_open.png";
    else
      usedIcon = children.iconOpen;
  }
  htmlCode = "<a href=\"javascript:" + "parent.toggleFolder('" + children.id + "','" +
             children.ver + "'," + children.seq + "," + openMode + ")\"><img src='" +
             defaultImageURL + imagePrefix +
             ".png' width=19 height=16 alt='Click to close this folder' align=top border=0>" +
             "<img src='" + defaultImageURL + usedIcon +
             "' width=16 height=16 align=top border=0></A>&nbsp;";

  return htmlCode;
}

function GetListNavCode(children, withTreeNavigation)
{
  var htmlCode;

  htmlCode = "<a href=\"javascript:" + "parent.loadDataFrame('" + children.id + "', '" + children.ver + "', " + children.seq + ", " + withTreeNavigation + ")\">";

  if (children == activeChildNode)
    htmlCode = htmlCode + "<b>" + children.name + "</b>"; 
  else
    htmlCode = htmlCode + children.name;

  htmlCode = htmlCode + "</a>" + webStyle.LineBreak + "\n";
  return htmlCode;
}

function drawTitleframe(withData)
{
  // titleframe beladen
  var outputFrame2 = titleframe.window.document;

  outputFrame2.open('text/html');
  outputFrame2.writeln(cDocTypeTrans);
  outputFrame2.writeln('<html>\n<head>');
  outputFrame2.writeln(cUTF8);
  outputFrame2.writeln("<title>Titleframe</title>");
  outputFrame2.writeln("</head>\n<body>");
  if (withData == 1)
  {
    outputFrame2.writeln('<font face="Arial,Helvetica,sans-serif" size="2" color="#000000">');
    outputFrame2.writeln("<table>\n  <tr><td nowrap>");
    outputFrame2.writeln("<b>" + activeChildNode.name + "</b>");
    outputFrame2.writeln("</td></tr>\n</table>");
  }
  outputFrame2.writeln("</body>\n</html>");
  outputFrame2.close();
}

// html-page for data-frame
// withTreeNavigation: 0 = ohne, 1 = mit, 2 = sprung aus Suche (Eltern aufklappen)
function loadDataFrame(id, ver, seq, withTreeNaviagtion, NrInList)
{
  var pos;

  if (withTreeNaviagtion == 1)
  {
    var nodeIndex = indexOfNode(id, ver, seq, NrInList);
  }
  else
    var nodeIndex = indexOfNode(id, ver, seq);

  if (nodeIndex > - 1)
  {
    var character;
    var pathNameLoc = treeframe.location.pathname;

    // Daten liegen in Unterverzeichnis 'data'
    // Bestimmung des absoluten Pfades für Frame "dataframe"
    if ((withTreeNaviagtion == 0) || (withTreeNaviagtion == 2))
    {
      pos = pathNameLoc.lastIndexOf('/');
      if (pos <= 0)
      {
        pos = pathNameLoc.lastIndexOf('\\');
        character = '\\';
      }
      else
      {
        character = '/';
      }
      if (nodeIndex <= 0)
        nodeIndex = 1;

      // Sonderbehandlung IE: Mischt \ mit / in unerlaubter weise, wenn Katalog
      // per URL, aber nicht per http aufgerufen wird!
      if ((pathNameLoc.substring(0, 1) == '/') && (pathNameLoc.substring(1, 2) == '\\'))
      {
        pathNameLoc = pathNameLoc.substring(1, pathNameLoc.length);
        pos--;
      }

      pathNameLoc = pathNameLoc.substring(0, pos + 1) + 'data/' + treeData[nodeIndex].url;

      // Bei Pocket-PC ist (bei neueren Versionen) http://localhost als Pfad vorhanden
      if ((dataframe.location.href.indexOf("file://localhost") == 0) &&
          (pathNameLoc.indexOf("file://localhost") != 0))
      {
        pathNameLoc = "file://localhost" + pathNameLoc;
      }
      // Wenn Ursprung mit file:...-Angabe ist dann auch Zielangabe damit ausstatten
      else if ((dataframe.location.href.indexOf("file:") == 0) &&
          (pathNameLoc.indexOf("file:") != 0))
      {
        pathNameLoc = "file:" + pathNameLoc;
      }
      dataframe.location.href = pathNameLoc;
    }
    else
    {
      dataframe.location.href = treeData[nodeIndex].url;
    }

    // Tree nachziehen?
    if (withTreeNaviagtion == 1)
      activeChildNode.open = 1;

    activeChildNode = treeData[nodeIndex];

    if (withTreeNaviagtion == 2)
    {
      activeChildNode.open = 1;

      var parentNode;
      var parentNodeIndex;

      parentNodeIndex = indexOfNode(activeChildNode.parent,
                                    activeChildNode.parentver,
                                    activeChildNode.parentseq);

      while (parentNodeIndex > 1)
      {
        parentNode = treeData[parentNodeIndex];
        parentNode.open = 1;

        parentNodeIndex = indexOfNode(parentNode.parent,
                                      parentNode.parentver,
                                      parentNode.parentseq);
      }
    }

    // Blank-Seite laden, da Bug PocketPC -> document.open löscht nicht Inhalt
    if (navigator.appName == cPocketPC)
    {
      dodrawTree();
    }
    else
    {
      timeOutId = setTimeout("drawTree()", 100);
      timeOutId = setTimeout("drawTitleframe(1)", 100);
    }
  }
  else
  {
    // Rekursion, da Index nicht gefunden!
    dataframe.location.href = 'recursion-.htm';
  }
}

// opens/closes folder nodes.
function toggleFolder(id, ver, seq, status)
{
  var nodeIndex = indexOfNode(id, ver, seq);

  treeData[nodeIndex].open = status;

  // Blank-Seite laden, da Bug PocketPC -> document.open löscht nicht Inhalt
  if (navigator.appName == cPocketPC)
  {
    dodrawTree();
  }
  else
  {
    timeOutId = setTimeout("drawTree()", 100)
  }
}

function showOverview()
{
  if (activeChildNode)
    dataframe.location.href = activeChildNode.url;
}

function showSearch()
{
  drawTitleframe(0);
  activeChildNode = null;

  if ((dataframe.location.href.indexOf(cCatalogMain) <= 0) &&
      (dataframe.location.href.indexOf(cCatalogPPC) <= 0))
  {
    if (dataframe.location.href.indexOf(cSearch) <= 0)
    {
      if (dataframe.location.href.indexOf(cBasket) <= 0)
        dataframe.location.href = '../' + cSearch;
      else
        dataframe.location.href = cSearch;
    }
    else
      dataframe.location.reload();
  }
  else
    dataframe.location.href = cSearch;
}

function showBasket()
{
  if (this.parent.name != '')
    var dstframe = this.parent;
  else
  {
    var dstframe = dataframe;
    drawTitleframe(0);
    activeChildNode = null;
  }

  if ((dstframe.location.href.indexOf(cCatalogMain) <= 0) &&
      (dstframe.location.href.indexOf(cCatalogPPC) <= 0))
  {
    if (dstframe.location.href.indexOf(cBasket) <= 0)
    {
      if (dstframe.location.href.indexOf(cSearch) <= 0)
        dstframe.location.href = '../' + cBasket;
      else
        dstframe.location.href = cBasket;
    }
    else
      dstframe.location.reload();
  }
  else
    dstframe.location.href = cBasket;
}

function gotoParent()
{
  if (activeChildNode)
  {
    loadDataFrame(activeChildNode.parent,
                  activeChildNode.parentver,
                  activeChildNode.parentseq,
                  0);
  }
}

function scaleArea(areaCoords, scaleFactor)
{
  strTemp = areaCoords;
  pos = strTemp.indexOf(',');
  posLeft = strTemp.substr(0, pos);

  strTemp = strTemp.substr(pos+1, 50);
  pos = strTemp.indexOf(',');
  posTop = strTemp.substr(0, pos);

  strTemp = strTemp.substr(pos+1, 50);
  pos = strTemp.indexOf(',');
  posRight = strTemp.substr(0, pos);

  strTemp = strTemp.substr(pos+1, 50);
  posBottom = strTemp;

  strTemp = Math.round(posLeft * scaleFactor)  + ',' + Math.round(posTop * scaleFactor) + ',' +
            Math.round(posRight * scaleFactor) + ',' + Math.round(posBottom * scaleFactor);

  return strTemp;
}

function ReScale(Value, Factor)
{
  str = Value.substr(0,Value.length-2);
  return str*Factor;
}

function scaleAreaSpan(areaElement, spanElement, Factor)
{
  iLeft = ReScale(spanElement.style.left, Factor);
  iTop = ReScale(spanElement.style.top, Factor);
  iWidth = ReScale(spanElement.style.width, Factor);
  iHeight = ReScale(spanElement.style.height, Factor);

  spanElement.style.left = iLeft + 'px';
  spanElement.style.top = iTop + 'px';
  spanElement.style.width = iWidth + 'px';
  spanElement.style.height = iHeight + 'px';

  iRight = iLeft + iWidth;
  iBottom = iTop + iHeight

  areaElement.coords = iLeft + ',' + iTop + ',' + iRight + ',' + iBottom;
}

function imageScale(scaleFactor)
{
  if (dataframe.imgfrm)
  {
    outputFrame = dataframe.imgfrm.window.document;

    // Je nachdem was groesser (Breite/Hoehe) ist, danach Ziehen, da sonst nicht
    // beide Abmessungen veraendert werden
    if (outputFrame.images[0].width > outputFrame.images[0].height)
      outputFrame.images[0].width = Math.round(outputFrame.images[0].width * scaleFactor);
    else if (outputFrame.images[0].width < outputFrame.images[0].height)
      outputFrame.images[0].height = Math.round(outputFrame.images[0].height * scaleFactor);
    else
    {
      outputFrame.images[0].width = Math.round(outputFrame.images[0].width * scaleFactor);
      outputFrame.images[0].height = Math.round(outputFrame.images[0].height * scaleFactor);
    }

    area = outputFrame.getElementsByTagName("area");
    span = outputFrame.getElementsByTagName("span");

    for (i = 0; i < area.length; i++)
    {
      scaleAreaSpan(area[i], span[i], scaleFactor);
    }
  }
}

// finds the index in the treeData Collection of the node with the given id.
function indexOfNode(id, ver, seq, NrInList)
{
  if (NrInList)
  {
    var currentIndex = 1;
    var iFound = 0;
    var children = extractChildrenOf(activeChildNode.id, activeChildNode.ver, activeChildNode.seq);
    while (currentIndex <= children.length)
    {
      if ((children[currentIndex].id == id) &&
          (children[currentIndex].ver == ver))
      {
        iFound++;

        if (iFound == NrInList)
        {
          currentIndex = indexOfNode(children[currentIndex].id, children[currentIndex].ver, children[currentIndex].seq);
          return currentIndex;
        }
      }
      currentIndex++;
    }
  }
  else
  {
    // von Anfang suchen ...
    var currentIndex = 1;
    while (currentIndex <= treeData.length)
    {
      if ((treeData[currentIndex].id == id) &&
          (treeData[currentIndex].ver == ver) &&
          (treeData[currentIndex].seq == seq))
      {
        return currentIndex;
      }
      currentIndex++;
    }
  }
  return -1;
}

//extracts and returns a Collection containing all of the node's immediate children nodes.
function extractChildrenOf(node, nodeVer, nodeSeq)
{
  var children = new Collection();
  var currentIndex = 1;
  while (currentIndex <= treeData.length)
  {
    if ((treeData[currentIndex].type == 'folder') || (treeData[currentIndex].type == 'link'))
    {
      if ((treeData[currentIndex].parent == node) &&
          (treeData[currentIndex].parentver == nodeVer) &&
          (treeData[currentIndex].parentseq == nodeSeq))
      {
        children.add(treeData[currentIndex])
      }
    }
    currentIndex++;
  }
  return children;
}

function getBrowser()
{
  cPocketPC = "Microsoft Pocket Internet Explorer";
  cIE       = "Microsoft Internet Explorer";
  cNetscape = "Netscape";

  if (navigator.appName == cPocketPC)
  {
    return 2;
  }
  else
  {
    if (navigator.appName == cNetscape)
    {
      bContinue = navigator.userAgent.indexOf("Gecko");

      if (bContinue > -1)
      {
        pos = navigator.userAgent.indexOf("Netscape");
        if (pos > -1)
          return 4;
        else
          return 3;
      }
      else
        return 3;
    }

    if (navigator.appName == cIE)
    {
      pos = navigator.userAgent.indexOf("Opera");
      if (pos != -1)
        return 5;
      else
        return 1;
    }
  }
  return -1;
}

////////////////////////////////////////////////////////
// Ab hier Objekt + Objektmethoden

// Konstruktur - a dynamic storage structure similar to an Array.
function TWebStyle()
{
  return this;
}

// Konstruktur - a dynamic storage structure similar to an Array.
function Collection()
{
  this.length = 0;
  this.add = add;
  return this;
}

// METHOD of Collection - adds an object to a Collection.
function add(object)
{
  this.length++;
  this[this.length] = object;
}

// OBJECT - represents the top-most node of the hierarchial tree.
function RootNode(id, ver, name, url, target, icon)
{
  this.id = id;
  this.ver = ver
  this.seq = 1;
  this.name = name;
  this.url = url;
  this.target = target;
  this.icon = icon;
  this.type = 'root';
  return this;
}

// OBJECT - represents a node which branches to contain other nodes.
function FolderNode(id, ver, seq, parent, parentver, parentseq, name, url, iconClosed, iconOpen)
{
  this.id = id;
  this.ver = ver;
  this.seq = seq;
  this.parent = parent;
  this.parentver = parentver;
  this.parentseq = parentseq;
  this.name = name;
  this.target = '';
  this.url = url;
  this.iconClosed = iconClosed;
  this.iconOpen = iconOpen;
  this.type = 'folder';
  this.open = 0;
  return this
}

// OBJECT - a node that represents a link using a URL.
function LinkNode(id, ver, seq, parent, parentver, parentseq, name, url, target, icon)
{
  this.id = id;
  this.ver = ver;
  this.seq = seq;
  this.parent = parent;
  this.parentver = parentver;
  this.parentseq = parentseq;
  this.name = name;
  this.url = url;
  this.target = target;
  if (icon != "")
    this.icon = icon;
  else
    this.icon = "folder_close.png";
  this.type = 'link';
  return this;
}
