/**
 *
 */
var TabHandler = function(tabIds, defaultTabId) {
  this.tabIds = tabIds;
  this.defaultTabId = defaultTabId;
  this.inEffect = null;
  this.outEffect = null;
  hash = location.hash.substring(1);
  
  if (this.tabIds.length <= 0) return;
  if (this.defaultTabId == "" && hash == "") return;
  
  if (this.tabIds.contains(hash)) {
    this.currentTabId = hash;
  } else {
    this.currentTabId = this.defaultTabId;
  }
  
  this.initialize = function() {
    this.tabIds.each(function(tabId) {
      if (tabId != this.currentTabId) {
        $(tabId).setStyle("display", "none");
      }
    }.bind(this));
  }
  
  this.selectTab = function(tabId) {
    if (this.currentTabId == tabId) return false;
    if (!this.tabIds.contains(tabId)) return false;
    
    if (this.inEffect != null) {
      this.inEffect.cancel();
      this.inEffect = null;
    }
    if (this.outEffect != null) {
      this.outEffect.complete();
      this.outEffect = null;
    }
    
    var oldTab = $(this.currentTabId);
    var newTab = $(tabId);
    this.currentTabId = tabId;
    
    // Show the new
    newTab.setStyle("opacity", 0);
    oldTab.setStyle("opacity", 1);
    newTab.setStyle("position", "");
    newTab.setStyle("display", "");
    
    // Both are visible and reseted, get their heights
    oldTabHeight = oldTab.getStyle("height").toInt();
    newTabHeight = newTab.getStyle("height").toInt();
    
    // Absolute position the old tab and set the new tabs height to the old one's
    newTab.setStyle("height", oldTabHeight);
    oldTab.setStyle("position", "absolute");
    
    this.inEffect = new Fx.Morph(newTab, { duration: 400 });
    this.inEffect.start({
      "height": newTabHeight,
      "opacity": 1
    });
    this.inEffect.complete = function() {
      newTab.setStyle("height", "");
      this.cancel();
      this.inEffect = null;
    };
    
    this.outEffect = new Fx.Morph(oldTab, { duration: 400 });
    this.outEffect.start({
      "height": newTabHeight,
      "opacity": 0
    });
    this.outEffect.complete = function() {
      oldTab.setStyle("display", "none");
      oldTab.setStyle("height", "");
      this.cancel();
      this.outEffect = null;
    };
    
    return true;
  } 
}
