function $(id) {
  return document.getElementById(id);
}

var gTab = null;

function switchTab(newId) {
  var newTab = $(newId);
  if (!newTab || !newId.match(/^tabs/)) return false;
  if (gTab) {
    var oldTab = $(gTab);
    oldTab.className = 'off';
    $('main-' + gTab.substring(5)).style.display = 'none';
  }
  newTab.className = 'on';
  $('main-' + newId.substring(5)).style.display = '';
  gTab = newId;
  if (gTab == 'tabs-home') {
    document.location.hash = "#";
  } else {
    document.location.hash = gTab;
  }
  // TODO(bolinfest): figure out why scroll happens on Firefox
  setTimeout(scrollToTop, 0);
  return true;
}

function scrollToTop() {
  document.documentElement.scrollTop = 0;
}

function tabListener() {
  if (this.className == 'off') {   
    switchTab(this.id);
  }
}

function addTabListeners() {
  var tabs = $('tabs').getElementsByTagName('TH');
  for (var i = 0; i < tabs.length; ++i) {
    var tab = tabs[i];
    tab.onmousedown = tabListener;
  }
  var useDefault = true;
  var hash = document.location.hash;
  if (hash) {
    // strip the # from the beginning of the hash
    useDefault = !switchTab(hash.substring(1));
  }
  if (useDefault) {
    switchTab('tabs-home');
  }
}

