var selectedTab;
var mouseInPopupMenuItem;
var SelectedButton;
//var cachedImageIndex;
//var cachedImageArray = new Array(100);

var panelHeight;
var finalHeight;
var menuDropDown;
var imgPopupPanel;
var _pathAdjust;
var lastWidth;
var lastHeight;

function AdjustPath(url)
{
  if (_pathAdjust == ".") {
    return url;
  } else {
    return _pathAdjust + "/" + url;
  }
}

function InitWebSiteEngine(selectedTabParam, pathAdjust) {
  var text;
  var i;
  var j;
  var targetText;
  var targetMainText;
  var targetSubText;

  _pathAdjust = pathAdjust;

  if (selectedTabParam != 0) {
    selectedTab = selectedTabParam;
  } else {
    text = String(document.location);
    i = text.indexOf('?');

    if (i > 0) {
      targetText = text.substring(i + 1);
      j = targetText.indexOf('.');
      if (j <= 0) {
        targetMainText = targetText;
        targetSubText = '';
      } else {
        targetMainText = targetText.substring(1, j - 1);
        targetSubText = targetText.substring(j + 1);
      }
      targetText = text.substring(i + 1);
      selectedTab = parseInt(targetText);
    } else {
      selectedTab = 1;
    }
  }

  mouseInPopupMenuItem = false;

  window.onerror = null;
  sNavigatorAppName = navigator.appName;
  iNavigatorVersion = parseInt(navigator.appVersion);

  bCanUseImages = false;
  if (sNavigatorAppName == "Netscape" && iNavigatorVersion >= 3) bCanUseImages = true;
  if (sNavigatorAppName == "Microsoft Internet Explorer" && iNavigatorVersion >= 4) bCanUseImages = true;
}

function ClearImageCache()
{
  // do nothing at this stage- may need to implement array of images
  // later, in which case this will need to be initialized here.
}

function CacheImage(sImageName)
{
// This code doesn't appear to work- replaced with CSS solution instead
/*
//  alert('caching: ' + sImageName);
  var img;

  img = new Image();
  try
  {
    img.src = sImageName;
    cachedImageArray[cachedImageIndex] = img;
    if (cachedImageIndex >= 99)
    {
      // start again- don't allow more than 100 images to be cached
      cachedImageIndex = 0;
      cachedImageIndex++;
    }
  }
  catch(e)
  {
    alert('exception caching image ' + sImageName + ': ' + e);
  }
*/
}

function GetButtonImageName(iButtonIndex, sButtonState)
{
// name format: menubar_button<n>[_{down|over}]
  if (iButtonIndex == SelectedButton) {
    // override button state - we know it should be down!!
    sButtonState = "down";
  }
  if (sButtonState == "") {
    return AdjustPath("images/menubar_button" + (iButtonIndex+1) + ".png");
  } else {
    return AdjustPath("images/menubar_button" + (iButtonIndex+1) + "_"
                      + sButtonState + ".png");
  }
}

function GetSepImageName(iButtonIndex, bIsRightSeparator,
                         sLeftButtonState, sButtonState, sRightButtonState)
{
// name format: menubar_sep<n>[_l{down|over}][_r{down|over}]
  var sAppendText;
  var sLeftState;
  var sRightState;
  var iSepIndex;
  if (bIsRightSeparator) {
    sLeftState = sButtonState;
    sRightState = sRightButtonState;
    iSepIndex = iButtonIndex + 1;
    if (SelectedButton != -1) {
      if (iButtonIndex == SelectedButton) {
        // override button state - we know it should be down!!
        sLeftState = "down";
      }
      if (iButtonIndex + 1 == SelectedButton) {
        // override button state - we know that the button to the right is down!
        sRightState = "down";
      }
    }
  } else {
    sLeftState = sLeftButtonState;
    sRightState = sButtonState;
    iSepIndex = iButtonIndex;
    if (SelectedButton != -1) {
      if (iButtonIndex == SelectedButton) {
        // override button state - we know it should be down!!
        sRightState = "down";
      }
      if (iButtonIndex - 1 == SelectedButton) {
        // override button state - we know that the button to the left is down!
        sLeftState = "down";
      }
    }
  }
  sAppendText = "";
  if (sLeftState != "") {
    sAppendText = "_l" + sLeftState;
  }
  if (sRightState != "") {
    sAppendText = sAppendText + "_r" + sRightState;
  }
  return AdjustPath("images/menubar_sep" + (iSepIndex+1) + sAppendText + ".png");
}

function HighlightButton(idx)
{
  var oBtn;
  if (bCanUseImages) {
    if (idx >= 0) {
      if (document.images) {
        oBtn = xGetElementById("Button" + idx);
        oBtn.src = GetButtonImageName(idx, "over");
        oSepLeft = xGetElementById("Sep" + idx);
        oSepLeft.src = GetSepImageName(idx, false, "", "over", "");
        oSepRight = xGetElementById("Sep" + (idx + 1));
        oSepRight.src = GetSepImageName(idx, true, "", "over", "");
      }
    }
  }
}

function NormalButton(idx)
{
  var oBtn;
  if (idx >= 0) {
    if (document.images) {
      oBtn = xGetElementById("Button" + idx);
      oBtn.src = GetButtonImageName(idx, "");
      oSepLeft = xGetElementById("Sep" + idx);
      oSepLeft.src = GetSepImageName(idx, false, "", "", "");
      oSepRight = xGetElementById("Sep" + (idx + 1));
      oSepRight.src = GetSepImageName(idx, true, "", "", "");
    }
  }
}

function GetButtonBottomYPos()
{
  return 71;
}

function GetButtonLeftXPos(idx)
{
  var oBtn;
  oBtn = xGetElementById("Sep" + idx);
  return oBtn.offsetLeft;
}

function MoveToNewPane(URL) {
  parent.frames[1].location = URL
}

function DropDownMenu(idx)
{
  SelectButton(idx);
  ShowPopup(idx);
}

function SelectButton(idx)
{
  var oldButton;
  var oBtn;
  if (bCanUseImages) {
    if (idx >= 0) {
      if (idx != SelectedButton) {
        oldButton = SelectedButton;
        SelectedButton = -1;
        NormalButton(oldButton);
        oBtn = xGetElementById("Button" + idx);
        oBtn.src = GetButtonImageName(idx, "down");
        oSepLeft = xGetElementById("Sep" + idx);
        oSepLeft.src = GetSepImageName(idx, false, "", "down", "");
        oSepRight = xGetElementById("Sep" + (idx + 1));
        oSepRight.src = GetSepImageName(idx, true, "", "down", "");
        SelectedButton = idx;
      }
    }
  }
}

function AnimatePopup()
{
  var height;
  var htmlText;
  var eventText;
  var graphicTop;

  menuDropDown = xGetElementById("menuDropDown");
  height = xHeight("menuDropDown") + 10;

  xHeight("menuDropDown", height);

  imgPopupPanel = xGetElementById("imgPopupPanel");
  panelHeight += 10;
  if (panelHeight < finalHeight) {
    xHeight("imgPopupPanel", panelHeight);
    setTimeout("AnimatePopup()", 20);
  } else {
    xHeight("imgPopupPanel", finalHeight);
    menuDropDown = xGetElementById("menuDropDown");

    htmlText = "";
    if (kbSupportsTransparentPNGs()) {
      graphicTop = AdjustPath("images/popup_line_top.png");
      graphicBottom = AdjustPath("images/popup_line_bottom.png");
    } else {
      graphicTop = AdjustPath("images/popup_line_top_IE.gif");
      graphicBottom = AdjustPath("images/popup_line_bottom.png");
    }

    htmlText = "<div><img style=\"display: block; margin: 0; border: 0; padding: 0;\" id='imgPopupTopLine' src='" + graphicTop + "' width='150' height='6' />";

    for (i = 1; i <= 5; i++) {
      itemName = "imgPopupItem" + i;
      eventText = "onMouseMove='HandlePopupMenuItemEnter(\"" + itemName + "\");' "
                  + "onMouseOut='HandlePopupMenuItemExit(\"" + itemName + "\");' "
                  + "onMouseDown='HandlePopupMenuItemSelect(\"" + itemName + "\"); return false;'";
      htmlText += "<img style=\"display: block; margin: 0; border: 0; padding: 0;\" id='" + itemName
                  + "' src='" + AdjustPath("images/popup_item_products_n" + i + ".png")
                                  + "' width='150' height='17' "
                  + eventText + " />";
//      htmlText += "<br />"
    }
    htmlText += "<img style=\"display: block; margin: 0; border: 0; padding: 0;\" id='imgPopupBottomSpacer' src='"
                       + AdjustPath("images/popup_item_products_spacer.png")
                       + "' width='150' height='6' />"
    htmlText += "<img style=\"display: block; margin: 0; border: 0; padding: 0;\" id='imgPopupBottomLine' src='"
                       + AdjustPath("images/popup_line_bottom.png")
                       + "' width='150' height='3' /></div>";
    menuDropDown.innerHTML = htmlText;
  }
}

function HidePopup()
{
  menuDropDown = xGetElementById("menuDropDown");
  menuDropDown.innerHTML = "";
}

function GoToNewPage(idx, subidx) {
  if (idx == 0) {
    document.location = AdjustPath("index.html");
  }
  if (idx == 1) {
    if (subidx == 0) {
      document.location = AdjustPath("sqlmatcher/index_pro.html");
    }
    if (subidx == 1) {
      document.location = AdjustPath("sqlmatcher/index_std.html");
    }
    if (subidx == 2) {
      document.location = AdjustPath("all_products.html");
    }
    if (subidx == 3) {
      document.location = AdjustPath("all_downloads.html");
    }
    if (subidx == 4) {
      document.location = AdjustPath("legacy_products.html");
    }
  }
  if (idx == 2) {
    document.location = AdjustPath("all_news.html");
  }
  if (idx == 3) {
    document.location = AdjustPath("all_articles.html");
  }
  if (idx == 4) {
    document.location = AdjustPath("support.html");
  }
  if (idx == 5) {
    document.location = AdjustPath("contact.html");
  }
  if (idx == 6) {
    document.location = AdjustPath("search.html");
  }
}

function ShowPopup(idx)
{
  var graphicTop;
  var graphicMiddle;
  var graphicBottom;
  var htmlText;

  if (idx != 1) {
    HidePopup();
    GoToNewPage(idx, 0);
  } else {
    menuDropDown = xGetElementById("menuDropDown");

    if (kbSupportsTransparentPNGs()) {
      graphicTop = AdjustPath("images/popup_line_top.png");
      graphicMiddle = AdjustPath("images/popup_panel_products.png");
      graphicBottom = AdjustPath("images/popup_line_bottom.png");
    } else {
      graphicTop = AdjustPath("images/popup_line_top_IE.gif");
      graphicMiddle = AdjustPath("images/popup_panel_products.png");
      graphicBottom = AdjustPath("images/popup_line_bottom.png");
    }
/*
    htmlText = "<img id='imgPopupTopLine' src='" + graphicTop + "' alt='(popup top line)' /><br />"
          + "<img id='imgPopupPanel' src='" + graphicMiddle + "' height='10' width='150' alt='(popup panel)' /><br />"
          + "<img id='imgPopupBottomLine' src='" + graphicBottom + "' alt='(popup bottom line)' /><br />";
*/
    htmlText = "<div><img style=\"display: block; margin: 0; border: 0; padding: 0;\" id=\"imgPopupTopLine\" src=\"" + graphicTop + "\" />"
          + "<img style=\"display: block; margin: 0; border: 0; padding: 0;\"  id=\"imgPopupPanel\" src=\"" + graphicMiddle + "\" height=\"10\" width=\"150\" />"
          + "<img style=\"display: block; margin: 0; border: 0; padding: 0;\"  id=\"imgPopupBottomLine\" src=\"" + graphicBottom + "\" />"
          + "</div>";
    menuDropDown.innerHTML = htmlText;

    menuDropDown.style.left = GetButtonLeftXPos(idx) + "px";
    menuDropDown.style.top = GetButtonBottomYPos() + "px";

    imgPopupPanel = xGetElementById("imgPopupPanel");
    panelHeight = 10;
    imgPopupPanel.style.height = panelHeight + "px";
    finalHeight = 91;
    setTimeout("AnimatePopup()", 20);
  }
}

function InitPage() {
  // make sure no button "selected" so we get the correct images for the cache.
  SelectedButton = -1;
  cachedImageIndex = 0;

  if (bCanUseImages) {
    ClearImageCache();
    // cache all button images
    for (i=0; i < 7; i++) {
      if (i < 7) {
        CacheImage(GetButtonImageName(i, ""));
        CacheImage(GetButtonImageName(i, "down"));
        CacheImage(GetButtonImageName(i, "over"));
      }
      CacheImage(GetSepImageName(i, false, "", "", ""));
      CacheImage(GetSepImageName(i, false, "down", "", ""));
      CacheImage(GetSepImageName(i, false, "over", "", ""));
      if (i < 7) {
        CacheImage(GetSepImageName(i, false, "", "down", ""));
        CacheImage(GetSepImageName(i, false, "", "over", ""));
        CacheImage(GetSepImageName(i, false, "over", "down", ""));
        CacheImage(GetSepImageName(i, false, "down", "over", ""));
      }
    }
    // cache menu drop-down images
    CacheImage(AdjustPath("images/popup_line_top.png"));
    CacheImage(AdjustPath("images/popup_line_bottom.png"));
    CacheImage(AdjustPath("images/popup_line_top_IE.gif"));
//    CacheImage(AdjustPath("images/popup_line_bottom.png"));
    CacheImage(AdjustPath("images/popup_item_products_spacer.png"));
//    CacheImage(AdjustPath("images/popup_line_bottom.png"));
    for (i=1; i <= 5; i++) {
      if (i <= 5) {
        CacheImage(AdjustPath("images/popup_item_products_n" + i + ".png"));
        CacheImage(AdjustPath("images/popup_item_products_h" + i + ".png"));
      }
    }
  }

  SelectButton(selectedTab - 1);   // select start button
  menuDropDown = xGetElementById("menuDropDown");
  menuDropDown.innerHTML = "";
  menuDropDown.style.position = 'absolute';
/*
  // production print logic
  if (document.location.href.indexOf('?print') != -1) {
//    HideNonPrintPageElements();
    SendPageToPrinter();
    ClosePage();
  }

  // debug print logic
  if (document.location.href.indexOf('?prtdebug') != -1) {
//    HideNonPrintPageElements();
  }

//  ShowPopup(0);
*/
  HidePopup();
  return true;
}

function InitPrintPage() {
  // production print logic
  if (document.location.href.indexOf('?print') != -1) {
//    HideNonPrintPageElements();
    SendPageToPrinter();
    ClosePage();
  }

  // debug print logic
  if (document.location.href.indexOf('?prtdebug') != -1) {
//    HideNonPrintPageElements();
  }

  return true;
}

function SetupResizeListeners()
{
  xAddEventListener(window, 'resize', winOnResize, false);
  xAddEventListener(window, 'scroll', winOnScroll, false);
//  alert('test');
}

/*
function winOnLoad()
{
  winOnResize(); // set initial position
  xAddEventListener(window, 'resize', winOnResize, false);
  xAddEventListener(window, 'scroll', winOnScroll, false);
}
*/

function HandlePopupVisibility()
{
  // Check to see if user has mouse cursor over pop-up menu or not.
  // If mouse is not hovering over pop-up then hide it.
  if (!mouseInPopupMenuItem) {
    HidePopup();
  }
}

function WaitAndCheckPopupVis()
{
  setTimeout("HandlePopupVisibility()", 500);
}

function MenuItemNameToIndex(name)
{
  for (i = 1; i <= 5; i++)
  {
    if (name == "imgPopupItem" + i)
    {
      return i;
    }
  }
  return -1;
}

function GetMenuItemImageName(idx, highlight)
{
  var highlightText;
  if (highlight) {
    highlightText = "h";
  } else {
    highlightText = "n";
  }
  return AdjustPath("images/popup_item_products_" + highlightText + idx + ".png");
}

function HandlePopupMenuItemEnter(itemName)
{
  mouseInPopupMenuItem = true;
  if (itemName != "") {
    menuItemImage = xGetElementById(itemName);
    menuItemImage.src = GetMenuItemImageName(MenuItemNameToIndex(itemName),
                                             true);
  }
}

function HandlePopupMenuItemExit(itemName)
{
  mouseInPopupMenuItem = false;
  if (itemName != "") {
    menuItemImage = xGetElementById(itemName);
    menuItemImage.src = GetMenuItemImageName(MenuItemNameToIndex(itemName),
                                             false);
  }
  WaitAndCheckPopupVis();
}

function HandlePopupMenuItemSelect(itemName)
{
  GoToNewPage(1, MenuItemNameToIndex(itemName) - 1);
}

var childWindow = null;

function PrintWinOpen_Base(sUrl, bDebug)
{
  var sFlags;
  var sWindowName;
  if (bDebug)
  {
    sFlags = "menubar=yes,resizable=yes,scrollbars=yes,toolbar=yes";
    sWindowName = "DebugPrintWindow";
  }
  else
  {
    sFlags = "menubar=no,resizable=yes,scrollbars=yes,toolbar=no";
    sWindowName = "PrintWindow";
  }
  if (childWindow && !childWindow.closed)
  {
    childWindow.location.href  = sUrl;
  }
  else
  {
    try
    {
      childWindow = window.open(sUrl, sWindowName, sFlags);
    }
    catch (e)
    {
      alert("javascript error occurred while trying to open window: "
        + e.message);
    }
  }
  if (childWindow == null || typeof(childWindow) == "undefined")
  {
    alert("Failed to open print window.  If you have a pop-up blocker "
          + "installed, please enable pop-ups for this site or you won't be "
          + "able to print.");
  }
  else
  {
    childWindow.focus();
  }
  return false;
}

function PrintWinOpen(sUrl) {
  return PrintWinOpen_Base(sUrl, false);
}

function PrintWinOpenDebug(sUrl) {
  return PrintWinOpen_Base(sUrl, true);
}

function xGetEltByIDOnChildPage(e) {
  if(typeof(e)!='string') return e;
  if(childWindow.document.getElementById) e=childWindow.document.getElementById(e);
  else if(childWindow.document.all) e=childWindow.document.all[e];
  else e=null;
  return e;
}

function HideLayer(layerName)
{
  var tempLayer;

  tempLayer = xGetElementById(layerName);
  tempLayer.style.visibility = "hidden";
  tempLayer.style.height = "0px";
}

function ClearAbsolutePositioning(layerName)
{
  var tempLayer;

  tempLayer = xGetElementById(layerName);
  tempLayer.style.position = "relative";
}

function HideNonPrintPageElements()
{
  var tempLayer;
  tempLayer = xGetElementById("contentPix");
  tempLayer.style.cssFloat = "none";
/*
  tempLayer.style.backgroundColor = "black";
  tempLayer.style.width = 5;
  tempLayer.style.height = 5;
*/
/*
  var tempImg;
  tempImg = xGetElementById("contentPixImage");
  tempImg.src = "";
  tempImg.style.width = 0;
  tempImg.style.height = 0;
  tempImg = xGetElementById("contentPixPrintImg");
  tempImg.src = "";
  tempImg.style.width = 0;
  tempImg.style.height = 0;
*/
  HideLayer("header");
  HideLayer("menuBar");
  HideLayer("topSeparator");
  HideLayer("menuDropDown");
  HideLayer("contentPix");
  HideLayer("bottomSeparator");
  HideLayer("footer");
  tempLayer = xGetElementById("seeAlso");
  tempLayer.style.height = 0;
  HideLayer("seeAlso");

  // one final step, reposition content layer at 0,0 pos
  tempLayer = xGetElementById("contentAll");
  tempLayer.style.background = "";

  ClearAbsolutePositioning("contentText");
  tempLayer = xGetElementById("contentText");
//  tempLayer.style.position = "absolute";
  tempLayer.style.top = 0;
  tempLayer.style.left = 0;
  tempLayer.style.position = "relative";
  tempLayer.style.marginLeft = 5;
  tempLayer.style.marginRight = 5;
  tempLayer.style.paddingRight = 10;
  tempLayer.style.paddingLeft = 10;
}

function SendPageToPrinter()
{
  var browserVersion;
  browserVersion = parseInt(navigator.appVersion)
  if (browserVersion >= 4) window.print();
}

function ClosePage()
{
  var parentwin;

  parentwin = window.self;           // Make handle for current window named "parentwin"
  parentwin.opener = window.self;    // Tell current window that it opened itself
  parentwin.close();                 // Close window's parent (e.g. the current window)
}

function ExtractFileName(url)
{
  var idx = url.lastIndexOf('/');
  if (idx >= 0)
  {
    // char found, return everything after the / char
    return url.substring(idx + 1);
  }
  else
  {
    // char not found- return whole url (assume file ref)
    return url;
  }
}

function ExtractFilePath(url)
{
  var idx = url.lastIndexOf('/');
  if (idx >= 0)
  {
    // char found, return everything before and including the / char
    return url.substring(0, idx + 1);
  }
  else
  {
    // char not found- return nothing (assume was file ref!)
    return "";
  }
}

function PrintPage(printPageURL)
{
  // open same URL in new window, but hide all the unnecessary divs

  var printUrl;
  printUrl = ExtractFilePath(printPageURL) + 'PRT-'
    + ExtractFileName(printPageURL);
  // production code:
  PrintWinOpenDebug(printUrl + '?print');
  // for debugging:
//  PrintWinOpenDebug(printUrl + '?prtdebug');
}

function StoreFormDimensions()
{
  lastWidth = xClientWidth();
  lastHeight = xClientHeight();
}

function winOnResize() {
  xWidth('bottomFloatMenu', xClientWidth());
  winOnScroll(); // initial slide
}

function winOnScroll() {
  var y = xScrollTop();

  y += xClientHeight() - xHeight('bottomFloatMenu');

  xSlideTo('bottomFloatMenu', 0, y, 0);
}

function RepositionBottomBar2()
{
  xHeight('contentPix', xHeight('contentText'));
//  xWidth('footer', xClientWidth());
  otherDivHeight = xHeight('header') + xHeight('menuBar')
                   + xHeight('topSeparator') + xHeight('menuDropDown');
  footerDivHeight = xHeight('bottomSeparator') + xHeight('footer');
  clientHeight = xClientHeight();
  newHeight = clientHeight /*- footerDivHeight*/ - otherDivHeight; // - 95;
//  alert('1:' + xHeight('header') + ' 2:' + xHeight('menuBar') + ' 3: ' + xHeight('topSeparator') + ' 4:' + xHeight('menuDropDown'));
//  alert('5:' + xClientHeight());
  if (xHeight('contentText') < newHeight)
  {
    xHeight('contentText', newHeight);
  }
}

function RepositionBottomBar()
{
  // resize contentText to make sure it covers at least the screen height
  clientHeight = xClientHeight();
  newHeight = xClientHeight();
  if (xHeight('contentText') < newHeight)
  {
    xHeight('contentText', newHeight);
  }
  // set up bottom bar position
  winOnResize();
}

