window.addEvent('domready', function() {
  smooth1 = new smoothtabs('tab1');
  smooth2 = new smoothtabs('tab2');
});


var smoothtabs = new Class({

  div_height : Array(),
  orig_div : Array(),
  
  initialize: function(idName) {
    this.idName = (idName) ? idName : 'tabs'
    // data divs
    dd = $$('[class^="'+this.idName+'-data"]');

    // display our content divs so we can get the height
    for (i=1; i<dd.length; i++) {
      dd[i].setStyle('display', 'block');
    }

    tabs = $$('#'+this.idName+'_menu li');
    
    // get the height of each one of our content divs
    tabs.each(function(tab) {
      var base_name = tab.id.replace(/-current/, '');
      this.div_height[base_name] = $(base_name + '-data').scrollHeight;
      this.orig_div[base_name] = $(base_name + '-data').cloneNode(true);
    }.bind(this));

    // now that we know the height, hide the divs
    for (i=1; i<dd.length; i++) {
      dd[i].setStyle('display', 'none');
      dd[i].setOpacity(0);
    }
    
    tabs.each(function(tab) {
       tab.addEvent('click', this.select_tab.pass(tab.id, this));
    }.bind(this));

  },

  select_tab: function(tab_id) {
    var idName = this.idName
    tab_id = tab_id.replace(/-current/,'');
    slide = $(idName+'_content').effect('height', {duration: 0, wait:false, transition: Fx.Transitions.linear});

    var cur_data = $E('[class="'+idName+'-data-current"]');
    var sel_data = $(tab_id + '-data');

    if ( cur_data.id == sel_data.id ) { return; }

    var cur_base = cur_data.id.substr(0, cur_data.id.indexOf('-data'));
    var sel_base = tab_id;

    var height = this.div_height[sel_base];
    var orig = this.orig_div[sel_base];
    
    orig.setStyle('display', 'block');
    
    $(cur_base + '-current').id = cur_base;
    $(tab_id).id = tab_id + '-current';

    // out with the old, in with the new
    new Fx.Style(cur_data, 'opacity').start(0.0).chain(function () {

      slide.start(parseInt(height)).chain(function () {

        cur_data.setStyle('display', 'none');
                
        orig.setStyles({
                         display: 'block'/*,
                         comment out height adjustment - fixed height
                         height: height + 'px'*/
                       });                          

        sel_data.setOpacity(0);

        new Fx.Style(sel_data, 'opacity').start(1.0).chain(function () {
          orig.className = idName+'-data-current';
          cur_data.className = idName+'-data';

          sel_data.replaceWith(orig);       
        })
      })
    });
  }

});

