// controls the hiding/showing of listings via the DOM

// toggles the display of locations based on clicked elt (should be 'a')
function toggle_locations(elt) {
  var pelt  = elt.parentNode;                   // li
  var gpelt = (pelt) ? pelt.parentNode : null;  // ul
  // recursively hide all of the unordered lists at the same level
  uls = gpelt.getElementsByTagName('ul');
  var temp;
  // hide all ul children
  for (var i = 0; i < uls.length; i++) {
    uls[i].style.display = 'none';
  }
  // deselect all list elements
  lis = gpelt.getElementsByTagName('li');
  for (var i = 0; i < lis.length; i++) {
    lis[i].className = lis[i].className.replace('sel', '');
  }
  // show relevant listing
  var show_ul = elt.nextSibling;
  show_ul = find_sib(show_ul, 'ul');
  smart_show(show_ul);
  // select element
  pelt.className += ' sel';
}

// decide which depth to show based on elt (should be ul)
function smart_show(elt) {
  elt.style.display = '';
  // for all of the list element children...
  lis = getChildrenByTagName(elt, 'li');
  if (!lis) return;
  if (lis.length == 1) {
    lis[0].className += ' sel';
    var ul = getChildrenByTagName(lis[0], 'ul')
    if (ul[0]) smart_show(ul[0]);
  }
}

// hide appropriate locations
function auto_hide() {
  uls = document.getElementsByTagName('ul');
  if (uls) {
    for (var i = 0; i < uls.length; i++) {
      if (uls[i].className == 'county') {
        toggle_locations(uls[i].getElementsByTagName('a')[0]);
      }
    }
  }
}

function getChildrenByTagName(elt, tag) {
  var cs = elt.childNodes;
  var o  = new Array;
  for (var i = 0; i < cs.length; i++) {
    if ((cs[i].tagName == tag.toUpperCase()) | (cs[i].tagName == tag.toLowerCase()))
      o.push(cs[i]);
  }
  return o;
}

function find_sib(elt, tag) {
  var fn = 'find_sib';
  var o = elt.nextSibling
  if (!o) return null;
  if (o.nodeType != 1) {
    // not an elemen node - keep moving
    return find_sib(o, tag);
  } else if (tag) {
    if ((o.tagName != tag.toUpperCase()) & (o.tagName != tag.toLowerCase())) {
      return find_sib(o, tag);
    } else {
      return o;
    }
  }
  return o; 
}