var selects_disabled = false;

//----------------------------------------------------------------------------
// Code to determine the browser and version.
//----------------------------------------------------------------------------

function Browser() {

  var ua, s, i;

  this.isIE    = false;  // Internet Explorer
  this.isOP    = false;  // Opera
  this.isNS    = false;  // Netscape
  this.isSAFARI = false;  // Safari
  this.version = null;

  ua = navigator.userAgent;

  s = "Safari";
  if ((i = ua.indexOf(s)) >= 0 ) {
    this.isSAFARI = true;
  }

  s = "Opera";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isOP = true;
    this.version = parseFloat(ua.substr(i + s.length));
    if (isNaN(this.version)) {
      // opera 9, at least, uses Opera/9 as the string
      this.version = parseFloat(ua.substr(i + s.length + 1));
    }
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as Netscape 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }

  s = "MSIE";
  if ((i = ua.indexOf(s))) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }
}

var browser = new Browser();

function exists(obj)
{
  if (!obj) {
    return false;
  }
  if (typeof(obj)=="unknown") {
    return false;
  }
  if (typeof(obj)=="undefined") {
    return false;
  }
  return true;
}

function kill_event(oEvent)
{
  if (exists(oEvent)) {
    if (exists(oEvent.return_value)) {
      oEvent.return_value=false;
    }
    if (exists(oEvent.cancelBubble)) {
      oEvent.cancelBubble=true;
    }
    if (exists(oEvent.stopPropogation)) {
      oEvent.stopPropagation();
    }
    if (exists(oEvent.preventDefault)) {
      oEvent.preventDefault();
    }
  }
}

// front ends for measuring various attributes under different browsers

function browserWindowLeft()
{
  return window.screenLeft ||
         window.screenX ||
         0;
}

function browserWindowTop()
{
  return window.screenTop ||
         window.screenY ||
         0;
}

function browserWindowWidth()
{
  return window.innerWidth ||
         document.documentElement.clientWidth ||
         document.body.clientWidth ||
         0;
}

function browserWindowHeight()
{
  return window.innerHeight ||
         document.documentElement.clientHeight ||
         document.body.clientHeight ||
         0;
}

function browserBrowserWidth()
{
  return window.outerWidth ||
         0;
}

function browserBrowserHeight()
{
  return window.outerHeight ||
         0;
}

function browserDocumentWidth()
{
  var pc = document.getElementById('page_container');
  return pc.offsetWidth ||
         window.innerWidth ||
         document.documentElement.scrollWidth ||
         document.body.scrollWidth ||
         0;
}

function browserDocumentHeight()
{
  var pc = document.getElementById('page_container');
  return pc.offsetHeight ||
         window.innerHeight ||
         document.documentElement.scrollHeight ||
         document.body.scrollHeight ||
         0;
}

function browserScrollX()
{
  return document.documentElement.scrollLeft ||
         document.body.scrollLeft ||
         window.pageXOffset ||
         0;
}

function browserScrollY()
{
  return document.documentElement.scrollTop ||
         document.body.scrollTop ||
         window.pageYOffset ||
         0;
}

function browserScreenWidth()
{
  return screen.availWidth ||
         screen.width ||
         0;
}

function browserScreenHeight()
{
  return screen.availHeight ||
         screen.height ||
         0;
}

function browserObjectX(obj)
{
  var x = 0;
  if (obj.offsetParent) {
    while (obj.offsetParent) {
      x += obj.offsetLeft
      obj = obj.offsetParent;
    }
  }
  else if (obj.x)
    x += obj.x;
  return x;
}

function browserObjectY(obj)
{
  var y = 0;
  if (obj.offsetParent) {
    while (obj.offsetParent) {
      y += obj.offsetTop
      obj = obj.offsetParent;
    }
  }
  else if (obj.y)
    y += obj.y;
  return y;
}

function browserStyleSheetMedia(ss)
{
  if (ss.media.mediaText)
    return(ss.media.mediaText)
  if (ss.media)
    return(ss.media)
  return '';
}

function browserCopyToClipboard(value)
{
  if (window.clipboardData) {
    window.clipboardData.setData("Text",value);
  }
}

function browserRowIndex(obj)
{
  if (obj.rindex) {
    return obj.rindex;
  }
  if (obj.rowIndex) {
    return obj.rowIndex;
  }
  return 0;
}

// disable backspace key
document.onkeydown = mykeyhandler;
function mykeyhandler()
{
  if (window.event && window.event.keyCode == 8 && !window.event.srcElement.type) {
    // they clicked backspace off a form element, disable the history back
    window.event.cancelBubble = true;
    window.event.returnValue = false;
    return false;
  }
}

// SECTION: PRINT

function before_printing()
{
//  if (typeof(report_buttons)!="undefined") {
//    report_buttons.style.visibility='hidden';
//  }

  // parse the DOM, switching ON printer-friendly versions of tabs, switching OFF old tabs and images
  if (document.allelements) {
    for (var i=0; i<document.allelements.length; i++) {
      var e = document.allelements[i];
      if (e.getAttribute('sciprint')) {
        if (e.getAttribute('sciprint')=='yes') {
          e.setAttribute('sciprint_saved',e.style.display);
          e.style.display = '';
        } else if (e.getAttribute('sciprint')=='no') {
          e.setAttribute('sciprint_saved',e.style.display);
          e.style.display = 'none';
        }
      }
      if (e.style.getAttribute && e.style.getAttribute('print-font-size')) {
        e.style.setAttribute('screen-font-size',e.style.fontSize);
        e.style.fontSize=e.style.getAttribute('print-font-size');
      }
      // - firefox/safari refuse to add properties on the fly, so I've disabled this for now
      //   but I'm leaving it in case we come up with a way to do this in the future
      // else if (e.style.getPropertyValue && e.style.getPropertyValue('print-font-size')) {
      //   e.style.setPropertyValue('screen-font-size',e.style.fontSize);
      //   e.style.fontSize=e.style.getPropertyValue('print-font-size');
      // }
    }
  }

  // fix textarea bug in IE
  if (document.all) {
    var collTextAreas = document.all.tags("TEXTAREA");
    var oNewDiv;
    var sTemp;
    for (var i = 0; i < collTextAreas.length; i++) {
      oNewDiv = document.createElement("DIV");
      oNewDiv.style.width = collTextAreas(i).clientWidth;
      oNewDiv.style.height = collTextAreas(i).clientHeight;
      oNewDiv.id = collTextAreas(i).uniqueID + "_div";
      // replace all line breaks With HTML line breaks
      sTemp = collTextAreas(i).value.replace(/\n/gi,"<BR>");
      // match 2 spaces With To non-breaking spaces
      sTemp = sTemp.replace(/\s\s/gi,"  ");
      oNewDiv.innerHTML = sTemp;
      collTextAreas(i).parentNode.insertBefore(oNewDiv, collTextAreas(i));
      collTextAreas(i).style.display = "none";
      oNewDiv = null;
    }
  }
}

function after_printing()
{
//  if (typeof(report_buttons)!="undefined") {
//    if (report_generated==true)
//      report_buttons.style.visibility='visible';
//  }

  // parse the DOM, switching OFF printer-friendly versions of tabs, switching ON old tabs and images
  if (document.allelements) {
    for (var i=0; i<document.allelements.length; i++) {
      var e = document.allelements[i];
      if (e.getAttribute('sciprint')) {
        if (e.getAttribute('sciprint')=='yes' || e.getAttribute('sciprint')=='no') {
          e.style.display = e.getAttribute('sciprint_saved');
        }
      }
      if (e.style.getAttribute && e.style.getAttribute('screen-font-size')) {
        e.style.fontSize=e.style.getAttribute('screen-font-size');
      }
      // - firefox/safari refuse to add properties on the fly, so I've disabled this for now
      //   but I'm leaving it in case we come up with a way to do this in the future
      // else if (e.style.getPropertyValue && e.style.getPropertyValue('screen-font-size')) {
      //   e.style.fontSize=e.style.getPropertyValue('screen-font-size');
      // }
    }
  }

  // fix textarea bug in IE
  if (document.all) {
    var collTextAreas = document.all.tags("TEXTAREA");
    var oDivToRemove;
    for (var i = 0; i < collTextAreas.length; i++) {
      oDivToRemove = document.all(collTextAreas(i).uniqueID + "_div");
      if (oDivToRemove != null) {
        oDivToRemove.removeNode(true);
      }
      collTextAreas(i).style.display = "";
    }
  }
}

function browserDisableEnterKey(evt)
{
  evt = (evt) ? evt : ((window.event) ? window.event : "")
  if (evt) {
    // process event here
    // alert(evt.keyCode); // IE and Safari
    // alert(evt.which); // FF
    return !(evt.keyCode==13 || evt.which==13);
  }
}

// initialize Safari/KDE
if (navigator.vendor == "Apple Computer, Inc." || navigator.vendor == "KDE") { // WebCore/KHTML
  function Document() {}
  function Event() {}
  function HTMLCollection() {}
  function HTMLElement() {}
  function Node() {}
  Document.prototype       = window["[[DOMDocument]]"];
  Event.prototype          = window["[[DOMEvent]]"];
  HTMLCollection.prototype = window["[[HTMLCollection.prototype]]"];
  HTMLElement.prototype    = window["[[DOMElement.prototype]]"];
  Node.prototype           = window["[[DOMNode.prototype]]"];
  // not sure if this works or not...
  var HTMLDocument = HTMLElement;
}

if (document.all) {
  // document.all surrogate
  document.allelements = document.all;

  // window.print surrogate
  window.onbeforeprint=before_printing;
  window.onafterprint=after_printing;
} else {
  if (HTMLDocument && HTMLDocument.prototype) {
    // document.all surrogate
    var allGetter = function () {
      var a = this.getElementsByTagName("*");
      var node = this;
      a.tags = function (sTagName) {
        return node.getElementsByTagName(sTagName);
      };
      return a;
    };
    HTMLDocument.prototype.__defineGetter__("allelements", allGetter);
  } else {
    document.allelements=document.getElementsByTagName("*");
  }

  // window.print surrogate
  window.old_print=window.print;
  var mozilla_print = function () {
    before_printing();
    window.old_print();
    // need to wait a second
    setTimeout("after_printing()",1000);
  };
  window.print=mozilla_print;
}

// this code is ours

var menu_delay=500;

var select_list = null;
var iframe_list = null;

if (browser.isIE) {
  if (browser.version<7) {
    var select_list = document.getElementsByTagName('select');
  }
  if (browser.version<6) {
    var iframe_list = document.getElementsByTagName('iframe');
  }
}

function disable_select()
{
  if (!selects_disabled) {
    if (select_list) {
      for (var i = 0; i<select_list.length;i++)
        select_list[i].style.visibility='hidden';
    }
    if (iframe_list) {
      for (var i = 0; i<iframe_list.length;i++)
        iframe_list[i].style.visibility='hidden';
    }
    selects_disabled = true;
  }
}

function enable_select()
{
  if (selects_disabled) {
    if (select_list) {
      for (var i = 0; i<select_list.length;i++)
        select_list[i].style.visibility='visible';
    }
    if (iframe_list) {
      for (var i = 0; i<iframe_list.length;i++)
        iframe_list[i].style.visibility='visible';
    }
    selects_disabled = false;
  }
}

// the actual menu code is from brainjar.com

//*****************************************************************************
// Do not remove this notice.
//
// Copyright 2000-2004 by Mike Hall.
// See http://www.brainjar.com for terms of use.
//*****************************************************************************

// browser code moved to browser.js
//----------------------------------------------------------------------------
// Code for handling the menu bar and active button.
//----------------------------------------------------------------------------

var activeButton = null;

/* [MODIFIED] This code commented out, not needed for activate/deactivate
   on mouseover.

// Capture mouse clicks on the page so any active button can be
// deactivated.

if (browser.isIE)
  document.onmousedown = pageMousedown;
else
  document.addEventListener("mousedown", pageMousedown, true);

function pageMousedown(event) {

  var el;

  // If there is no active button, exit.

  if (activeButton == null)
    return;

  // Find the element that was clicked on.

  if (browser.isIE)
    el = window.event.srcElement;
  else
    el = (event.target.tagName ? event.target : event.target.parentNode);

  // If the active button was clicked on, exit.

  if (el == activeButton)
    return;

  // If the element is not part of a menu, reset and clear the active
  // button.

  if (getContainerWith(el, "DIV", "menu") == null) {
    delayreset=setTimeout("delayResetButton()",menu_delay)
  }
}

[END MODIFIED] */

// [MODIFIED] Reworked resetButton to be on a slight delay

function resetButton(button) {

  // Restore the button's style class.

  removeClassName(button, "menuButtonActive");

  enable_select(); // bmn

  // Hide the button's menu, first closing any sub menus.

  if (button.menu != null) {
    closeSubMenu(button.menu);
    button.menu.style.visibility = "hidden";
  }
}

function clearDelayReset()
{
  if (window.delayreset) {
    clearTimeout(delayreset)
  }
}

function delayResetButton()
{
  resetButton(activeButton);
  activeButton = null;
}

// [END MODIFIED]

function buttonClick(event, menuId) {

  var button;
  var type;

  // Get the target button element.
  // [MODIFIED] clear the reset delay
  clearDelayReset();
  // [END MODIFIED]

  if (browser.isIE) {
    button = window.event.srcElement;
    type = window.event.type;
  } else {
    button = event.currentTarget;
    type = event.type;
  }
  if (hasClassName(button,"menuArrow") && button.parentNode) {
    button = button.parentNode;
  }

  if (type=='click' && button.href && button.href!='#') {
    window.location.href=button.href;
    return;
  }

  // Blur focus from the link to remove that annoying outline.

  button.blur();

  // Associate the named menu to this button if not already done.
  // Additionally, initialize menu display.

  if (button.menu == null) {
    button.menu = document.getElementById(menuId);
    if (button.menu.isInitialized == null)
      menuInit(button.menu);
  }

  // [MODIFIED] Added for activate/deactivate on mouseover.

  // Set mouseout event handler for the button, if not already done.

  if (button.onmouseout == null)
    button.onmouseout = buttonOrMenuMouseout;

  // Exit if this button is the currently active one.

  if (button == activeButton)
    return false;

  // [END MODIFIED]

  // Reset the currently active button, if any.

  if (activeButton != null)
    resetButton(activeButton);

  // Activate this button, unless it was the currently active one.

  if (button != activeButton) {
    depressButton(button);
    activeButton = button;
  }
  else
    activeButton = null;

  disable_select(); // bmn

  return false;
}

function buttonMouseover(event, menuId) {

  var button;

  // [MODIFIED] Added for activate/deactivate on mouseover.
  // [MODIFIED] clear the reset delay
  clearDelayReset();
  // [END MODIFIED]

  // Activates this button's menu if no other is currently active.

  if (activeButton == null) {
    buttonClick(event, menuId);
    return;
  }

  // [END MODIFIED]

  // Find the target button element.

  if (browser.isIE)
    button = window.event.srcElement;
  else
    button = event.currentTarget;

  // If any other button menu is active, make this one active instead.

  if (activeButton != null && activeButton != button)
    buttonClick(event, menuId);
}

function depressButton(button) {

  var x, y;

  // Update the button's style class to make it look like it's
  // depressed.

  button.className += " menuButtonActive";

  // [MODIFIED] Added for activate/deactivate on mouseover.

  // Set mouseout event handler for the button, if not already done.

  if (button.onmouseout == null)
    button.onmouseout = buttonOrMenuMouseout;
  if (button.menu.onmouseout == null)
    button.menu.onmouseout = buttonOrMenuMouseout;

  // [END MODIFIED]

  // Position the associated drop down menu under the button and
  // show it.

  x = getPageOffsetLeft(button);
  y = getPageOffsetTop(button) + button.offsetHeight;

  // For IE, adjust position.

  if (browser.isIE) {
    x += button.offsetParent.clientLeft;
    y += button.offsetParent.clientTop;
  }

  button.menu.style.left = x + "px";
  button.menu.style.top  = y + "px";
  button.menu.style.visibility = "visible";
}

//----------------------------------------------------------------------------
// Code to handle the menus and sub menus.
//----------------------------------------------------------------------------

function menuMouseover(event) {

  var menu;

  // Find the target menu element.
  // [MODIFIED] clear the reset delay
  clearDelayReset();
  // [END MODIFIED]

  if (browser.isIE)
    menu = getContainerWith(window.event.srcElement, "DIV", "menu");
  else
    menu = event.currentTarget;

  // Close any active sub menu.

  if (menu.activeItem != null)
    closeSubMenu(menu);
}

function menuItemMouseover(event, menuId) {

  var item, menu, x, y;

  // Find the target item element and its parent menu element.
  // [MODIFIED] clear the reset delay
  clearDelayReset();
  // [END MODIFIED]

  if (browser.isIE)
    item = getContainerWith(window.event.srcElement, "A", "menuItem");
  else
    item = event.currentTarget;
  menu = getContainerWith(item, "DIV", "menu");

  // Close any active sub menu and mark this one as active.

  if (menu.activeItem != null)
    closeSubMenu(menu);
  menu.activeItem = item;

  disable_select(); // bmn

  // Highlight the item element.

  item.className += " menuItemHighlight";

  // Initialize the sub menu, if not already done.

  if (item.subMenu == null) {
    item.subMenu = document.getElementById(menuId);
    if (item.subMenu.isInitialized == null)
      menuInit(item.subMenu);
  }

  // [MODIFIED] Added for activate/deactivate on mouseover.

  // Set mouseout event handler for the sub menu, if not already done.

  if (item.subMenu.onmouseout == null)
    item.subMenu.onmouseout = buttonOrMenuMouseout;

  // [END MODIFIED]

  // Get position for submenu based on the menu item.

  x = getPageOffsetLeft(item) + item.offsetWidth;
  y = getPageOffsetTop(item);

  // Adjust position to fit in view.

  var maxX, maxY;

  if (browser.isIE) {
    maxX = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft) +
      (document.documentElement.clientWidth != 0 ? document.documentElement.clientWidth : document.body.clientWidth);
    maxY = Math.max(document.documentElement.scrollTop, document.body.scrollTop) +
      (document.documentElement.clientHeight != 0 ? document.documentElement.clientHeight : document.body.clientHeight);
  }
  if (browser.isOP) {
    maxX = document.documentElement.scrollLeft + window.innerWidth;
    maxY = document.documentElement.scrollTop  + window.innerHeight;
  }
  if (browser.isNS) {
    maxX = window.scrollX + window.innerWidth;
    maxY = window.scrollY + window.innerHeight;
  }
  maxX -= item.subMenu.offsetWidth;
  maxY -= item.subMenu.offsetHeight;

  if (x > maxX)
    x = Math.max(0, x - item.offsetWidth - item.subMenu.offsetWidth
      + (menu.offsetWidth - item.offsetWidth));
  y = Math.max(0, Math.min(y, maxY));

  // Position and show the sub menu.

  item.subMenu.style.left = x + "px";
  item.subMenu.style.top  = y + "px";
  item.subMenu.style.visibility = "visible";

  // Stop the event from bubbling.

  if (browser.isIE)
    window.event.cancelBubble = true;
  else
    event.stopPropagation();
}

function closeSubMenu(menu) {

  if (menu == null || menu.activeItem == null)
    return;

  // Recursively close any sub menus.
  // [MODIFIED] clear the reset delay
  clearDelayReset();
  // [END MODIFIED]

  if (menu.activeItem.subMenu != null) {
    closeSubMenu(menu.activeItem.subMenu);
    menu.activeItem.subMenu.style.visibility = "hidden";
    menu.activeItem.subMenu = null;
  }
  removeClassName(menu.activeItem, "menuItemHighlight");
  menu.activeItem = null;
}

// [MODIFIED] Added for activate/deactivate on mouseover. Handler for mouseout
// event on buttons and menus.

function buttonOrMenuMouseout(event) {

  var el;

  // If there is no active button, exit.
  // [MODIFIED] clear the reset delay
  clearDelayReset();
  // [END MODIFIED]

  if (activeButton == null)
    return;

  // Find the element the mouse is moving to.

  if (browser.isIE)
    el = window.event.toElement;
  else {
    if (event.relatedTarget != null)
      el = (event.relatedTarget.tagName ? event.relatedTarget : event.relatedTarget.parentNode);
    if (!el) {
      // we moved "into the void" (probably over an iframe)
      // for now, leave the menu open until they move back off the iframe
      return;
    }
  }

  // If the element is not part of a menu, reset the active button.

  if (getContainerWith(el, "DIV", "menu") == null) {
    delayreset=setTimeout("delayResetButton()",menu_delay)
  }
}

// [END MODIFIED]

//----------------------------------------------------------------------------
// Code to initialize menus.
//----------------------------------------------------------------------------

function menuInit(menu) {

  var itemList, spanList;
  var textEl, arrowEl;
  var itemWidth;
  var w, dw;
  var i, j;

  // Find the width of a menu item.

  itemList = menu.getElementsByTagName("A");
  if (itemList.length > 0)
    itemWidth = itemList[0].offsetWidth;
  else
    return;

  // For items with arrows, add padding to item text to make the
  // arrows flush right.

  for (i = 0; i < itemList.length; i++) {
    spanList = itemList[i].getElementsByTagName("SPAN");
    textEl  = null;
    arrowEl = null;
    for (j = 0; j < spanList.length; j++) {
      if (hasClassName(spanList[j], "menuItemText"))
        textEl = spanList[j];
      if (hasClassName(spanList[j], "menuItemArrow"))
        arrowEl = spanList[j];
    }
    if (textEl != null && arrowEl != null) {
      textEl.style.paddingRight = (itemWidth 
        - (textEl.offsetWidth + arrowEl.offsetWidth)) + "px";
      // For Opera, remove the negative right margin to fix a display bug.
      if (browser.isOP)
        arrowEl.style.marginRight = "0px";
    }
  }

  // Fix IE hover problem by setting an explicit width on first item of
  // the menu.

  if (browser.isIE) {
    w = itemList[0].offsetWidth;
    itemList[0].style.width = w + "px";
    dw = itemList[0].offsetWidth - w;
    w -= dw;
    itemList[0].style.width = w + "px";
  }

  // Mark menu as initialized.

  menu.isInitialized = true;
}

//----------------------------------------------------------------------------
// General utility functions.
//----------------------------------------------------------------------------

function getContainerWith(node, tagName, className) {

  // Starting with the given node, find the nearest containing element
  // with the specified tag name and style class.

  while (node != null) {
    if (node.tagName != null && node.tagName == tagName &&
        hasClassName(node, className))
      return node;
    node = node.parentNode;
  }

  return node;
}

function hasClassName(el, name) {

  var i, list;

  // Return true if the given element currently has the given class
  // name.

  list = el.className.split(" ");
  for (i = 0; i < list.length; i++)
    if (list[i] == name)
      return true;

  return false;
}

function removeClassName(el, name) {

  var i, curList, newList;

  if (el.className == null)
    return;

  // Remove the given class name from the element's className property.

  newList = new Array();
  curList = el.className.split(" ");
  for (i = 0; i < curList.length; i++)
    if (curList[i] != name)
      newList.push(curList[i]);
  el.className = newList.join(" ");
}

function getPageOffsetLeft(el) {

  var x;

  // Return the x coordinate of an element relative to the page.

  x = el.offsetLeft;
  if (el.offsetParent != null)
    x += getPageOffsetLeft(el.offsetParent);

  return x;
}

function getPageOffsetTop(el) {

  var y;

  // Return the x coordinate of an element relative to the page.

  y = el.offsetTop;
  if (el.offsetParent != null)
    y += getPageOffsetTop(el.offsetParent);

  return y;
}

