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();
                }
            }
        }
    });  
	 	
	function confirmdeletebook(){
		
		var selections = grid.selModel.getSelections();
        var prez = [];
        for(i = 0; i< grid.selModel.getCount(); i++){
         	prez.push(selections[i].json.book_id);
		}
        var encoded_array = Ext.encode(prez);
		
		Ext.Ajax.request({
			loadMask: true,
			sync : true,
			url: 'data/getBookRelatedRecord.php',
			params: {book_id: encoded_array},
			success: function(resp) {
				
				var str = "";
				resbool=resp.responseText;
				if(resbool != ""){
					str = "It has related record in " + resbool;	
				}
				Ext.MessageBox.confirm('Confirmation', str +' Are you sure want to delete.?', deletebook);
				
			}				
		});		

  	} 
  	
	function deletebook(btn){		
	    if(btn=='yes'){
         var selections = grid.selModel.getSelections();
         var prez = [];
         for(i = 0; i< grid.selModel.getCount(); i++){
          prez.push(selections[i].json.book_id);
         }
         var encoded_array = Ext.encode(prez);
         Ext.Ajax.request({  
            waitMsg: 'Please Wait',
            url:  'book-grid-delete.php', 
            params: { 
               task: "DELETEBOOK", 
               ids:  encoded_array
              }, 
            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');      
              }
         });
      }  
  	}
	
    var store = new Ext.data.JsonStore({
		autoDestroy: true,
		totalProperty: 'count',	
		root: 'rows',
		remoteSort: true,
        sortInfo: {
            		field: 'book_id',
            		direction: 'ASC'
		},	
		url: 'data/view-book-data.php', 			
        fields: [{
					name:'book_id',
					type: 'int'
				},{
					name:'school_id',
					type: 'int'
				},{
					name:'book_registerid',
					type: 'list'
				},{
					name:'book_registerno',
					type: 'int'
				},{
					name: 'book_name',
					type: 'list'
				},
				{
					name: 'branch_name',
					type: 'list'
				},
				{
					name: 'book_category',
					type: 'list'
				}, {
					name: 'book_language',
					type: 'list'
				},{
					name: 'book_author',
					type: 'list'
				},{
					name: 'publisher_name',
					type: 'list'
				},{
					name: 'book_price',
					type: 'int'
				},{
					name: 'book_vender',
					type: 'list'
				},{
					name: 'book_edition',
					type: 'list'
				},{
					name: 'book_available',
					type: 'list'
				},{
					name: 'book_rack',
					type: 'string'
				},
				{
					name: 'book_shelf_no',
					type: 'string'
				},
				{
					name: 'book_divno',
					type: 'string'
				},{
					name: 'book_gift',
					type: 'list'
				},{
					name:'book_purchasedate',
					 type: 'date',
					 dateFormat: 'Y-m-d'
				}],
		idProperty: 'book_id,book_name',
		writer:new Ext.data.JsonWriter()
    });	
	
	var booknameObj = Ext.data.Record.create([
           {name: 'book_name'},
           {name: 'book_name'}
    ]);
	
	var bookcategoryObj = Ext.data.Record.create([
           {name: 'book_category'},
           {name: 'book_category'}
    ]);
	
	
	
	var booklanguageObj = Ext.data.Record.create([
           {name: 'book_language'},
           {name: 'book_language'}
    ]);
	
	var bookauthornameObj = Ext.data.Record.create([
           {name: 'book_author'},
           {name: 'book_author'}
    ]);
	
	var bookauthornamestore = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy
			({
            	
				url: 'data/getBookGenerelStore.php',
				success: function(response,options){
                	var json = Ext.util.JSON.decode(response.responseText);
            	} 
       		}),
        reader: new Ext.data.JsonReader({
		root: 'rows',
		id: 'book_author',
		labelField:'book_author'
		},bookauthornameObj)
	}); 
	bookauthornamestore.load({params:{action:'author'}});
	 
	var bookpublishernameObj = Ext.data.Record.create([
           {name: 'publisher_name'},
           {name: 'publisher_name'}
    ]);
 	
	var bookpublishernamestore = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy
			({
            	
				url: 'data/getBookGenerelStore.php',
				success: function(response,options){
                	var json = Ext.util.JSON.decode(response.responseText);
            	} 
       		}),
        reader: new Ext.data.JsonReader({
		root: 'rows',
		id: 'publisher_name',
		labelField:'publisher_name'
		},bookpublishernameObj)
	});
	
	bookpublishernamestore.load({params:{action:'publishername'}});
	
	var bookvendernameObj = Ext.data.Record.create([
           {name: 'book_vender'},
           {name: 'book_vender'}
    ]);
	
	var bookvendernamestore = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy
			({
            	
				url: 'data/getBookGenerelStore.php',
				success: function(response,options){
                	var json = Ext.util.JSON.decode(response.responseText);
            	} 
       		}),
        reader: new Ext.data.JsonReader({
		root: 'rows',
		id: 'book_vender',
		labelField:'book_vender'
		},bookvendernameObj)
	});
	
	bookvendernamestore.load({params:{action:'vender'}});
	 
	var bookeditionObj = Ext.data.Record.create([
           {name: 'book_edition'},
           {name: 'book_edition'}
    ]);
	
	var bookeditionstore = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy
			({
            	
				url: 'data/getBookGenerelStore.php',
				success: function(response,options){
                	var json = Ext.util.JSON.decode(response.responseText);
            	} 
       		}),
        reader: new Ext.data.JsonReader({
		root: 'rows',
		id: 'book_edition',
		labelField:'book_edition'
		},bookeditionObj)
	});
	bookeditionstore.load({params:{action:'edition'}});
	
	var registersObj = Ext.data.Record.create([
           {name: 'register_id'},
           {name: 'register_name'}
    ]);
	
	var registerstore = new Ext.data.Store({ 
	    proxy: new Ext.data.HttpProxy
			({									    
				url: 'data/getBookRegister.php', 
				success: function(response,options){
                	var json = Ext.util.JSON.decode(response.responseText);
            	} 
       		}),
		reader: new Ext.data.JsonReader({			
		id: 'register_id',
		labelField:'register_name',
		root: 'rows'
	  },registersObj)
	});
	registerstore.load();
	
	
	
	var filters = new Ext.ux.grid.GridFilters({
		filters:[
					{
					  type: 'numeric',
					  dataIndex: 'book_id',
					  phpMode: true
					},{
						type: 'numeric',
						dataIndex: 'book_registerno',
						 phpMode: true
					},{
						type:'list',
						dataIndex: 'publisher_name',
						labelField:'publisher_name',
						store : bookpublishernamestore,
						phpMode: true
					},{
						type:'list',
						dataIndex: 'book_author',
						labelField:'book_author',
						store : bookauthornamestore,
						phpMode: true
					}, {
						type:'list',
						dataIndex: 'book_vender',
						labelField:'book_vender',
						store : bookvendernamestore,
						phpMode: true
					},{
						  type: 'numeric',
						  dataIndex: 'book_price',
						  phpMode: true
					},{
						type:'list',
						dataIndex: 'book_edition',
						labelField:'book_edition',
						store : bookeditionstore,
						phpMode: true
					}, {
						type:'list',
						dataIndex: 'book_available',
						options : [{id:'1',text:'Yes'},{id:'0',text:'No'}],
						phpMode: true
					}, {
						type:'list',
						dataIndex: 'book_gift',
						options : ['Purchase','Gift'],
						phpMode: true
					},{
						type: 'date',
						dataIndex: 'book_purchasedate'
					}
				]
    });  
//grid.getColumnModel().setHidden(7, true);
	var createColModel = function (finish, start) {
        var columns =[sm2,
			{header: "Edit",width:40,renderer: function(value, metaData, record, rowIndex, colIndex, store) {
	    	   		return '<a href="addedit-book.php?ID='+ record.get('book_id') +'">Edit</a>';}
			},{header: "Cancel",width:45,renderer: function(value, metaData, record, rowIndex, colIndex, store) {
	    	   		return '<a href="addedit-book-cancel.php?ID='+ record.get('book_id') +'">Cancel</a>';}
			},
  		    {id:'book_id',header: "ID", width: 40, sortable: true, dataIndex: 'book_id',hidden: true
			},{header: 'Register Name', width: 90, sortable: true, dataIndex: 'book_registerid',align:'left'
			},{header: 'Reg No', width: 65, sortable: true, dataIndex: 'book_registerno',align:'center'
			},{header: 'Book Name', width: 140, sortable: true, dataIndex: 'book_name'
			},{header: 'Language', width: 80, sortable: true, dataIndex: 'book_language'
			},{header: 'Branch Name', width: 100, sortable: true, dataIndex: 'branch_name'
			},{header: 'Book Category', width: 100, sortable: true, dataIndex: 'book_category'
			},{header: 'Book Edition', width: 100, sortable: true, dataIndex: 'book_edition',align:'center'
			},{header: 'Book Author', width: 100, sortable: true, dataIndex: 'book_author'
			},{header: 'Publisher Name', width: 100, sortable: true, dataIndex: 'publisher_name'
			},{header: 'Vender Name', width: 100, sortable: true, dataIndex: 'book_vender'
			},{header: 'Division', width: 70, sortable: true, dataIndex: 'book_divno'
			},{header: 'Rack', width: 70, sortable: true, dataIndex: 'book_rack'
			},{header: 'Shelf No', width: 70, sortable: true, dataIndex: 'book_shelf_no'
			},{header: 'Price', width: 80, sortable: true, dataIndex: 'book_price',align:'center'
			},{header: 'Purchase/Gift', width: 85, sortable: true, dataIndex: 'book_gift'
			},{header: "Date", width: 70,dataIndex: 'book_purchasedate',sortable: true,
			renderer: Ext.util.Format.dateRenderer('d/m/Y')
			}/*,{header: 'Book Active', width: 85, sortable: true, dataIndex: 'book_active',align:'center'
			}*/,{header: 'Book Available', width: 85, sortable: true, dataIndex: 'book_available',align:'center'
			}];
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),
    	selModel: new Ext.grid.RowSelectionModel({singleSelect:false}),
 		loadMask: true,
		columnLines:true,
    	 stripeRows: true,
		frame: true,
		enableColLock:false,
		sm: sm2,
		plugins: [filters],
       
        height:380,
        width:775,
		layout: 'fit',
		listeners: {
            render: {
                fn: function(){
                    store.reload({
                        params: {
                            start: 0,
                            limit: 10 
                        }
                    });
                }
            }
        },
		tbar: [{
            	iconCls: 'icon-add',
           		text: 'New Book',
            	handler: function() {
               location.href= "addedit-book.php"; }
          
        	},'-',
           { 
            text: 'Delete Book',
            
            handler: confirmdeletebook,   
            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();
            } 
        }  
    ]);
	
	var BookWindow = new Ext.Window({
        title: 'View Book Information',
        height: 380,
        width: 785,
        layout: 'fit',
		closeAction:'close',
		modal:true,
		collapsible:'true',
        items: grid,
		border:false
    });
	var varWidth =  (screen.width - BookWindow.width)/2;
	BookWindow.setPosition(varWidth,((screen.height/4)-110));
	BookWindow.show();
});