/**
 * @author Bruno Bornsztein <bruno@missingmethod.com>
 * @copyright 2007 Curbly LLC
 * @package Glider
 * @license MIT
 * @url http://www.missingmethod.com/projects/glider/
 * @version 0.0.3
 * @dependencies prototype.js 1.5.1+, effects.js
 */

/*  Thanks to Andrew Dupont for refactoring help and code cleanup - http://andrewdupont.net/  */

Glider = Class.create({
    initialize: function(wrapper, options){
        
        this.scrolling  = false;
        this.wrapper    = $(wrapper);
        this.container  = new Element('div').addClassName("scrollcontainer");
        this.scroller   = new Element('div').addClassName("scroller");
        
        this.scroller.update(this.wrapper.innerHTML);
        this.wrapper.update('');
        this.wrapper.insert(this.container);
        this.container.insert(this.scroller);
        
        this.sections   = this.scroller.childElements();
        
        if(this.sections.length > 1){            
            this.options    = Object.extend({ duration: 1.0, frequency: 5, controls:false, arrows:false }, options || {});
            
            this.sections.each( function(section, index) {
              section._index = index;
            });

            this.events = {
                click: this.click.bind(this)
            };
            if(this.options.controls){               
                this.buildControls();
            }
            if(this.options.arrows){
                this.buildArrows();
            }
            
            if(this.options.initialSection) this.moveTo(this.options.initialSection, this.scroller, { duration:this.options.duration });  // initialSection should be the id of the section you want to show up on load
            if(this.options.autoGlide){
                var self = this;
                this.wrapper.observe("mouseleave",function(e){self.start();});
                this.wrapper.observe("mouseenter",function(e){self.stop();});
                this.start();
            }
        }

      },

  buildControls: function(){
      var d = new Element('div');
      d.className = "controls";
      this.controls = [];
      var self = this;
      this.sections.each( function(section, index) {
          var link = new Element('a');
                   
          var div = new Element('div');
          link.insert(div);
          d.insert(link);
          self.controls.push(link);
          link.observe('click', self.events.click);

      });
      this.wrapper.insert(d);
      this.markControl(0);
  },  
  
  buildArrows: function(){
      var self = this;
      var la = new Element('div').addClassName("leftarrow");
      this.wrapper.insert(la);
      la.observe("click",function(event){
         self.previous(); 
      });
      var ra = new Element('div').addClassName("rightarrow");
      this.wrapper.insert(ra);
      ra.observe("click",function(event){
         self.next(); 
      });
      ra.hide();
      la.hide();
      this.wrapper.observe("mouseenter",function(event){
          
          ra.show();
          la.show();
      });
      this.wrapper.observe("mouseleave",function(event){
          
          ra.hide();
          la.hide();
      });
  },

  click: function(event) {    
    this.stop();
    var link = Event.findElement(event, 'a');    
    if (this.scrolling) this.scrolling.cancel();
    //determine index of control element
    var index = link.previousSiblings().length;
    this.markControl(index);   
    this.moveTo(this.sections[index], this.scroller, { duration:this.options.duration });     
    Event.stop(event);
  },

  markControl: function(index){
      for(var i = 0;i<this.controls.length;i++){
        var control = this.controls[i];
        control.removeClassName("active");
        if(i==index)control.addClassName("active");
      }
  },

  moveTo: function(element, container, options){
        this.current = $(element);        
        var move = -container.offsetLeft - $(element).offsetLeft;
        var newx = - element.offsetLeft;
        this.scrolling = new Effect.Move(container, { x: newx, y: 0, mode: 'absolute', duration: this.options.duration});
        //this.scrolling = new Effect.MoveBy(container,0,move,options);
        return false;
    },
		
  next: function(){
    if (this.current) {
      var currentIndex = this.current._index;
      var nextIndex = (this.sections.length - 1 == currentIndex) ? 0 : currentIndex + 1;      
    } else {
        var nextIndex = 1;
    }
    
      this.markControl(nextIndex);
      this.moveTo(this.sections[nextIndex], this.scroller);
    
  },
	
  previous: function(){
    if (this.current) {
      var currentIndex = this.current._index;
      var prevIndex = (currentIndex == 0) ? this.sections.length - 1 : 
       currentIndex - 1;
    } else var prevIndex = this.sections.length - 1;
    this.markControl(prevIndex);
    this.moveTo(this.sections[prevIndex], this.scroller);
  },

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

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



    periodicallyUpdate: function()
    {  
         this.timer = setInterval(this.next.bind(this), this.options.frequency*1000);
    }

});
