Ext.onReady(function(){
    	
	Ext.QuickTips.init();
	
	var member = Ext.data.Record.create([
   	       {name: 'member_group'},
		   {name: 'member_group'}
    ]);
	
	var groupstore = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy
			({
            	url: 'data/getgroupmembername.php', 
				success: function(response,options){
                	var json = Ext.util.JSON.decode(response.responseText);
            	} 
       		}),
        reader: new Ext.data.JsonReader({
			root: 'rows1',
			id: 'member_group',
			labelField:'member_group'
		},member)
	});
	
	groupstore.load();
	
 	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 confirmDeleteMembers(){
		var selections = grid.selModel.getSelections();
        var prez = [];
        for(i = 0; i< grid.selModel.getCount(); i++){
         	prez.push(selections[i].json.member_id);
		}
        var encoded_array = Ext.encode(prez);
		Ext.Ajax.request({
			loadMask: true,
			sync : true,
			url: 'data/getMemberRelatedRecord.php',
			params: {member_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.?', deleteMembers);
				
				
			}				
		});		
	} 
	
	function deleteMembers(btn){
    	if(btn=='yes'){
        	var selmembers = grid.selModel.getSelections();
         	var prez = [];
		 	var sec = [];
         	for(i = 0; i< grid.selModel.getCount(); i++){
          		prez.push(selmembers[i].json.member_id);
		  		
		  	}
         	var encoded_array = Ext.encode(prez);
		 	
         	Ext.Ajax.request({  
            	waitMsg: 'Please Wait',
            	url: 'data/delete-member-data.php', 
            	params: { 
               		task: "DELETESTU", 
               		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');      
              	}
         	});
      }  
  }
	
	store = new Ext.data.JsonStore({
    	autoDestroy: true,
        url:'data/view-member-data.php',
        remoteSort: true,
       	sortInfo: {
            field: 'member_id',
            direction: 'ASC'
        },
        storeId: 'myStore',
        idProperty: 'student_id',
        root: 'data',
        totalProperty: 'count',
        fields: [
				 	{
						name: 'member_id',
						type:'int'
					}, {
						name:'member_registerno',
						type:'int'
					}, {
						name:'member_group',
						type:'string'
					}, {
						name:'member_name',
						type:'string'
					}, {
						name:'member_address',
						type:'string'
					}, {
						name:'member_phone',
						type:'int'
					}, {
						name: 'member_mobileno',
						type:'int'
					}, {
						name: 'member_refby',
						type:'string'
					}, {
						name: 'member_refaddress',
						type:'string'
					}, {
						name: 'member_refphone',
						type:'int'
					}, {
						name: 'member_approvedfrom',
						type:'date',
						 dateFormat: 'Y-m-d'
					}, {
						name: 'member_approvedto',
						type:'date',
						 dateFormat: 'Y-m-d'
					},{
						name: 'member_maxissuelimit',
						type:'int'
					}, {
						name: 'member_remark',
						type:'string'
					}
			] 
    });

	var filters = new Ext.ux.grid.GridFilters({
		filters:[
					{
						type: 'numeric',
						dataIndex: 'member_id'
					},{
						type: 'numeric',
						dataIndex: 'member_registerno'
					},  {
						type: 'list',
						dataIndex: 'member_group',
						labelField:'member_group',
						store : groupstore,
						phpMode: true
					},  {
						type: 'string',
						dataIndex: 'member_name'
					},  {
						type: 'string',
						dataIndex: 'member_phone'
					}, {
						type:'string',
						dataIndex: 'member_refby'
					}, {
						dataIndex: 'member_refphone',
						type:'string'
					},  {
						type: 'string',
						dataIndex: 'member_mobileno'
					},  {
						type: 'date',
						dataIndex: 'member_approvedfrom'
					},  {
						type: 'date',
						dataIndex: 'member_approvedto'
					},  {
						type: 'numeric',
						dataIndex: 'member_maxissuelimit'
					}
				]
    });
	
	var createColModel = function (finish, start) {
        var columns = [
		sm2,
		{
			header: "Edit",	
			width:30,
		   renderer: function(value, metaData, record, rowIndex, colIndex, store) {
    	    		return '<a href="addedit-member.php?ID='+ record.get('member_id') +'">Edit</a>';
			}
		},
		{
            dataIndex: 'member_id',
            header: 'Member ID', 
			hidden:true,
	        filterable: true
        }, {
            dataIndex: 'member_registerno',
            header: 'Reg.No.',
            filterable: true
        }, {
            dataIndex: 'member_group',
            header: 'Group Name',
            filterable: true
        }, {
            dataIndex: 'member_name',
            header: 'Member Name'
        }, {
            dataIndex: 'member_address',
            header: 'Member Address'

		},  {
            dataIndex: 'member_phone',
            header: 'Phone No',
			width:70
        },  {
            dataIndex: 'member_mobileno',
            header: 'Mobile No',
			width:70
        },{
            dataIndex: 'member_refby',
            header: 'Reference By'
        }, {
            dataIndex: 'member_refaddress',
            header: 'Ref.Address'
        }, {
            dataIndex: 'member_refphone',
            header: 'Ref. Phone',
			width:70
        }, {
            dataIndex: 'member_approvedfrom',
            header: 'Approved From',
			renderer: Ext.util.Format.dateRenderer('d/m/Y'),
			width:90
        },{
            dataIndex: 'member_approvedto',
            header: 'To',
			renderer: Ext.util.Format.dateRenderer('d/m/Y'),
			width:70
        }, {
            dataIndex: 'member_maxissuelimit',
            header: 'Max Issue Limit',
			align:'center',
			width:90
        }, {
            dataIndex: 'member_remark',
            header: 'Remark'
        }];
		
		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,
	    height: 360,    
        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: [{
            	iconCls: 'icon-add',
           		text: 'Add Member',
            	handler: function() {
               location.href='addedit-member.php'; 
			   }
        	},'-',
           { 
            text: 'Delete Member',
            handler: confirmDeleteMembers, 
            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 MemberWindow = new Ext.Window({
        title: 'View Library Member Information',
        height: 360,
        width: 800,
        layout: 'fit',
		closeAction:'close',
		modal:true,
		collapsible:'true',
		
		border:false,
		bodyBorder:false,
		items: grid
    });
	var varWidth =  (screen.width - MemberWindow.width)/2;
	MemberWindow.setPosition(varWidth,((screen.height/4)-110));
	MemberWindow.show();
});