Ext.onReady(function(){
    Ext.QuickTips.init();
	
	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 = {
        local:  'grid-filter.json',  
        remote: '../data/bookissue-grid-filter.php'
       };
    var encode = false;
    var local = false;
   	
	function confirmDeleteBookIssue(){
    	if(grid.selModel.getCount() == 1){
      		Ext.MessageBox.confirm('Confirmation','You are about to delete a Issue Book. Continue?', deleteBookIssue);
    	} else if(grid.selModel.getCount() > 1){
      		Ext.MessageBox.confirm('Confirmation','Delete these Issue Book?', deleteBookIssue);
    	} 
  	}
	
	function deleteBookIssue(btn){
    	if(btn=='yes'){
			var selections = grid.selModel.getSelections();
			var prez1 = [];
			var prez2 = [];
			var prez3 = [];
			for(i = 0; i< grid.selModel.getCount(); i++){
				prez1.push(selections[i].json.issuedetail_id);
				prez2.push(selections[i].json.book_id);
				prez3.push(selections[i].json.issue_id);
			}
			
			var encoded_array1 = Ext.encode(prez1);
			var encoded_array2 = Ext.encode(prez2);
			var encoded_array3 = Ext.encode(prez3);
			 
			Ext.Ajax.request({  
				waitMsg: 'Please Wait',
				url: 'data/issue-grid-delete.php', 
				params:{ 
				   task: "DELETEEMP", 
				   ids1:  encoded_array1,
				   ids2:  encoded_array2,
				   ids3:  encoded_array3
				}, 
				success:function(response){
					var result=eval(response.responseText);
				  	switch(result){
				  		case 1: 
							store.reload();
							break;
				  		default:
							Ext.MessageBox.alert('Warning','Could not delete the entire selection.');
							break;
				  	}
				},
				failure:function(response){
				  	var result=response.responseText;
				  	Ext.MessageBox.alert('error','could not connect to the database. retry later');      
				}
			});
      	}  
  	}
	
	store = new Ext.data.JsonStore({
		autoDestroy: true,
        url:'data/bookissue-grid-filter.php',
        remoteSort: true,
       	sortInfo:{ field: 'book_id',direction: 'ASC' },
        storeId: 'myStore',
        idProperty: 'issuedetail_id',
        root: 'data',
        totalProperty: 'total',
        fields: [{
            name:'book_id', type:'int'
		},{
            name:'issue_registerno', type:'int'
        },{
            name:'book_registerno', type:'int'
		},{
            name: 'book_name'
        },{
            name: 'member_type', type:'list'
		 },{
            name: 'member_name', type:'list'
      	},{
            name: 'issue_date', 
			type: 'date', 
			dateFormat: 'Y-m-d'
        },{
            name: 'issue_returnlastdate', 
			type: 'date', 
			dateFormat: 'Y-m-d'
        }
		] 
    });
    
	var filters = new Ext.ux.grid.GridFilters({
	 encode: encode, 
        local:false,                                      
		filters: [{
            type: 'int',
            dataIndex: 'issue_registerno'
        },{
            type: 'int',
            dataIndex: 'book_registerno'
        },
		{
            type:'string',
            dataIndex: 'book_name'
        },
		{
            type:'list',
            dataIndex: 'member_name',
			options : [{id:'1',text:'Student'},{id:'2',text:'Employee'},{id:'3',text:'Member'}],
			phpMode: true
        },
		{
            type:'date',
            dataIndex: 'issue_date'
        },
		{
            type:'date',
            dataIndex: 'issue_returnlastdate'
        }
		]
    });
	
	var createColModel = function (finish, start){
        var columns = [
		sm2,
		{
            dataIndex: 'issue_registerno',
            header: 'Issue Reg.No.',
			width: 60
        },
		{
            dataIndex: 'book_registerno',
            header: 'Book Reg.No.',
			width: 60
        }, 
		{
            dataIndex: 'book_name',
            header: 'Book Name',align:'center',
			width:180
        }, 
		{
            dataIndex: 'member_name',
            header: 'Member Type',
			width: 80
		},
		{
            dataIndex: 'issue_date',
            header: 'Issue Date',
			renderer: Ext.util.Format.dateRenderer('d/m/Y')
        },
		{
            dataIndex: 'issue_returnlastdate',
            header: 'Issue Return Last Date',
			renderer: Ext.util.Format.dateRenderer('d/m/Y'),
			width: 100
        }
		];
return new Ext.grid.ColumnModel({
            columns: columns.slice(start || 0, finish),
            defaults: {
                sortable: true
            }
        });
    };
	
	var grid = new Ext.grid.GridPanel({
        store: store,
        colModel: createColModel(40), 
        loadMask: true,
		frame: true,
		enableColLock:false,
		columnLines:true,
	    height: 380,   
        width: 800,
        layout: 'fit',
    	selModel: new Ext.grid.RowSelectionModel({singleSelect:false}),
        plugins: [filters],
		sm: sm2,
        listeners:{
            render:{
                fn:function(){
                    store.reload({
                        params: {
                            start: 0,
                            limit: 10    
                        }
                    });
                }
            }
        },
		tbar: [
           {text: 'Delete Book',
            handler: confirmDeleteBookIssue,  
            iconCls:'remove',
			ref: '../removeButton',
			disabled: true}
	  ], 
        bbar: new Ext.PagingToolbar({
            store: store,
            pageSize: 10,
			displayInfo: true
			,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.";
     }
    }
   });
  });
	
	var ViewBookIssueWindow = new Ext.Window({
        title: 'Book Issue',
        height: 360,
        width: 650,
		modal:true,
        layout: 'fit',
		closeAction:'close',
		border: false,
		collapsible:'true',
		items: grid
    }).show();
	var varWidth =  (screen.width - ViewBookIssueWindow.width)/2;
	ViewBookIssueWindow.setPosition(varWidth,((screen.height/4)-110));
});