// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// tabbed.js
//
// by drow@ipHouse.com
// licensed under a Creative Commons Attribution-Share Alike 3.0 License
// http://creativecommons.org/licenses/by-sa/3.0/
//
// uses Prototype
// http://www.prototypejs.org/
//
// version 1.0  2010-02-03 initial release
// version 1.1  added support for nested tab blocks

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// global data

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// init tabs

  function init_tabs () {
    if (window.location.hash) {
      target = window.location.hash;
    } else {
      target = '';
    }
    if (blocks = $$('div.tab_block')) {
      var B = {}; Builder.dump(B);

      blocks.each(function (block) {
        block_attr = { 'class': 'tab_nav' };
        items = [];
        active = false; active_id = false;

        if (tabs = get_tabs(block)) {
          tabs.each(function (tab) {
            tbd_id = tab.identify();
            tbd_hash = title_hash(tab.title);

            if (link = tab.readAttribute('href')) {
              a_attr = { 'href': link };
            } else {
              a_attr = { 'onclick': "lift_tab(this,'" + tbd_id + "')" };
            }
            tab_link = B.A(a_attr,tab.title);
            items.push(B.LI({},tab_link));
            tab.addClassName('inactive');

            if (tbd_hash == target) {
              active = tab_link; active_id = tbd_id;
            }
          });
          block.insert({ 'top': B.UL(block_attr,items) });

          if (active) {
            lift_tab(active,active_id);
          } else {
            lift_tab(block.down('ul').down('a'),tabs[0].identify());
          }
        }
      });
    }
  }
  function get_tabs (block) {
    return select_children(block,'div.tab');
  }
  function select_children (parent,desc) {
    return parent.childElements().grep(new Selector(desc));
  }
  function title_hash (string) {
    return '#' + string.replace(/\s+/g,'_').underscore();
  }

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// lift tab

  function lift_tab (link,tbd_id) {
    link.up('ul').select('a').each(function (a) {
      a.removeClassName('active');
    });
    link.addClassName('active');

    get_tabs(link.up('div')).each(function (d) {
      d.addClassName('inactive');
    });
    $(tbd_id).removeClassName('inactive');
    window.location.hash = title_hash($(tbd_id).title);
  }

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// showtime

  document.observe('dom:loaded',init_tabs);

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

