var ScheduleGrid=Class.create();
ScheduleGrid.prototype={
  // JS for the HTML in app/views/events/_day_grid. Uses Prototype 1.5 (for now).
  
  initialize:function(table){
    table=$(table);
    this.model={
      hourMin:9,
      hourMax:24,
      hoursVisible:11, // # hours visible across top of schedule
      scrollIncrement:5, // hours
      directions:{ EARLIER:-1, LATER:1 }
    };
    this.model.hour=this.model.hourMin;
    this.views={
      wrapper:table,
      controls:{
        scrollEarlier:table.down('div.scroll-earlier').show().down('span').hide(),
        scrollLater:table.down('div.scroll-later').show().down('span')
      },
      events:table.down('div.events-wrapper').setStyle({overflow:"hidden"}).down('table.events')
        // div is originally overflow:auto for graceful degradation
    };
    this.observers={
      scrollEarlier:function(ev){ this.scrollEarlier(); }.bind(this),
      scrollLater:function(ev){ this.scrollLater(); }.bind(this)
    };
    
    this.startObservers();
  },
  startObservers:function(){
    this.views.controls.scrollEarlier.observe('click', this.observers.scrollEarlier);
    this.views.controls.scrollLater.observe('click', this.observers.scrollLater);
  },
  stopObservers:function(){
    this.views.controls.scrollEarlier.stopObserving('click', this.observers.scrollEarlier);
    this.views.controls.scrollLater.stopObserving('click', this.observers.scrollLater);
  },
  scrollEarlier:function(){ this.scrollEvents(this.model.directions.EARLIER); },
  scrollLater:function(){ this.scrollEvents(this.model.directions.LATER); },
  canScroll:function(direction){
    var m=this.model, dirs=m.directions;
    switch(direction){
      case dirs.EARLIER:
        return m.hour > m.hourMin;break;
      case dirs.LATER:
        return m.hour <= m.hourMax - m.hoursVisible;break;
    }
    return false;
  },
  scrollEvents:function(direction){
    if(!this.canScroll(direction)){ return; }

    var m=this.model, hours=direction*m.scrollIncrement;
    new Effect.Move(this.views.events,{ x:hours*-100, duration:0.25 });
    this.model.hour+=hours;
    
    this.toggleControl(m.directions.EARLIER);
    this.toggleControl(m.directions.LATER);
  },
  toggleControl:function(direction){
    var ctrl=this.views.controls[direction == this.model.directions.EARLIER ? 'scrollEarlier' : 'scrollLater'];
    if(this.canScroll(direction)){ ctrl.show(); }else{ ctrl.hide(); }
  }
};

Event.observe(window,'load',function(){
  $$('table.schedule-grid').each(function(t){ new ScheduleGrid(t); });
});
