/*
Copyright (c) 2009 Victor Stanciu - http://www.victorstanciu.ro

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.

Este código es una modificación/evolución del código creado por Victor Stanciu
realizada por Alimagen - http://web.alimagen.com

*/


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


 //Clase ProtoCarrusel
 ProtoCarrusel = Class.create(PanelsBox, {
  initialize: function($super, container, options){
   $super(container);
   this.version = '1.4.4';
   this.scrolling = false;
   this.scroller = null;
   this.controls = [];
   this.timer = null;

   Object.extend(Object.extend(this.options, {
    auto:               false,
    afterMove:          null,                 //función a ejecutar después de mover
    beforeMove:         null,
    circular:           false,
    controlClassName:   'carousel-control',
    controlsContainer:  null,
    disabledClassName:  'carousel-disabled',
    duration:           1,
    effect:             'scroll',
    frequency:          6,
    jumperClassName:    'carousel-jumper',
    lapseInterval:      5,
    marginZero:         false,
    next:               true,
    panelClassName:     'carousel-slide',
    selectedClassName:  'carousel-selected',
    transition:         'sinoidal',
    vertical:           false,            //si true implementar en vertical (hay que cambiar las dimensiones del scroller)
    visibleSlides:      1,
    wheel:              false
   }), options || {});

   if(this.options.effect == 'fade') this.options.circular = true;
   if(Usefull.domLoaded && !this.building) this.build();
  },

  //código a ejecutar al cargarse el dom.
  onLoadDom: function($super, e){
   $super(e);

   var containerHtml = this.container.innerHTML;
   
   //Arregla un bug en Chrome
   this.container.setStyle({
    height: '0px',
    overflow: 'hidden'
   });

   //Se crean dos divs dentro del contenedor
   this.container.insert(this.scroller = new Element('div').addClassName('scroller').insert(new Element('div').addClassName('contSlides')));
   this.scroller.firstDescendant().innerHTML = containerHtml;
   this.panels.invoke('remove');
   this.panels = this.scroller.select('.' + this.options.panelClassName);

   if(this.options.wheel) this.scroller.observe('mousewheel', this.wheel.bindAsEventListener(this)).observe('DOMMouseScroll', this.wheel.bindAsEventListener(this));

   if(this.options.controlsContainer){
    this.controls = $(this.options.controlsContainer).select('.' + this.options.controlClassName);
    this.controls.invoke('observe', 'click', this._click.bind(this));
    if(this.controls.length){
     this.options.auto = this.options.circular = false;
     if(this.options.controlsContainer) $(this.options.controlsContainer).setStyle({display: 'block'});
    }
   }

   if(this.options.circular){
    this.options.visibleSlides = 1;
    var clonFirst = this.panels[0].clone(true);
    var clonSecond = this.panels[1].clone(true);
    with(this.panels){
     last().insert({after: clonFirst});
     push(clonFirst);
     last().insert({after: clonSecond});
     push(clonSecond);
    }
   }
   this.panels.each(function(slide, index){slide.store('_index', index);});
   with(this.scroller) scrollLeft = scrollTop = 0;
   
   //Aplicar estilos
   var slideAuxi = this.panels[0];
   var paddings = slideAuxi.accumulateDimensions(['paddingLeft', 'paddingRight']);
   var borderWidth = slideAuxi.accumulateDimensions(['borderLeftWidth', 'borderRightWidth']);
   var slidesWidth = slideAuxi.getWidth();
   var slidesWidthWB = slideAuxi.getWidth() - (paddings + borderWidth);
   var maxNumSlides = (this.container.getWidth()/slidesWidth).floor();
   if(this.options.visibleSlides > maxNumSlides) this.options.visibleSlides = maxNumSlides;
   
   var horMargins = 0, verMargins = 0, scrollerHorMargins = 0, scrollerVerMargins = 0, scrollerWidth = 0, scrollerHeight = 0, slidesContWidth = 0, slidesContHeight = 0;
   if(this.options.marginZero) this.panels.invoke('setStyle', {margin: 0 + 'px'});   
   var horMarginsCss = ['marginLeft', 'marginRight'], verMarginsCss = ['marginTop', 'marginBottom'];
   if(this.options.vertical){
    horMargins = slideAuxi.accumulateDimensions(horMarginsCss);
    verMargins = this.panels.inject(0, function(acc, panel, n){return acc + panel.accumulateDimensions(verMarginsCss);});
    scrollerHorMargins = horMargins;
    for(var i = 0; i < this.options.visibleSlides; i++) scrollerVerMargins += this.panels[i].accumulateDimensions(verMarginsCss);
    scrollerWidth = slidesWidth + scrollerHorMargins;
    scrollerHeight = slideAuxi.getHeight() * this.options.visibleSlides + scrollerVerMargins;
    slidesContWidth = scrollerWidth;
    slidesContHeight = slideAuxi.getHeight() * this.panels.length + verMargins;
   }
   else{
    horMargins = this.panels.inject(0, function(acc, panel, n){return acc + panel.accumulateDimensions(horMarginsCss);});
    if(Usefull.IE6) horMargins += this.panels[0].accumulateDimensions(['marginLeft']);
    verMargins = slideAuxi.accumulateDimensions(verMarginsCss);
    for(var i = 0; i < this.options.visibleSlides; i++) scrollerHorMargins += this.panels[i].accumulateDimensions(horMarginsCss);
    scrollerVerMargins = verMargins;
    scrollerWidth = slidesWidth * this.options.visibleSlides + scrollerHorMargins;
    scrollerHeight = slideAuxi.getHeight() + scrollerVerMargins;
    slidesContWidth = slidesWidth * this.panels.length + horMargins;
    slidesContHeight = scrollerHeight;
   }
   
   this.panels.invoke('setStyle', {
    width: slidesWidthWB + 'px',
    'float': 'left'
   });
   this.scroller.firstDescendant().setStyle({
    width: slidesContWidth + 'px',
    height: slidesContHeight + 'px',
    overflow: 'hidden'
   });
   this.scroller.setStyle({
    width: scrollerWidth + 'px',
    height: scrollerHeight + 'px',
    margin: '0px',
    overflow: 'hidden'
   });
   this.container.setStyle({
    width: scrollerWidth + 'px',
    height: scrollerHeight + 'px'
   }).scrollTop = 0;
  },

  onLoadDoc: function($super, e){
   $super(e);
   if(this.options.auto) this.start();
   this.building = false;
  },

  _click: function($super, e){
   var element = $super(e);
   e.stop();
   if(this.scrolling) return;         //volver si el carrusel se mueve
   this.lapse();
   if(element.hasClassName(this.options.disabledClassName)) return;
   else{
    if(element.hasClassName(this.options.controlClassName)) eval("this." + element.rel + "()");
    else if(element.hasClassName(this.options.jumperClassName)){
     var slideIndex = this.validateIndex(element.href.match(/#((?:(?:\w)+[.-]*)+)/) ? $(RegExp.$1).retrieve('_index') : element.retrieve('_index'));
     if(this.options.circular && this.options.effect != 'fade'){
      if(slideIndex == this.currentIndex || (this.currentIndex - this.jumpers.length) == slideIndex) return;
      var halfway = this.jumpers.length / 2;
      var distance = (this.currentIndex - slideIndex).abs();
      switch(this.currentIndex){
       case 0:
        if(distance > halfway) this.show(this.lastIndex());
        break;
       case 1:
        if(distance > halfway) this.show(this.lastIndex() + 1);
        break;
       case this.lastIndex():
        if(distance > halfway) this.show(this.firstIndex() - 1);
        break;
      }
     }
     this.moveTo(slideIndex);
    }
   }
  },
  
  show: function($super){
   $super(arguments[1]);
   
   this.beforeMove();
   var slideOffset = this.offset(this.current);
   with(this.scroller){
    scrollLeft = slideOffset[0];
    scrollTop = slideOffset[1];
   }
   this.afterMove();
  },

  moveTo: function(){
   this.updateCurrent(arguments[0]);
   
   var slideOffset = this.offset(this.current);

   if(this.scrolling) this.scrolling.cancel();
   switch(this.options.effect){
    case 'fade':
     this.scrolling = new Effect.Opacity(this.scroller, {
      from: 1.0,
      to: 0,
      duration: this.options.duration,
      afterFinish: function(){
       this.scroller.scrollLeft = slideOffset[0];
       this.scroller.scrollTop = slideOffset[1];
       new Effect.Opacity(this.scroller, {
        from: 0,
        to: 1.0,
        duration: this.options.duration,
        beforeStart: this.beforeMove.bind(this),
        afterFinish: this.afterMove.bind(this)
       });
      }.bind(this)
     });
     break;

    case 'scroll':
    default:
     var ourTransitions = ['spring'];
     var transition = eval('Effect.Transitions.' + (ourTransitions.include(this.options.transition) ? this.options.transition : 'sinoidal'));
     this.scrolling = new Effect.SmoothScroll(this.scroller, {
      duration: this.options.duration,
      x: slideOffset[0],
      y: slideOffset[1],
      transition: transition,
      beforeStart: this.beforeMove.bind(this),
      afterFinish: this.afterMove.bind(this)
     });
   }
   return false;
  },

  prev: function(){
   var prevIndex = 0;
   prevIndex = this.currentIndex - this.options.visibleSlides;
   prevIndex = this.validateIndex(prevIndex);
   if(this.currentIndex == this.firstIndex() && this.options.circular && this.options.effect != 'fade') this.show(this.lastIndex() + 1);
   this.moveTo(prevIndex);
  },

  next: function(){
   var nextIndex = this.options.visibleSlides;
   nextIndex = this.validateIndex(this.currentIndex + this.options.visibleSlides);
   if(this.currentIndex == this.lastIndex() && this.options.circular && this.options.effect != 'fade') this.show(this.firstIndex() - 1);
   this.moveTo(nextIndex);
  },

  first: function(){this.moveTo(this.firstIndex());},

  last: function(){this.moveTo(this.lastIndex());},

  toggle: function(){
    if(this.previous) this.moveTo(this.panels[this.previous.retrieve('_index')]);
    else return false;
  },

  stop: function(){if(this.timer) clearTimeout(this.timer);},

  start: function(){this.periodicallyUpdate();},

  pause: function(){
    this.stop();
    this.activateControls();
  },

  lapse: function(){
   if(this.options.auto){
    this.stop();
    this.timer = setTimeout(this.periodicallyUpdate.bind(this), this.options.lapseInterval * 1000);
   }
  },

  periodicallyUpdate: function(){
   if(this.timer != null){
    clearTimeout(this.timer);
    this.options.next ? this.next(): this.prev();
   }
   this.timer = setTimeout(this.periodicallyUpdate.bind(this), this.options.frequency * 1000);
  },

  wheel: function(e){
   var delta = 0;

   this.lapse();
   e = window.event || e;  //Prototype no da soporte para eventos de rueda del ratón. Tampoco carga el evento.
   Event.stop(e);

   if(e.wheelDelta) delta=e.wheelDelta / 120; 
   else if(e.detail) delta=-e.detail / 3;
   if(!this.scrolling){              //Poner al principio
    this.deactivateControls();
    if(delta > 0) this.prev();
    else this.next(); 
   } 
   return Math.round(delta); //Safari Round
  },

  deactivateControls: function(){this.controls.invoke('addClassName', this.options.disabledClassName);},

  activateControls: function(){
   if(!this.controls.length) return;
   var lastSlideIndex = this.lastIndex();

   if(this.options.circular) this.controls.invoke('removeClassName', this.options.disabledClassName);
   else{
    if(lastSlideIndex == 0) return;
    if(this.currentIndex != 0 && this.currentIndex != lastSlideIndex) this.controls.invoke('removeClassName', this.options.disabledClassName);
    else{
     if(this.currentIndex == 0) this.controls.findAll(function(s){return ['next','last'].include(s.rel);}).invoke('removeClassName',this.options.disabledClassName);
     if(this.currentIndex == lastSlideIndex) this.controls.findAll(function(s){return ['first','prev'].include(s.rel);}).invoke('removeClassName',this.options.disabledClassName);
    }
   }
  },
  
  updateJumpers: function($super){
   $super();
   if(this.options.selectedClassName && this.jumpers.length){
    this.jumpers[this.currentIndex < this.jumpers.length ? this.currentIndex : 0].addClassName(this.options.selectedClassName);
   }
  },
  
  beforeMove: function(){
   this.deactivateControls();
   this.updateJumpers();
   if(this.options.beforeMove && (typeof this.options.beforeMove == 'function'))  this.options.beforeMove();
  },

  afterMove: function(){
   this.activateControls();
   if(this.options.afterMove && (typeof this.options.afterMove == 'function')) this.options.afterMove();
   this.scrolling = false;
  },
  
  //Primer índice válido
  firstIndex: function(){return this.options.circular ? 1 : 0;},
  
  //Último índice válido
  lastIndex: function(){
   var numPanels = this.panels.length;
   var lastValidIndex = numPanels - this.options.visibleSlides;
   return numPanels > this.options.visibleSlides ? (this.options.circular ? lastValidIndex - 1 : lastValidIndex) : 0;
  },
  
  validateIndex: function(slideIndex){
   if(typeof slideIndex == 'undefined'){
    alert('El panel al que saltar no est&aacute; definido correctamente.');
    return this.firstIndex();
   }
   var lastSlideIndex = this.lastIndex(), firstSlideIndex = this.firstIndex();
   if(slideIndex < firstSlideIndex) return this.options.circular || this.options.auto ? lastSlideIndex : firstSlideIndex;
   return slideIndex > lastSlideIndex ? (this.options.circular || this.options.auto ? firstSlideIndex : lastSlideIndex) : slideIndex;
  },
  
  //Desplazamiento de un panel
  offset: function(slide){
   var scrollerOffset = this.scroller.cumulativeOffset();
   var slideOffset = slide.cumulativeOffset();
   var marginLeft = parseInt(slide.getStyle('margin-left'));
   var marginTop = parseInt(slide.getStyle('margin-top'));
   return [(slideOffset[0] - scrollerOffset[0]) - (Usefull.IE6 ? marginLeft * 2 : marginLeft), (slideOffset[1] - scrollerOffset[1]) - marginTop];
  }
 });
 

 //Efecto SmoothScroll
 Effect.SmoothScroll = Class.create(Effect.Base, {
  initialize: function(element){
   this.element = $(element);
   var options = Object.extend({x:0, y:0, mode:'absolute'} , arguments[1] || {});
   this.start(options);
  },

  setup: function(){
   if(this.options.continuous && !this.element._ext){
    this.element.cleanWhitespace();
    this.element._ext = true;
    this.element.appendChild(this.element.firstChild);
   }
   this.originalLeft = this.element.scrollLeft;
   this.originalTop = this.element.scrollTop;
   if(this.options.mode == 'absolute'){
    this.options.x -= this.originalLeft;
    this.options.y -= this.originalTop;
   }
  },

  update: function(position){
   this.element.scrollLeft = this.options.x * position + this.originalLeft;
   this.element.scrollTop = this.options.y * position + this.originalTop;
  }
 });

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



