window.onload = function() {
  var first;
  
  $$('#nav a').each(function(a) {
    first = first || a;
    a.onclick = cnt_navClick;
    var sec = cnt_link2sec(a);
    a._cnt_sec = sec;
    sec._cnt_a = a;
    sec.hide();
  });
  
  $$('h2 a').each(function(a) {
    a.replace(a.innerHTML);
  });
  
  $$('.js-hidden').each(function(e) {
    e.hide();
    e.removeClassName("js-hidden");
  });
  
  var namedLinks = $$('a[name]'); 
  
  $$('#sections a').each(function(a) {
    var name = a.getAttribute("href");
    if(name)
      var indexforhash = name.indexOf("#");
    
    if(name && (indexforhash == 0 || indexforhash == 34)) {
      if(indexforhash == 0)
      	var name = name.substring(1);
      else if(indexforhash == 34)
          var name = name.substring(35);
      a.onclick = cnt_navClick;
      if(a._cnt_sec = $(name)) {
        a.onclick = cnt_navClick;
        throw $continue;
      }
      
      namedLinks.each(function(nl) {
        if(nl.name == name) {
          //alert(name);
          for(var node = nl.parentNode; node; node = node.parentNode) {
            if(node._cnt_a) {
              a._cnt_sec = node;
              a.onclick = cnt_navClick;
              throw $break;
            }
          }
        }
      });
    }
  });
  
  $('sections').show();
  $('nav').show();
  first.onclick();
};

var cnt_navigating = false;

function cnt_link2sec(a) {
   return $(a.href.replace(/.*#/g, ''));
}

function cnt_navClick() {
  if(cnt_navigating) return;

  var thisSec = this._cnt_sec;
  //alert("thisSec:"+thisSec);
  if((!thisSec) || thisSec.visible())
  {
    //alert("returning");
    return;
  }
  
  cnt_navigating = true;
  var thisA = thisSec._cnt_a;
  
  var job = function() { new Effect.Appear(thisSec, { duration: .5, afterFinish: function() { cnt_navigating = false; thisSec.show(); } }); };
  
  $$('#nav a').each(function(a) {
    var sec = a._cnt_sec;
    a.removeClassName("active");
    if(sec.visible() && sec != thisSec) {
      new Effect.Fade(sec, { duration: .5, afterFinish: job });
      
      job = null;
    }
  });
  if(job) job();
  thisA.addClassName("active");
  return thisA != this;
 
}

