Ext.onReady(function(){
	
	//This is our JSON record set which defines what kind of data will be present in the JSON passed back from our component.
	var users = Ext.data.Record.create([
	{name:'ID',allowBlank:false},
	{name:'FIRSTNAME',type:'string'},
	{name:'LASTNAME',type:'string'},
	{name:'DISPLAYNAME',type:'string'},
	{name:'USERNAME',type:'string'},
	{name:'USERACCOUNTINGCODE',type:'string'},
	{name:'PHONE',type:'string'}
	])
	
	//The Proxy object will specify URLs to call for different CRUD operations
	var proxy = new Ext.data.HttpProxy({
		method:'POST',				
		api:{
			read: 'Users.cfc?method=getUsers',//Our URL for reading the grid data
			create: 'Users.cfc?method=addUser',//For Adding a new User (future implementation)
			update: 'Users.cfc?method=editUser'//When a User is updated
		},
		//the function writeSuccess will be called when the Store finishes a succesful write (add/edit) to the server
		listeners: {
			write: {
				fn: writeSuccess
			}
		}
	})
	
	//Our JSON Writer, configuration used to updating/adding of records
	var writer = new Ext.data.JsonWriter({
		//We will only send the changed fields
		writeAllFields:false		
	})
	
    // create the Data Store
    var store = new Ext.data.JsonStore({
    	totalProperty:'DATASET',//This is how many total records are there in the set.
    	root:'ROWS',//The Root of the data.        
		proxy:proxy,
		id:'ID',
		successProperty:'SUCCESS',//What return string data will be set to true/false to let Ext know that server call was succesful or not
		autoSave:false,//we will use event listeners to call save manually
        remoteSort:true,//We will sort server side
        //Base Params are parameters passed in during every call
        baseParams:{            	
            	returnFormat: 'JSON',
            	start: '0',
            	limit: '50'
            },
        //We define the JSON Reader for the data. We also need to set the totalProperty, root and idProperty for the dataset here.
        reader: new Ext.data.JsonReader({
        		totalProperty:'DATASET',
        		root:'ROWS',
        		idProperty:'ID'												
        	},users
        ),
        //Fields read in
        fields: [
            'ID','FIRSTNAME','LASTNAME','DISPLAYNAME','USERNAME','USERACCOUNTINGCODE','PHONE'
        ],
		writer:writer,
		//Any Store execeptions will be caught here
		listeners: {			
			exception : function(proxy,type,action,options,res,rs) {
				alert(type);
			}
		}      
    });
	
	// Our Form Variable to be used for editor grid
	var varForm = Ext.form;
	
   	//We setup the Grid
	var cm = new Ext.grid.ColumnModel({
       columns:[
	   	new Ext.grid.RowNumberer(),//This will do numbering on the grid for us        
        {
			header: "ID",
			dataIndex:'ID',
			editable: false,
			width:50 
		},
		{			
            header: "First Name",
            dataIndex: 'FIRSTNAME',
            width: 100,
            hidden:false,            
            sortable: true,			
            editor: new varForm.TextField({
                allowBlank: false
            })
        },{
            header: "Last Name",
            dataIndex: 'LASTNAME',
            width: 100,
            hidden: false,
            sortable: true,
			editor: new varForm.TextField({
                allowBlank: false
            })
        },{
            header: "Display Name",
            dataIndex: 'DISPLAYNAME',
            width: 150,
            hidden: false,
            sortable: true,
			 editor: new varForm.TextField({
                allowBlank: false
            })
        },{
            header: "User Name",
            dataIndex: 'USERNAME',
            width: 100,
            hidden: false,
            sortable: true,
			editor: new varForm.TextField({
                allowBlank: false
            })
        },{
            header: "Contact",
            dataIndex: 'PHONE',
            width: 100,
            hidden: false,
            sortable: true,
			editor: new varForm.TextField({
                allowBlank: false
            })
        }]
    })
	
	 // create the editor grid
    var grid = new Ext.grid.EditorGridPanel({
        width:750,
        height:500,		              
        title:'Users',
        store: store,
        trackMouseOver:true,
        disableSelection:false,
        loadMask: true,
		stripeRows: true,
		collapsible: true,
		cm:cm,//Our column model
		frame:true,//Make it more nicer looking (?)
        clicksToEdit: 1,//One click on row data will bring on edit box
		renderTo:'editgrid',
		// paging bar on the bottom
       bbar: new Ext.PagingToolbar({
            pageSize: 50,
            store: store,
            displayInfo: true,
            displayMsg: 'Displaying Records {0} - {1} of {2}',
            emptyMsg: "No Records to display"            
        }),
		tbar: new Ext.Toolbar({
			items : [
				{
					xtype:'tbtext',
					text:'Welcome. Click Row Data to Edit.',
					itemId:'tbartext',
					id:'tbartext'
				}
			]
		}),
		 listeners: {
		 	afteredit: { //This listener event function will be called when user finishes editing data box and tabs/enters/clicks out.
		 		fn: editStore
		 	}
		}        
    });
	
	function editStore(e)
	{
		//Call our store's save event that will fire things off'
		this.store.save();		
	}
	
	//Our server call was successful, display user feedback here
	function writeSuccess(store, action, result, res, rs)
	{
		//Get Toolbar Object
		var tbar = grid.getTopToolbar();
		//Remove current text
		tbar.remove("tbartext");
		//Add new text		
		tbar.addText({
			xtype:'tbtext',
			text:'Success !! ' + res.MESSAGE,
			itemId:'tbartext'
			}
		);
		//Redo layout to render new toolbar text
		tbar.doLayout();
	}
	
	//Default Sort set for the grid load call
	store.setDefaultSort('ID','ASC');
   
    // trigger the data store load
    store.load();	
	
});
