/************/
/*   INIT   */
/************/
Event.observe(window, "load", pageFirstLoad);

function pageFirstLoad(ev) {
  // Hide all elements with .hidden class
  $$(".hidden").each( function(el){
    el.hide();
  });
  
  // Initialize inputs
  initInputs();
  
  // Show default menu
  showDefaultSubmenu();
  
  // Set active tab
  setActiveTab();
  
  // Event.observe("navigation", "click", showSubNav);
}

/************/
/* FUNCTIONS*/
/************/

// Add hint text to inputs
// Note: This function should be upgraded to use a more compatible event
//       driven approach
function initInputs()
{
	var inputs = document.getElementsByTagName("input");
	for (var i=0; i<inputs.length; i++)
	{
		if (inputs[i].type == "text" && (inputs[i].name == "search"))
		{
			inputs[i].onfocus = function ()
			{
				if (this.value == "search this website")
					this.value = "";
			}
			inputs[i].onblur = function ()
			{
				if (this.value == "" && this.name == "search") this.value = "search this website";
			}
		}
	}
}

// Show the default submenu
function showDefaultSubmenu() {
  var bodyId = document.body.id;
  var expectedId = bodyId + '-subnav';
  var found = false;

  $$(".sub-nav").each( function(el){
    if (!found) {
      if (el.id == expectedId) {
        found = true;
        el.show();
      }
    }
  });
  
  if (!found) {
    menus.each( function(pair){
      if (pair.value.indexOf(bodyId) >= 0) {
        found = true;
        $(pair.key + "-subnav").show();
      }
    });
  }
}

// Show subnavigation if available for link
function showSubNav(ev) {
  var el = ev.element();
  if (el.match("a.nav-link")) {
    var linkId = el.id.gsub("-nav", '');
    var contextId = document.body.id;
    
    // Child accessing parent
    if (menus.get(linkId).indexOf(contextId) >= 0) {
      // Nothing...
    }
    else {
      // Remove active links
      $$("#navigation .nav-link").each( function(el){
        el.removeClassName("active");
      });
      
      // Add active status
      el.addClassName("active");
      
      // Subnav
      var subnav = $(linkId+"-subnav");
      
      // Hide currently visible subnavs
      $$(".sub-nav").each( function(el){
        if (el.visible() && el != subnav) el.hide();
      });
      
      if (subnav) {
        // Show subnav if exists
        subnav.appear();
        
        // Kill event
        Event.stop(ev);
      }
    }
  }
}

// Set the currently active tab in the subnav
function setActiveTab() {
  var el = $$('.sub-nav a[href="'+document.body.id+'"]')[0];
  if (typeof el != 'undefined') el.addClassName('active');
}
