/*
Copyright (c) 2009 Emilio Lucia - http://web.alimagen.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the 
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit 
persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the 
Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/


try{
 if(typeof TabBox == 'undefined'){
  var TabBox = null;
  Usefull.testPrototypeVersion(Usefull.requiredPrototype);
 }
 else{
  throw{
   name: "Error de variables",
   message: "TabBox ya se ha definido."
  }
 }


 //Clase TabBox
 TabBox = Class.create(PanelsBox, {
  initialize: function($super, container, tabsContainer, options){
   $super(container);
   this.version = '1.1.4';
   this.TBCookieJar = null;
   this.goUp = null;
   this.showing = false;
   this.TBAnchorElement = null;           //elemento al que apunta el ancla
   this.previousHeight = null;            //altura del panel previo (importante para el efecto)
   this.reLoad = false;

   Object.extend(Object.extend(this.options, {
    afterShow:          null,
    anchorClassName:    'tab-anchor',
    beforeShow:         null,
    cookieName:         'TBC',
    duration:           1,
    effect:             'none',      // 'none' o 'appear'
    goUpClassName:      'go-Up',
    goUpOffsetX:        0,
    goUpOffsetY:        0,
    goUpText:           'arriba',
    heightIncludeGoUp:  600,         //no implementado
    includeGoUp:        false,
    jumperClassName:    'tab-jumper',
    jsCtnerOffsetX:     0,
    jsCtnerOffsetY:     0,
    panelClassName:     'tab-panel',
    rememberTab:        false,
    selectedClassName:  'tab-selected',
    tabsPosition:       'top'          //'top' o 'bottom'
   }), options || {});
   
   this.options.jumpersContainer = tabsContainer;
   
   Event.observe(window, 'unload', this.onUnLoadDoc.bindAsEventListener(this));
  },

  //código a ejecutar al cargarse el dom.
  onLoadDom: function($super, e){
   var opts = this.options;   //comprimir código
   
   opts.jumpersContainer = $(opts.jumpersContainer);
   
   with(opts.jumpersContainer){
    var clonJC = clone(true);
    remove();
    $(this.container).insert({top: clonJC});
   }
   
   opts.jumpersContainer = clonJC;
   
   $super(e);
   
   if(!this.panels.length || !this.jumpers.length) return;

   $$('a.' + opts.anchorClassName).each(function(TBAnchor){
    var auxiIndex = TBAnchor.href.lastIndexOf('#'), panel = null, idElement = "";
    
    if(auxiIndex != -1 && ++auxiIndex != TBAnchor.href.length){
     TBAnchor.store('_idElement', idElement = TBAnchor.href.substr(auxiIndex));
     panel = $(idElement).up("div." + opts.panelClassName);
    }
    if(panel && typeof panel != 'undefined') TBAnchor.store('_index', panel.retrieve('_index'));
   }, this).invoke('observe', 'click', this._click.bind(this));
   
   if(opts.includeGoUp && opts.tabsPosition != 'bottom'){
    this.goUp = new Element('div').addClassName(this.options.goUpClassName).insert(new Element('a', {href: '#'}).insert(opts.goUpText));
    this.container.insert(this.goUp);
    this.goUp.select('a')[0].observe("click", this.scrollToTabs.bindAsEventListener(this));
    this.goUp.setStyle({
     display: 'block',
     position: 'absolute',
     left: opts.goUpOffsetX + 'px',
     bottom: opts.goUpOffsetY + 'px',
     zIndex: 20
    });
   }
   
   with(this.container){
    var containerTop = getStyle('position') == 'relative' ? parseInt(getStyle('top')) : 0;
    
    setStyle({
     position: 'relative',
     top: (isNaN(containerTop) ? 0 : containerTop) + opts.jumpersContainer.getHeight() + 'px',
     marginTop: '0px'
    });
   }
   
   with(opts.jumpersContainer){
    setStyle({
     display: 'block',
     position: 'absolute',
     left: opts.jsCtnerOffsetX + 'px',
     zIndex: 20
    });
    
    switch(opts.tabsPosition){
     case 'top':
      setStyle({top: -getHeight() + opts.jsCtnerOffsetY + 'px'});
      break;
     case 'bottom':
      setStyle({bottom: -getHeight() + opts.jsCtnerOffsetY + 'px'});
      break; 
    }
   }
  },

  onLoadDoc: function($super, e){
   if(!this.panels.length || !this.jumpers.length){
    alert('Error: no hay paneles o no hay controles.');
    return;
   }
   
   var overflow = this.panels[0].getStyle('overflow');     //se asume overflow igual para todos los paneles
   
   this.panels.invoke('setStyle', {
    display: 'none',
    overflow: (overflow == 'visible' ? 'hidden' : overflow ? overflow : 'auto')     //necesario para que funcione el efecto. Auto se devuelve como null
   });

   if(this.options.rememberTab){
    this.TBCookieJar = new CookieJar({expires: 5});
    var TBCObject = null;
    
    with(this.TBCookieJar){
     var cookiesNames = getKeys();
     
     for(var i = 0; i < cookiesNames.length; i++){
      if((TBCObject = get(cookiesNames[i])) && TBCObject.containerId == this.container.id){
       this.options.initial = TBCObject.panelIndex;
       remove(cookiesNames[i]);
       this.reLoad = true;
       break;
      }
     }
    }
   }
   $super(e);  //se llama al método show() por primera vez
  },

  onUnLoadDoc: function($super, e){
   if(!this.panels.length || !this.jumpers.length) return;
   
   if(this.options.rememberTab){
    var TBCObject = null;
    var cookiesNames = this.TBCookieJar.getKeys();
    this.TBCookieJar = new CookieJar({expires: 10});      //Se instancia uno nuevo para que funcione
    this.TBCookieJar.put(this.options.cookieName + cookiesNames.length, {
     panelIndex: this.currentIndex,
     containerId: this.container.id
    });
   }
  },

  _click: function($super, e){
   var element = $super(e);
   e.stop();
   if(!element || this.showing) return;
   var _index = element.retrieve('_index');
   with(element){
    if(hasClassName(this.options.anchorClassName)){
      if(_index == this.current.retrieve('_index')){
       Effect.ScrollTo(retrieve('_idElement'));
       return;
      }
      this.TBAnchorElement = retrieve('_idElement');
    }
   }
   if(typeof _index != 'undefined') this.show(_index);
  },
  
  scrollToTabs: function(e){
   Effect.ScrollTo(this.options.jumpersContainer);
   e.stop();
  },

  show: function($super){
   $super(arguments[1]);

   this.beforeShow();
   
   if(!this.previous){
    with(this.current) show().setStyle({height: getOnlyHeight() + 'px'});    //Se le pone altura por un bug en IE6
    this.afterShow();
    return;
   }
   
   switch(this.options.effect){
    case 'none':
     this.previous.hide();
     this.current.show();
     this.afterShow();
     break;
    case 'appear':
     var containerHeight = this.previous.getHeight();
     this.container.setStyle({height: containerHeight + 'px'});
     
     with(this.current){
      show();                         //para obtener dimensiones el elemento tiene que estar mostrado
      setStyle({
       position: 'absolute',
       top: this.container.getStyle('paddingTop'),
       left: this.container.getStyle('paddingLeft'),
       zIndex: 20,
       width: getOnlyWidth() + 'px',                //IMPORTANTE: suaviza el efecto
       height: getOnlyHeight() + 'px'
      });
      
      var dif = this.previous.getHeight() - getHeight();
      hide();
     }
     
     this.previousHeight = this.previous.getOnlyHeight();

     new Effect.Parallel([
      new Effect.Appear(this.current, {sync: true}),
      new Effect.Morph(this.container, {sync: true, style: 'height: ' + (containerHeight - dif) + 'px;'}),
      new Effect.Morph(this.previous, {sync: true, style: 'height: ' + (this.previousHeight - dif) + 'px; visibility: hidden;'})
     ], {
      duration: this.options.duration,
      afterFinish: function(){
       this.previous.setStyle({
        height: this.previousHeight + 'px',
        display: 'none'
       });
       this.current.setStyle({position: 'static'});
       this.afterShow();
      }.bind(this)
     });
     break;
   }
  },
  
  updateJumpers: function($super){
   $super();
   this.jumpers[this.currentIndex].addClassName(this.options.selectedClassName);
  },
  
  beforeShow: function(){
   this.updateJumpers();
   with(this.options) if(beforeShow && (typeof beforeShow == 'function')) beforeShow();
   this.showing = true;
  },

  afterShow: function(){
   with(this.options) if(afterShow && (typeof afterShow == 'function')) afterShow();
   if(this.TBAnchorElement){
    Effect.ScrollTo(this.TBAnchorElement);
    this.TBAnchorElement = null;
   }
   if(this.reLoad){
    Effect.ScrollTo(this.options.jumpersContainer);
    this.reLoad = false;
   }
   this.showing = false;
  }
 });

}
catch(e){
 alert(e.name + ": " + e.message);
}