$.fn.tabControl = function() {
  return this.each(function() {
    var elem        = $(this),
        initial_tab = elem.attr('active') || 1,
        contents    = elem.find('.tab_content').hide(),
        buttons     = elem.children('ul').children('li');

    // Setup buttons and event listeners
    buttons.each(initializeTab).hover(onMouseOver, onMouseOut).click(onTabClick);
    parseQueryString();

    return this;

    function initializeTab(index) {
      var button = $(this);

      // Set associated content divs
      button.data('content', $(contents[index]));
      $(contents[index]).data('tab', button);

      // button size metadata
      button.addClass(button.children('span').height() >= 24 ? "double" : "single");
    }

    function onMouseOver() {
      $(this).addClass('hover');;
    }

    function onMouseOut() {
      $(this).removeClass('hover');
    }

    function onTabClick() {
      var clicked_tab     = $(this).addClass('active'),
          active          = contents.filter(":visible").hide(),
          div_to_be_shown = clicked_tab.data('content').show();

      // change the body class to allow dynamic positioning (height) of its background
      // image, which is the swoosh dividing graphic above footer
      $('body').removeClass();
      $('body').addClass($(this).attr("id"));

      if (active.length > 0 && clicked_tab.get(0) != active.data('tab').get(0)) {
        active.data('tab').removeClass('active');
      }
    }

    // Allow ?tab=X to set the starting tab
    function parseQueryString() {
      if (window.location.href.indexOf('?') > 0) {
        $.each(window.location.href.split('?')[1].split('&'), function(index) {
          var key = this.split('=')[0], value = this.split('=')[1];
          if (key == 'tab' && value <= buttons.length)
            initial_tab = value; return false;
        });
      }

      buttons.eq(initial_tab-1).click();
    }
  });
};

$(document).ready(function() {
  $('#tabs').tabControl();
});