Ext.onReady(function(){
    
	Ext.QuickTips.init();
	
	var designationObj = Ext.data.Record.create([
    	{name: 'designation_id'},
        {name: 'designation_name'}
   	]);
	
	var designationstore = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy
			({
            	url: 'data/getdesignation.php',
				success: function(response,options){
                	var json = Ext.util.JSON.decode(response.responseText);
            	} 
       		}),
			reader: new Ext.data.JsonReader({
			root: 'rows',
			id: 'designation_id',
			labelField:'designation_name'
			},designationObj)
		});
	
	var xg = Ext.grid;
	
	var sm2 = new xg.CheckboxSelectionModel({
 		listeners: {
			selectionchange: function(sm) {
            	if (sm.getCount()) {
                    grid.removeButton.enable();
                } else {
                    grid.removeButton.disable();
                }
            }
        }
    });  

	var encode = false;
    var local = false;
   	
	function confirmDeleteEmployees(){
		var selections = grid.selModel.getSelections();
      	var prez = [];
        for(i = 0; i< grid.selModel.getCount(); i++){
        	prez.push(selections[i].json.employee_id);
		}
        var encoded_array = Ext.encode(prez);
		
		Ext.Ajax.request({
			loadMask: true,
			sync : true,
			url: 'data/getalltableemp.php',
			params: {employee_id: encoded_array},
			success: function(resp) {
				resbool=resp.responseText;
				if(resbool){
					Ext.MessageBox.confirm('Confirmation','It has related record in ' + resbool +' Are you sure want to delete.?', deleteEmployees);
				}	 			
			}				
		});	
	} 
	
	function deleteEmployees(btn){
    	if(btn=='yes'){
        	var selections = grid.selModel.getSelections();
         	var prez = [];
         	for(i = 0; i< grid.selModel.getCount(); i++){
         	 	prez.push(selections[i].json.employee_id);
         	}
         	var encoded_array = Ext.encode(prez);
         	Ext.Ajax.request({  
            	waitMsg: 'Please Wait',
            	url: 'data/employee-grid-delete.php', 
            	params: { 
               		task: "DELETEEMP", 
               		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/employee-grid-filter.php',
        remoteSort: true,
       	sortInfo:{ field: 'employee_id',direction: 'ASC' },
        storeId: 'myStore',
        idProperty: 'employee_id',
        root: 'data',
        totalProperty: 'total',
        fields:[
		{
        	name:'employee_id', 
			type:'int'
        },{
            name: 'employee_name'
        },{
            name: 'employee_address'
        },{
            name: 'employee_phone'
        },{
            name: 'employee_mobile'
        },{
            name: 'employee_email'
        },{
            name: 'employee_salary',
			type:'int'
		},{
            name: 'employee_birthdate', 
			type: 'date', 
			dateFormat: 'Y-m-d'
		},{
            name: 'employee_joindate', 
			type: 'date', 
			dateFormat: 'Y-m-d'
		},{
            name: 'designation_name'
        }] 
    });
    
	var filters = new Ext.ux.grid.GridFilters({
		encode: encode, 
        local:false,                                      
		filters: [{
			type: 'numeric',
            dataIndex: 'employee_id'
        },{
            type:'string',
            dataIndex: 'employee_name'
        },{
            type:'string',
            dataIndex: 'employee_phone'
        },{
            type:'string',
            dataIndex: 'employee_mobile'
        },{
            type:'string',
            dataIndex: 'employee_email'
        },{
            type:'numeric',
            dataIndex: 'employee_salary'
        },{
            type:'date',
            dataIndex: 'employee_birthdate'
        },{
            type:'date',
            dataIndex: 'employee_joindate'
		},{
            type:'list',
            dataIndex: 'designation_name',
			store : designationstore,
			labelField:'designation_name',
            phpMode: true
        }]
    });    

	var createColModel = function (finish, start) {
    	var columns = [
		sm2,
		{
			header: "Edit",	
			width:35,
		    renderer: function(value, metaData, record, rowIndex, colIndex, store) {
		   		return '<a href="addedit-employee.php?ID='+ record.get('employee_id') +'">Edit</a>';
			}
		},
		{
 			dataIndex:'employee_id',
            header:'Employee ID',
			align:'center',
			hidden:true
		},{
            dataIndex: 'designation_name',
            header: 'Designation',
			width:70,
			align:'center'
		},{
            dataIndex: 'employee_name',
            header: 'Name',
			width:130
		},{
            dataIndex: 'employee_address',
            header: 'Address',
			width:100
		},{
            dataIndex: 'employee_phone',
            header: 'Phone No',
			width:75
		},{
            dataIndex: 'employee_mobile',
            header: 'Mobile No',
			width:75
		},{
            dataIndex: 'employee_email',
            header: 'Email ID',
			width:175
		},{
            dataIndex: 'employee_salary',
            header: 'Salary',
			width:50
		},{
            dataIndex: 'employee_birthdate',
			align:'center',
            header: 'Birth Date',
			renderer: Ext.util.Format.dateRenderer('d/m/Y'),
			width:65
		},{
            dataIndex: 'employee_joindate',
			align:'center',
            header: 'Joining Date',
			renderer: Ext.util.Format.dateRenderer('d/m/Y'),
			width:75
        }];
		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: 775,
        //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 Employee',
				handler: function() {
               		location.href="addedit-employee.php"; 
				}
      		},'-',
			{
				text: 'Delete Employee',
            	handler: confirmDeleteEmployees,  
            	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.";
				}
			}
		});
  	});
	
	store.on({
		'beforeload': {
    		fn: function(store, options){
            	options.params || (options.params = {}); 
            	Ext.apply(options.params, {
            		pageNo: this.pageNumber
            	});
        	},
        	scope: this
    	}
	});
	
	var ViewEmployeeWindow = new Ext.Window({
        title: 'View Employee Information',
        height: 360,
        width: 915,
		modal:true,
        layout: 'fit',
		closeAction:'close',
		border: false,
		collapsible:'true',
		items: grid
    }).show();
	
	var varWidth =  (screen.width - ViewEmployeeWindow.width)/2;
	ViewEmployeeWindow.setPosition(varWidth,((screen.height/4)-100));
});