var store = new Ext.data.JsonStore({
    url:  'data/view-dist-data.php',
	remoteSort: true,
	totalProperty: 'total',
    root: 'certificates',
    idProperty: 'dist_id',
    totalProperty: 'count',
  	sortInfo: {
            field: 'dist_id',
            direction: 'ASC'
        },
     storeId: 'myStore',
 	 fields: [{
			 name:'dist_id',
			 type:'int'
			 },
			 {	name:'company_code',
			 	type:'int'
			 },
			 {	name:'dist_nameeng',
			 	type:'string'
		     }],
	        writer:new Ext.data.JsonWriter()
});
Ext.onReady(function() {
	
	var xg = Ext.grid;
	 var sm2 = new xg.CheckboxSelectionModel({
        listeners: {
            selectionchange: function(sm) {
                if (sm.getCount() && flgDelete=='true') {
                    grid.removeButton.enable();
                } else {
                    grid.removeButton.disable();
                }
            }
        }
    });  
	var url = {
        remote:  'data/view-dist-data.php'
       };
    var encode = false;
    var local = false;
	function confirmDeleteUsers(){
    if(grid.selModel.getCount() == 1) // only one president is selected here
    {
      Ext.MessageBox.confirm('Confirmation','You are about to delete a District. Continue?', deleteUsers);
    } else if(grid.selModel.getCount() > 1){
      Ext.MessageBox.confirm('Confirmation','Delete these District?', deleteUsers);
    } 
} 
function deleteUsers(btn){
    if(btn=='yes'){
         var selections = grid.selModel.getSelections();
         var prez = [];
		 for(i = 0; i< grid.selModel.getCount(); i++){
          prez.push(selections[i].json.dist_id);
		}
         var encoded_array = Ext.encode(prez);
         Ext.Ajax.request({  
            waitMsg: 'Please Wait',
            url: 'data/district-grid-delete.php', 
            params: { 
               task: "DELETEDIST", 
               ids:  encoded_array
			   }, 
            success: function(response){
              var result=eval(response.responseText);
              switch(result){
              case 1: 
                store.reload();
				Ext.MessageBox.show({
									   title: 'Success',
									   msg: 'District Deleted Successfully.',
									   buttons: Ext.MessageBox.OK,
									   icon:Ext.MessageBox.INFO
				                      });
				
                break;
              default:
			     Ext.MessageBox.show({
									   title: 'Warning',
									   msg: 'Could not delete the entire selection.',
									   buttons: Ext.MessageBox.OK,
									   icon:Ext.MessageBox.WARNING
				                      });
                
                break;
              }
            },
            failure: function(response){
              var result=response.responseText;
			  Ext.MessageBox.show({
									   title: 'Error',
									   msg: 'Could not delete the entire selection.',
									   buttons: Ext.MessageBox.OK,
									   icon:Ext.MessageBox.ERROR
				                      });
                   
              }
         });
      }  
  }
	var filters = new Ext.ux.grid.GridFilters({
		filters:[
			{
				type: 'int',
				dataIndex: 'company_code'
			},
			{
				type: 'string',
				dataIndex: 'dist_nameeng'
			}
		]
	});
  var createColModel = function (finish, start) {
	  var columns=[
				  sm2,
				  {header: "Edit",width:45,renderer: function(value, metaData, record, rowIndex, colIndex, store) {
	    	   		return '<a href="addedit-district.php?ID='+ record.get('dist_id') +'">Edit</a>';}
				  },
		
                 { header: "ID",width:55, dataIndex: 'dist_id', sortable: true, hidden:true },
				 { header: "Company Code",width:150,dataIndex: 'company_code', sortable: true,hidden:true},
				 { header: "District Name English",width:150,dataIndex: 'dist_nameeng', sortable: true}
				
            ];
return new Ext.grid.ColumnModel({
            columns: columns.slice(start || 0, finish),
            defaults: {
                sortable: true
            }
        });
    };
	    var grid = new Ext.grid.GridPanel({
		store: store,
		selModel: new Ext.grid.RowSelectionModel({singleSelect:false}),
        colModel: createColModel(40),
		enableColLock:false,
		 stripeRows: true,
		 plugins: [filters],
		sm: sm2,
		listeners: {
            render: {
                fn: function(){
                    store.reload({
                        params: {
                            start: 0,
                            limit: 10
                        }
                    });
                }
            }
        },
		 tbar: [{
            	iconCls: 'icon-add',
           		text: 'Add District',
            	handler: function() {
               location.href="addedit-district.php"; }
          },'-',
           { 
            text: 'Delete District',
            handler: confirmDeleteUsers,   // Confirm before deleting
            iconCls:'remove',
			ref: '../removeButton',
			disabled: true
      		}],
     
        width: 250,
        height: 350,
        loadMask: true,
        columnLines:true,
        bbar: new Ext.PagingToolbar({
            pageSize: 10,
            store: store,
            displayInfo: true,
            displayMsg: 'Displaying data {0} - {1} of {2}',
            emptyMsg: "No Data found",
			plugins: [filters]
        })
				
    });
	grid.getBottomToolbar().add([
       '->',
       {
            text: 'Clear Filter Data',
            handler: function () {
                grid.filters.clearFilters();
            } 
        }  
    ]);	
	grid.on('render', function() {
   grid.tip = new Ext.ToolTip({
    view: grid.getView(),
    target: grid.getView().mainBody,
    delegate: '.x-grid3-row',
    trackMouse: true,
    renderTo: document.body,
    listeners: {
     beforeshow: function updateTipBody(tip) {
      tip.body.dom.innerHTML = "Click on Edit Link To Edit Record.";
     }
    }
   });
  });
   store.load({ params: { start: 0, limit: 10} });
    var DistrictWindow = new Ext.Window({
        title: 'View District Information',
        height: 345,
        width: 260,
		modal:true,
        layout: 'fit',
		border: false,
		closeAction:'close',
		collapsible:'true',
		
		
        items: grid
    }).show();
	
	var varWidth =  (screen.width - DistrictWindow.width)/2;
DistrictWindow.setPosition(varWidth,((screen.height/4)-100));
});