Event.observe(window, 'load', buildIndex, false);

function buildIndex(e) {
  // Get content headings
  var contentDiv = $('content-a');
  var heads = contentDiv.getElementsByTagName('h3');
  if (heads.length < 2) return;

  // Build list
  var list = document.createElement('select');
  list.id = 'indexList';
  for (var i1=0; i1<heads.length; i1++) {
    heads[i1].parentNode.id = 'index' + i1;
    heads[i1].parentNode.className = heads[i1].parentNode.className + ' section globalhide';
    var text = document.createTextNode(heads[i1].textContent?heads[i1].textContent:heads[i1].innerText);
    var option = document.createElement('option');
    option.appendChild(text);
    option.value = 'index' + i1;
    list.appendChild(option);
  }

  // Add list
  var indexDiv = $('on-this-page');
  indexDiv.appendChild(list);
  
  if (heads.length > 1) {
    var temp = indexDiv.className.replace(/(\s|^)globalhide(\s|$)/, ' ');
    indexDiv.className = temp;
  }
  
  // Add listener to dropdown
  var dropdown = $('indexList');
  Event.observe(dropdown, 'change', showSection, false);
  
  // Check for an anchor in the URL and switch to the corresponding section
  var hash = window.document.location.hash;
  var aSection;
  if (hash != '' && hash != '#') {
    aSection = $(hash.substr(1)).up('div.section');
    dropdown.down(parseInt(aSection.id.substr(5))).selected = true;
    $(hash.substr(1)).scrollTo();
  }
  else {
    aSection = $('index0');
  }
  aSection.removeClassName('globalhide');
}

function showSection(e) {
  var dropdown = Event.element(e);
  var curIndexId = dropdown.value;
  
  // Get section divs
  var contentDiv = $('content-a');
  var sections = contentDiv.getElementsByClassName('section');
  
  for (var i2=0; i2<sections.length; i2++) {
    if (sections[i2].id == curIndexId) {
      sections[i2].className = sections[i2].className.replace(/(\s|^)globalhide(\s|$)/, ' ');
    }
    else if (sections[i2].className.search(/(\s|^)globalhide(\s|$)/) == -1) {
      sections[i2].className = sections[i2].className + ' globalhide';
    }
  }
}
