// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// 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/

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

  var tab_info = { };

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// 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) {
        items = [];
        active = false;

        if (tabs = get_tabs(block)) {
          tabs.each(function (tab) {
            tab.addClassName('inactive');

            tab_hash = title_hash(tab.title);
            tab.writeAttribute('hash',tab_hash);

            if (link = tab.readAttribute('href')) {
              a_attr = { 'href': link };
            } else {
              a_attr = { 'onclick': "lift_tab('" + tab_hash + "')" };
            }
            tab_link = B.A(a_attr,tab.title.substr(0,3));
            items.push(B.LI({},tab_link));

            tab_info[tab_hash] = { 'tab': tab, 'link': tab_link };
            if (tab_hash == target) active = tab_hash;
          });
          block_attr = { 'class': 'tab_nav' };
          block.insert({ 'top': B.UL(block_attr,items) });

          if (active) {
            lift_tab(active);
          } else {
            lift_tab(tabs[0].readAttribute('hash'));
          }
        }
      });
    }
  }
  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 (tab_hash) {
    var tab = tab_info[tab_hash].tab;
    var link = tab_info[tab_hash].link;

    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');
    });
    tab.removeClassName('inactive');
    window.location.hash = tab_hash;
  }

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

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

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

