var WakoopaTabs = Class.create({
  initialize: function(menu) {
    // Clicks will be on A's
    Event.observe(menu, 'click', this.switchTab.bindAsEventListener(this));

    // Save the name of the tab we should display
    // Marked by ID
    var firstTab = this.tabNameFromElement($('active'));

    // Present in URL
    if (!firstTab) {
      firstTab = document.location.href.split("#")[1];
    }

    // First visible tab
    if (!firstTab) {
      // Look for first displayed tab and make it active
      $(menu).select('ul li').each(function(li) {
        if (li.visible() && !firstTab) {
          firstTab = li.firstDescendant().href.split('#')[1];
        }
      });
    }

    // Now find the element that matches firstTab and show it
    this.showTab($(this.tabIdFromName(firstTab)).firstDescendant());
  },

  tabNameFromElement: function(ele) {
    if (ele && ele.href) {
      return ele.href.split('#')[1];
    }
    return false;
  },

  tabIdFromName: function(name) {
    return "tab_" + name;
  },

  setActiveId: function(ele) {
    ele.id = 'active';
    $(ele).ancestors()[0].addClassName("active");
  },

  switchTab: function(evt) {
    var ele = Event.element(evt);
    var href = ele.getAttribute('href');
    if (ele && href) {
      this.showTab(ele);
    }
    Event.stop(evt);
  },

  showTab: function(ele) {
    // Hide the current tab
    if(this.activeTab) {
      $(this.activeTab).hide();
      $('active').ancestors()[0].removeClassName("active");
      $('active').id = '';
    }

    // Show the new tab
    this.activeTab = this.tabNameFromElement(ele);
    if($('search_nav')) {
      if(this.activeTab == "software") {
        $('search_nav').show();
      }  else {
        $('search_nav').hide();
      }
    }

    $(this.activeTab).show();
    this.setActiveId(ele);
  }
});
