/**************************************************************

  Script    : plannig
  Authors   : Nicolas Charpotier
  Licence   : Open Source MIT Licence


**************************************************************/

var planning = new Class({
  
  Implements: [Options,Events],
  
  options : {},

  initialize: function(el,options){
		var that = this;
		that.elements = el;
    that.setOptions(options);
		that.elements.getElement('.bt-next').addEvent('click', function(e) {
		  e.stop();
      that.request(that.elements.getElement('#date1').value,'next');
    });
		that.elements.getElement('.bt-prev').addEvent('click', function(e) {
		  e.stop();
      that.request(that.elements.getElement('#date1').value,'prev');
    });
  },
  
  request: function(date,goto) {
		var that = this,
		    newLoader  = new Element('div', {
      'class': 'loading'
    });
    newLoader.replaces(this.elements.getElement('table'));
		req = new Request.JSON({
      url: '/elnido/availability/calendar/',
      async: false,
      encoding: 'utf-8',
      onComplete: function(j) {
        that.construct(j.calendar)
      }
    }).get({"date":date,"goto":goto});
  },
  
  construct: function(request) {

		var newTable  = new Element('table'),
		    newBody  = new Element('tbody').inject(newTable),
		    newFirstLine  = new Element('tr').inject(newBody),
		    newFirstTh  = new Element('th', {
          'scope': 'col'
        }).inject(newFirstLine),
				newLine,
				newRow,
				count=0;

		request.each(function(cal) {

		  this.elements.getElement('.title').set('html',cal.title);
		  this.elements.getElement('#date1').set('value',cal.date);

			cal.days.each(function(day) {
        new Element('th', {
          'scope': 'col',
          'html': day.title
        }).inject(newFirstLine);
		  });

			cal.rooms.each(function(room) {
        newLine = new Element('tr').inject(newBody);
				if ((count)%2) newLine.addClass('alt');
				new Element('th', {
          'scope': 'row',
          'class': 'row',
          'html': room.title
        }).inject(newLine);	

			  room.states.each(function(state) {
          newRow = new Element('td').inject(newLine);
				  if (state.isActive) newRow.addClass('inactive');
		    });
				count++;
		  });
		},this);
    newTable.replaces(this.elements.getElement('div.loading'));
  }
	
});
