/**
 * 
Open Source License
------------------------------------------------------------------------------------------
Generic Table Editor is licensed under the terms of the Open Source GPL 3.0 license. 

http://www.gnu.org/licenses/gpl.html

Generic Table Editor is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Foobar is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Foobar.  If not, see .

--

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

 * 
 * Generic Table Editor
 *
 * Generic Grid to access values of a database table.
 * 
 * Check this examples:
 * http://extjs.com/deploy/dev/examples/restful/restful.html
 * http://extjs.com/deploy/dev/examples/writer/writer.html
 * http://extjs.com/deploy/dev/examples/grid/row-editor.html
 * 
 * @author Bernhard Woehrlin
 * @copyright (c) 2008-2009, IT.CappuccinoNet.com
 * @date 2009-09-01 16:27:36
 * @version 1.3
 *
 */
APPL.ux.layout.Init = Ext.extend(Ext.Panel, {
  border: false,
  id: 'id-panel',
  layout: 'anchor',
  split: true,
  empty: false,
	config: null,
  isnew: false,
	grid01: null,
	defaults: {
    split: true,
    collapsible: false,
    bodyStyle: 'padding:0px'
  },
  initComponent: function(){

    // initialize the necessary panels		
    
    // Application instance for showing user-feedback messages.
    //var App = new Ext.App({});

    // Create a standard HttpProxy instance.
		var proxy = new Ext.data.HttpProxy({
		    //url: APPL.DATA_URL
				// Alternatively, one can use the object-form to specify each API-action
				restful: 0,
				api: {
						read : APPL.DATA_URL+'/'+APPL.CONFIG.controller+'/view',
						create : APPL.DATA_URL+'/'+APPL.CONFIG.controller+'/create',
						update : APPL.DATA_URL+'/'+APPL.CONFIG.controller+'/update',
						destroy : APPL.DATA_URL+'/'+APPL.CONFIG.controller+'/destroy'
				}
				
		});

		// Typical JsonReader.  Notice additional meta-data params for defining the core attributes of your json-response
		FB.log("APPL.CONFIG: "+APPL.CONFIG.data.length, FB.INFO)
		var readeritems = new Array();
		
		for (var i = 0; i < APPL.CONFIG.data.length; i++) {
		  FB.log("id: "+APPL.CONFIG.data[i].id, FB.INFO);
			switch(APPL.CONFIG.data[i].type) {
				case('text'):
           readeritems[i] = { name: APPL.CONFIG.data[i].id, allowBlank: APPL.CONFIG.data[i].allowBlank };
           break;
				case('boolean'):
           readeritems[i] = { name: APPL.CONFIG.data[i].id, allowBlank: APPL.CONFIG.data[i].allowBlank, type: 'boolean' };
           break;
        case('date'):
           //readeritems[i] = { name: APPL.CONFIG.data[i].id, allowBlank: APPL.CONFIG.data[i].allowBlank, type: 'date', dateFormat: 'Y-m-d'};
           readeritems[i] = { name: APPL.CONFIG.data[i].id , type: 'date', dateFormat: 'Y-m-dTH:i:s'};
           break;
				case('time'):
           //readeritems[i] = { name: APPL.CONFIG.data[i].id, allowBlank: APPL.CONFIG.data[i].allowBlank, type: 'date', dateFormat: 'Y-m-d'};
           readeritems[i] = { name: APPL.CONFIG.data[i].id };
           break;
        case('integer'):
          readeritems[i] = { name: APPL.CONFIG.data[i].id };
        case('id'):
          readeritems[i] = { name: APPL.CONFIG.data[i].id };
        default: 
			   	 readeritems[i] = { name: APPL.CONFIG.data[i].id };
      }
			
		}
		FB.log(readeritems.length);
		var reader = new Ext.data.JsonReader({
		    totalProperty: 'total',
		    successProperty: 'success',
		    idProperty: 'id',
		    root: 'data'
		}, readeritems);

		// The new DataWriter component.
		var writer = new Ext.data.JsonWriter({
		    encode: false,   // <-- don't return encoded JSON -- causes Ext.Ajax#request to send data using jsonData config rather than HTTP params
		    returnJson: true,
				writeAllFields: true
			 
		});


    // Typical Store collecting the Proxy, Reader and Writer together.
		var store = new Ext.data.Store({
		    id: 'termin',
		    restful: 0,     // <-- Is this Store is RESTful?
		    proxy: proxy,
		    reader: reader,
		    writer: writer,    // <-- plug a DataWriter into the store just as you would a Reader
		    listeners: {
	        write : function(store, action, result, res, rs) {
						
						  FB.log('action: '+action);
              FB.log('result: '+result);
              if (action == 'create' || action == 'destroy') {
								FB.log('update the grid');
                userGrid.getStore().reload({params:{start:0, limit: APPL.CONFIG.grid.numrows}});
							}
	            Ext.MessageBox.alert(APPL.MSG_SAVE_SUCCESS, res.message); // <-- show user-feedback for all write actions
	            
	        },
	        exception : function(proxy, type, action, options, res, arg) {
	            if (type === 'remote') {
	                Ext.Msg.show({
	                    title: 'REMOTE EXCEPTION',
	                    msg: res.message,
	                    icon: Ext.MessageBox.ERROR,
	                    buttons: Ext.Msg.OK
	                });
	            }
	        }
        }
		});
		function formatDate(value){
        return value ? value.dateFormat('Y-m-d') : '';
    }
    
		// create reusable renderer
		Ext.util.Format.comboRenderer = function(combo){
		    return function(value){
		        var record = combo.findRecord(combo.valueField, value);
		        return record ? record.get(combo.displayField) : combo.valueNotFoundText;
		    }
		}
		var times = [];
		times.push(['--:--', '--:--']);
  
		for (i=1;i<=24;i++) {
			var h = i;
			if (h < 10) h = '0'+i;
		  
		  times.push([h+':00', h+':00']);
		  times.push([h+':30', h+':30']);
		  
		  
		  
		}
		// create the combo instance
		var combo = new Ext.form.ComboBox({
		    typeAhead: true,
		    triggerAction: 'all',
		    lazyRender:true,
		    mode: 'local',
				allowBlank: false,                    
		    store: new Ext.data.ArrayStore({
		        id: 0,
		        fields: [
		            'myId',
		            'displayText'
		        ],
		        data:  times
		    }),
		    valueField: 'myId',
		    displayField: 'displayText'
		});

		 
		var columsitems = new Array();
    //columsitems[0] = new Ext.grid.RowNumberer();
    for (var i = 0; i < APPL.CONFIG.data.length; i++) {
			FB.log("id: " + APPL.CONFIG.data[i].id, FB.INFO);
		
			switch(APPL.CONFIG.data[i].type) {
	        case('id'):
             columsitems[i] = { 
               dataIndex: APPL.CONFIG.data[i].id, 
               header: APPL.CONFIG.data[i].header, 
               sortable: APPL.CONFIG.data[i].sortable,
               width: APPL.CONFIG.data[i].width
             };
             break;
          case('text'):
             columsitems[i] = { 
               dataIndex: APPL.CONFIG.data[i].id, 
               header: APPL.CONFIG.data[i].header, 
               autoHeight: true,
               sortable: APPL.CONFIG.data[i].sortable,
               width: APPL.CONFIG.data[i].width,
               editor: new Ext.form.TextField({
							 	 xtype: 'textfield', 
								 autoHeight: true,
								 allowBlank: APPL.CONFIG.data[i].allowBlank,
                 blankText : APPL.MSG_TEXFIELD_BLANKTEXT,
								 invalidText: APPL.MSG_TEXFIELD_INVALIDTEXT
								 /*,validator: function (value) {
								 	FB.log('value: '+value);
									return null;
								 }*/
								//regex: APPL.CONFIG.data[i].regex
							 })
             };
             break;
          case('integer'):
             columsitems[i] = { 
               xtype: 'numbercolumn',
               dataIndex: APPL.CONFIG.data[i].id, 
               header: APPL.CONFIG.data[i].header, 
               sortable: APPL.CONFIG.data[i].sortable,
               width: APPL.CONFIG.data[i].width,
               editor: new Ext.form.TextField({
							 	 xtype: 'textfield', 
								 allowBlank: APPL.CONFIG.data[i].allowBlank,
								 blankText : APPL.MSG_TEXFIELD_BLANKTEXT,
                 invalidText: APPL.MSG_TEXFIELD_INVALIDTEXT
							})
             };
             break;
          case('boolean'):
	           columsitems[i] = { 
	             xtype: 'booleancolumn',
               dataIndex: APPL.CONFIG.data[i].id, 
	             header: APPL.CONFIG.data[i].header, 
	             sortable: APPL.CONFIG.data[i].sortable, 
	             width: APPL.CONFIG.data[i].width, 
	             align: 'center',
	             trueText: 'Ja',
	             falseText: 'Nein',
	             editor: {
	                xtype: 'checkbox'
	             } 
	          };
	           break;
	        case('date'):
	           columsitems[i] = { 
	             xtype: 'datecolumn',
	             dataIndex: APPL.CONFIG.data[i].id, 
	             header: APPL.CONFIG.data[i].header, 
	             sortable: APPL.CONFIG.data[i].sortable, 
	             width: APPL.CONFIG.data[i].width, 
	             format: 'Y-m-d',
	             renderer: formatDate,
               type: 'date', 
	             dateFormat: 'Y-m-d',
               editor: new Ext.form.DateField({
							 	    xtype: 'date',
                    allowBlank: false,
                    //minValue: '2006-01-01',
                    format: 'Y-m-d',
										blankText : APPL.MSG_TEXFIELD_BLANKTEXT,
                    invalidText: APPL.MSG_TEXFIELD_INVALIDTEXT,
										inputType: 'date',
										minText: 'Can\'t have a start date before the company existed!'
                    //maxValue: (new Date()).format('Y-m-d')disabledDays: [0, 6],
                    //disabledDaysText: 'Plants are not available on the weekends'
                  })
						 };
						 break;
	        case('time'):
             columsitems[i] = { 
               dataIndex: APPL.CONFIG.data[i].id, 
               header: APPL.CONFIG.data[i].header, 
               sortable: APPL.CONFIG.data[i].sortable,
               width: APPL.CONFIG.data[i].width,
               editor: combo,
               renderer: Ext.util.Format.comboRenderer(combo) // pass combo instance to reusable renderer
             };
             break;
          default: 
	           columsitems[i] = { 
	             dataIndex: APPL.CONFIG.data[i].id, 
	             header: APPL.CONFIG.data[i].header, 
	             sortable: true, 
	             width: APPL.CONFIG.data[i].width
	           };
	      }
      
    }
    FB.log(columsitems.length);
		
    
    // use RowEditor for editing
    var editor = new Ext.ux.grid.RowEditor({
        saveText: APPL.MSG_SAVE,
				errorSummary: false
    });
    
		// load the store immeditately
    store.load({params:{start:0, limit: APPL.CONFIG.grid.numrows}});

    // Create a typical GridPanel with RowEditor plugin
    var userGrid = new Ext.grid.GridPanel({
        iconCls: 'icon-grid',
        renderTo: 'application',
        frame: false,
        title: APPL.CONFIG.grid.title,
        loadMask: true,
        autoScroll: true,
        height: APPL.CONFIG.grid.height,
        width: APPL.CONFIG.grid.width,
        store: store,
        plugins: [editor],
        columns : columsitems,
        tbar: [{
            text: APPL.MSG_ADD,
            iconCls: 'silk-add',
            handler: onAdd
        }, '-', {
            text: APPL.MSG_REMOVE,
            iconCls: 'silk-delete',
            handler: onDelete
        }, '-'],
        viewConfig: {
            forceFit: true
        },// paging bar on the bottom
        bbar: new Ext.PagingToolbar({
            pageSize: APPL.CONFIG.grid.numrows,
            store: store,
            displayInfo: true,
            displayMsg: APPL.MSG_PAGING_DISPLAYMSG,
            emptyMsg: APPL.MSG_PAGING_EMPTYMSG,
						prevText: APPL.MSG_PAGING_PREVTEXT,
						nextText: APPL.MSG_PAGING_NEXTTEXT,
						lastText: APPL.MSG_PAGING_LASTTEXT,
						firstText: APPL.MSG_PAGING_FIRSTTEXT,
						beforePageText: APPL.MSG_PAGING_BEFOREPAGETEXT,
						afterPageText: APPL.MSG_PAGING_AFTERPAGETEXT
            /*items:[
                '-', {
                pressed: true,
                enableToggle:true,
                text: 'Show Preview',
                cls: 'x-btn-text-icon details',
                toggleHandler: function(btn, pressed){
                    var view = grid.getView();
                    view.showPreview = pressed;
                    view.refresh();
                }
            }]*/
        })

    });

   
    Ext.apply(this, {
      items: [userGrid]
    });
		
		/**
     * onAdd
     */
    function onAdd(btn, ev) {
        var u = new userGrid.store.recordType({
            titel : '',
            link: '',
            datum : '2009-01-01',
						show: 'false'
        });
        editor.stopEditing();
        userGrid.store.insert(0, u);
        editor.startEditing(0);
				
    }
    /**
     * onDelete
     */
    function onDelete() {
        var rec = userGrid.getSelectionModel().getSelected();
        if (!rec) {
            return false;
        }
        userGrid.store.remove(rec);
    }
		
		
    // call parent
    APPL.ux.layout.Init.superclass.initComponent.apply(this, arguments);


  } // eo initComponent
  ,afterRender: function(){

    APPL.ux.layout.Init.superclass.afterRender.apply(this, arguments);
    FB.log('Successfully rendered APPL.ux.comp.Panel', FB.DEBUG);
  } 

  
	
});

Ext.reg('medias.layout.entry', APPL.ux.layout.Init);




// eof