Ext.override(Ext.form.TimeField, {
    initComponent: function() {
        if (typeof this.minValue == "string") {
            this.minValue = this.parseDate(this.minValue);
        }
        if (typeof this.maxValue == "string") {
            this.maxValue = this.parseDate(this.maxValue);
        }

        if (!this.store) {
            var min = this.parseDate(this.minValue);
            if (!min) {
                min = new Date(this.initDate).clearTime();
            }
            var max = this.parseDate(this.maxValue);
            if (!max) {
                max = new Date(this.initDate).clearTime().add('mi', (24 * 60) - 1);
            }
            var times = [];
            while (min <= max) {
                times.push(min.dateFormat(this.format));
                min = min.add('mi', this.increment);
            }
            this.store = times;
        }

        Ext.form.TimeField.superclass.initComponent.call(this);
    },

    beforeBlur: Ext.form.TimeField.superclass.beforeBlur // no longer required
});



function TimeBlocks(initOptions){
    if(!canEdit){
    userLogin();
    TimeSlotEditorWin.close();
    }
    windowHeight = 350;
    
    var fm = Ext.form;
    
    // create the Data Store
    var store = new Ext.data.Store({
        // destroy the store if the grid is destroyed
        autoDestroy: true,
        
        // load remote data using HTTP
        url: '/ajax/bookings/getPeriods.cfm',

        // specify a XmlReader (coincides with the XML format of the returned data)
        reader: new Ext.data.XmlReader({
            // records will have a 'plant' tag
            record: 'period',
            // use an Array of field definition objects to implicitly create a Record constructor
            fields: [
                // the 'name' below matches the tag name to read, except 'availDate'
                // which is mapped to the tag 'availability'
                {name: 'id', type: 'int'},
                {name: 'title', type: 'string'},
                {name: 'starttime'},
                {name: 'endtime'}
            ]
        })
    });
    
    
    var cm = new Ext.grid.ColumnModel({
        columns: [
            {
                id: 'blockID',
                header: 'ID',
                dataIndex: 'id',
                hidden: true
            },
            {
                id: 'blockName',
                header: 'Time Block Name',
                dataIndex: 'title',
                width: 220,
                // use shorthand alias defined above
                editor: new fm.TextField({
                    allowBlank: false
                })
            }, {
                header: 'Start Time',
                dataIndex: 'starttime',
                width: 130,
                editor: new fm.TimeField({
                  name: 'timeStart',
                  dataIndex: 'starttime',
                  minValue: '6:00am',
                  maxValue: '8:00pm'
                })
            }, {
                header: 'Ending Time',
                dataIndex: 'endtime',
                width: 130,
                editor: new fm.TimeField({
                  name: 'timeEnd',
                  dataIndex: 'endtime',
                  minValue: '6:00am',
                  maxValue: '8:00pm'
                })
            }
        ]
    });
    
 
  var grid = new Ext.grid.EditorGridPanel({
        store: store,
        cm: cm,
        width: 600,
        height: 300,
        autoExpandColumn: 'blockName', // column with this id will be expanded
        frame: true,
        clicksToEdit: 1,
        buttons: [{
                text: 'Save',
                handler: function(){
                  var json_params = Ext.encode(this.data);  
                   store.each(function(record) {  
                        Ext.Ajax.request({
                           url: '/ajax/bookings/saveTimes.cfm',
                           success: function() {TimeSlotEditorWin.close()},
                           failure: function() {console.debug('failure')},
                           //callback: function(o,s,r) {$('#response').html(r.responseText)},
                           params: record.data
                        });
                    });
            }},{
            text: 'Cancel',
            handler: function(){ TimeSlotEditorWin.close() }
        }]
    });
    
    
    grid.on({
      cellclick:{
        fn: function(grid, rowIndex, columnIndex, e){
              var fieldName2 = grid.getColumnModel().getDataIndex(2); 
              var fieldName3 = grid.getColumnModel().getDataIndex(3); 
              var dt = new Date();
              var valid = true;
              if(rowIndex > 0 && columnIndex == 2) {
                var recordPrev = grid.getStore().getAt(rowIndex-1);  
                var record = grid.getStore().getAt(rowIndex);
                
                var previousCellValue = Date.parseDate(recordPrev.get(fieldName3),'g:i A');
                var CurrentCellValue = Date.parseDate(record.get(fieldName2),'g:i A');
                var NextCellValue = Date.parseDate(record.get(fieldName3),'g:i A');
                
                if(previousCellValue > CurrentCellValue || NextCellValue < CurrentCellValue)
                   valid = false;
                   //record.reject();
              
              } else if(rowIndex < 9 && columnIndex == 3){
                var record = grid.getStore().getAt(rowIndex);  
                var recordNext = grid.getStore().getAt(rowIndex+1);  
              
                var previousCellValue = Date.parseDate(record.get(fieldName2),'g:i A');
                var CurrentCellValue = Date.parseDate(record.get(fieldName3),'g:i A');
                var NextCellValue = Date.parseDate(recordNext.get(fieldName2),'g:i A');
                
                if(previousCellValue > CurrentCellValue || NextCellValue < CurrentCellValue)
                   valid = false;
                   //record.reject();
                
              } else if(rowIndex == 9 && columnIndex == 3){
                var record = grid.getStore().getAt(rowIndex); 
                
                var previousCellValue = Date.parseDate(record.get(fieldName2),'g:i A');
                var CurrentCellValue = Date.parseDate(record.get(fieldName3),'g:i A');
                
                if(previousCellValue > CurrentCellValue)
                  valid = false;
                   //record.reject();
              }
              
              if(!valid) {
                var cell = grid.getView().getCell(rowIndex, columnIndex);
                var el = Ext.get(cell);
                var classOld = 'x-form-invalid';
 
                // toggle the cssClass
                if (el.hasClass(classOld)) {
                    el.removeClass(classOld);
                } else {
                    el.addClass(classOld);
                }
              
              }
       }
      }
    });

 var TimeSlotEditorWin = new Ext.Window({
          id: 'timeSlotEditor',
          plain: true,
          title: 'Time Blocks',
          width:370,
          minWidth: 370,
          height:windowHeight,
          minheight:windowHeight,
          maxHeight: windowHeight,
          border: false,
          layout:'fit',
          closable: true,
          closeAction:'close',
          maximizable: true,
          modal: false,
          items: grid
          
      });
      TimeSlotEditorWin.show(this);
      store.load();
};



