<?php 
	require "_header.php";
	require "includeGridFilters.php";
	require "data/combo_student.php";
	$username = $_SESSION["VedantnrUserName"];
?>
<div id="main-content" > 
<!-- start custom CSS/JS -->
<script type="text/javascript">
	var username = '<?php echo $username; ?>';
</script>
<script src="js/login-confirm.js" type="text/javascript"></script>
<script type="text/javascript">
var loadingMask = new Ext.LoadMask(Ext.getBody(), {msg:"Loading data, please wait...",id:"loadingMask"});

function deletedata()
	{
		var grid = Ext.getCmp('grid');
		var selections = grid.selModel.getSelections();
		 var prez = [];
         for(i = 0; i< grid.selModel.getCount(); i++){
          prez.push(selections[i].json.student_id);
		 }
         var encoded_array = Ext.encode(prez);
         Ext.Ajax.request({  
            waitMsg: 'Please Wait',
            url: 'data/student-grid-delete.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');      
              }
         });
	}

Ext.onReady(function(){
	 loadingMask.show();
	 Ext.QuickTips.init();
 	 var xg = Ext.grid;
	 var sm2 = new xg.CheckboxSelectionModel({
        listeners: {
            selectionchange: function(sm) {
                if (sm.getCount() ) {
					 if(flgDelete == "true"){
						grid.removeButton.enable();
					 }
			   } else {
                    grid.removeButton.disable();
                }
            }
        }
    });  	
					 
	var url = {
        local:  'grid-filter.json', 
        remote: 'data/view-student-grid-filter.php'
       }; 
	var encode = false;
	var local = false;
 
	function confirmDeleteStudents(){
		
			var selections = grid.selModel.getSelections();
         	var prez = [];
         	for(i = 0; i< grid.selModel.getCount(); i++){
          	prez.push(selections[i].json.student_id);
			}
            var encoded_array = Ext.encode(prez);
			
			Ext.Ajax.request({
				loadMask: true,
				sync : true,
				url: 'data/getRelatedRecord.php',
				params: {action:'student',student_id: encoded_array},
				success: function(resp){
					var str = "";
					resbool=resp.responseText;
					if(resbool != ""){
						str = "It has related record in " + resbool +" Please Delete This Record First";
								Ext.MessageBox.show({
									title: 'Error',
									msg: str,
									buttons: Ext.MessageBox.OK,
									icon:Ext.MessageBox.ERROR
								});	
					}
					else{
						Ext.MessageBox.confirm('Confirmation', ' Are you sure want to delete This Record.?', deleteStudents);
					}
				}				
			});		
	} 
	
	function deleteStudents(btn){
		if(btn == 'yes'){
			loginWindow.show();
      	}  
  	}
	
    function formatDate(value){
		
		var temp = value.dateFormat('d/m/Y');
		if(temp=="28/02/1900")
		{
			return '';
		}
		else
		{
        	return temp;
		}
    }
	
	
  
  
var sec;
store = new Ext.data.JsonStore({
    	autoDestroy: true,
		url:'data/view-student-grid-filter.php',
        remoteSort: true,
        storeId: 'myStore',
        idProperty: 'student_inquiry_id',
        root: 'data',
        totalProperty: 'total',
        fields: [{
            name: 'student_inquiry_id',
			type:'int'
        }, {
            name: 'branch_id'
        }, {
            name: 'semester_name'
        },{
            name: 'cur_divison'
        },  {
            name: 'studentname'
        },{
            name: 'student_gender'
        },{
            name: 'student_admdate',
			type: 'date',
            dateFormat: 'Y-m-d'
        }, {
            name: 'student_birthdate',
			type: 'date',
            dateFormat: 'Y-m-d'
        }, {
            name: 'student_category'
        },
		{
            name: 'student_admby'
        },
		{
			name: 'student_phoneo'	
		},
		{
			name: 'student_phoner'	
		}
		] 
    });

	
	
 var branchstore = new Ext.data.ArrayStore({
		fields: ['branch_id', 'branch_name'],
		data: Ext.student.branch1
  	}); 
	
  var semesterstore = new Ext.data.ArrayStore({
		fields: ['semester_id', 'semester_name'],
		data: Ext.student.semester
  	}); 
	
var divisionstore = new Ext.data.ArrayStore({
    	fields:['division_id','division_name'],
		data: Ext.student.division
	});	  
	
var BranchCombo = {
    xtype: 'combo',
    store: branchstore,
	id:'branch_id',
    displayField: 'branch_name',
    valueField: 'branch_id',
    editable: false,
    mode: 'local',
    forceSelection: true,
    triggerAction: 'all',
    //emptyText: 'Select a Branch...',
    selectOnFocus: true,
	width:100,
    listeners: {
        'select': function(cmb, rec, idx) {
				 sec = this.getValue(),
				 Ext.getCmp('division_id').reset();
                 store.load({params: { 'branch_id': this.getValue(),start:0,limit:10}
			});
        }
    }}
	
var SemesterCombo = {
    xtype: 'combo',
    store: semesterstore,
	id:'semester_id',
    displayField: 'semester_name',
    valueField: 'semester_id',
    editable: false,
    mode: 'local',
    forceSelection: true,
    triggerAction: 'all',
    //emptyText: 'Select a Smester...',
    selectOnFocus: true,
	width:100,
    listeners: {'select': function(cmb, rec, idx) {
		Ext.getCmp('division_id').reset();
		var branch=Ext.getCmp('branch_id').getValue();
		divisionstore.filter('division_id',branch+cmb.getValue(),false,true,true);
		var cnt=divisionstore.getCount();
											if(cnt==1)
											{
												Ext.getCmp('division_id').setValue(divisionstore.getAt(0).data.division_name);
											}
											
				 if(Ext.getCmp('branch_id').getValue()!="")
				 {
	 store.load({params: {'branch_id': Ext.getCmp('branch_id').getValue(),'semester_id': this.getValue(),start:0,limit:10}});
				 }else{
				 alert('Select Branch First')
				 this.reset();
				 }
        }
    }}
	

var DivisionCombo = {		
						xtype: 'combo',
						name: 'division_id',
						id:'division_id',
						labelSeparator:'',	
						fieldLabel :'Division :<span class="comp">*</span>' ,
						forceSelection:true,				
						displayField:'division_name',
						valueField: 'division_name'
						,lastQuery:''
						,allowBlank:false
						,triggerAction:'all'
						,mode:'local'
						,store:divisionstore
						,width:100
						,selectOnFocus: true,
						listeners: {'select': function(cmb, rec, idx) {
						 if(Ext.getCmp('branch_id').getValue()!="" && Ext.getCmp('semester_id').getValue()!="" )
						 {
							 store.load({params: {
									'branch_id': Ext.getCmp('branch_id').getValue(),
									'semester_id':Ext.getCmp('semester_id').getValue(),
									'division_id': this.getValue(),
									start:0,limit:10}});
										 }else{
										 alert('Select Branch And Semester First')
										 this.reset();
										 }
						}
    }
				  }


    var filters = new Ext.ux.grid.GridFilters({
        encode: encode,
        local: false,                                      
		filters: [{
            type: 'numeric',
            dataIndex: 'student_id'
        },  {
            type: 'string',
            dataIndex: 'student_gturegno'
        },  {
			type:'list',
            dataIndex: 'section_name',
			labelField:'section_name',
			store : branchstore,
            phpMode: true
	    },  {
            type: 'string',
            dataIndex: 'semester_name',
			labelField:'semester_name'
        },{
            type:'string',
            dataIndex: 'studentname',
             phpMode: true
        }, {
            type: 'list',
            dataIndex: 'student_active',
			options : ['Yes','No'],
			 phpMode: true
        }, {
            type: 'list',
            dataIndex: 'student_gender',
			options : ['Male','Female'],
			 phpMode: true
        }, {
			type:'list',
            dataIndex: 'student_category',
			options: [{id:'GENERAL',text:'GENERAL'},
					   {id:'OBC',text:'OBC'},
					   {id:'SC',text:'SC'},
					   {id:'ST',text:'ST'},
					   {id:'MINORITY',text:'MINORITY'} ],
            phpMode: true
        },{
            type: 'date',
            dataIndex: 'student_admdate'
        }
		,{
            type: 'date',
            dataIndex: 'student_birthdate'
        }
		,
		{
            type: 'list',
            dataIndex: 'student_admby',
			options : ['ACPDC','M.Q','V.Q'],
			 phpMode: true
        }]
    });  
	
var createColModel = function (finish, start) {
        var columns = [
		sm2,
		{
			header: "Edit",	
			id:'btnEdit',
			width:30,
		    renderer: function(value, metaData, record, rowIndex, colIndex, store) {
    	   		return '<a href="addedit-student.php?ID='+ record.get('student_id') +'">Edit</a>';
			}
		},
		{
            dataIndex: 'student_id',
            header: 'Student ID', 
			width:80,
			hidden:true,
	        filterable: true
        }, {
            dataIndex: 'student_gturegno',
            header: 'Enrollment No',
			width:90,
            filterable: true
        }, {
            dataIndex: 'semester_name',
            header: 'Semester',
			width:60
        },{
            dataIndex: 'cur_divison',
            header: 'Div',
			width:40
        },{
            dataIndex: 'studentname',
            header: 'Student Name',
            id: 'SurName', 
            filter: {type: 'string'},
			width:210
        }, {
            dataIndex: 'student_admdate',
            header: 'Admis. Date',
			width:70,
			renderer:formatDate,
            filter: {
            }
        },
		<?php if($_SESSION["VedantnrUserRole"]!='Faculty' && $_SESSION["VedantnrUserRole"]!='Hod') { ?>
		{
            dataIndex: 'student_birthdate',
            header: 'Birth Date',
			width:70,
			renderer:formatDate,
            filter: {
            }
        }, <?php } ?> {
            dataIndex: 'student_gender',
            header: 'Gen',
            id: 'Gender',
			width:40
        }, {
            dataIndex: 'student_category',
            header: 'Category',
			width:65,
            filter: {
            }            
        },{
            dataIndex: 'student_admby',
            header: 'Adm By',
			width:50,
            filter: {
            }            
        },{
            dataIndex: 'student_mobilestudents',
            header: 'Mob.Student',
			width:80,
            filter: {
            }            
        },{
            dataIndex: 'student_mobileparents',
            header: 'Mob.Parents',
			width:80,
            filter: {
            }            
        } ];
		
		return new Ext.grid.ColumnModel({
            columns: columns.slice(start || 0, finish),
            defaults: {
                sortable: true
            }
        });
    };
var grid = new Ext.grid.GridPanel({
		id:'grid',
		name:'grid',
        store: store,
        colModel: createColModel(40), 
        loadMask: true,
		frame: true,
		enableColLock:false,
		columnLines:true,
	    height: 460,    
        width: 900,
        layout: 'fit',
    	selModel: new Ext.grid.RowSelectionModel({singleSelect:false}),
		listeners: {
            render: {
                fn: function(){
					if(Ext.getCmp('branch_id').getValue()!="")
					{
						alert(Ext.getCmp('division_id').getValue());
                    	store.reload({
							params: {
								'branch_id': Ext.getCmp('branch_id').getValue(),
								'semester_id':  Ext.getCmp('semester_id').getValue(),
								'division_id':  Ext.getCmp('division_id').getValue(),
								start: 0,
								limit: 10   
							}
						});
					}
                }
            }
        },
        plugins: [filters],
		sm: sm2,
       	tbar: [{
            	iconCls: 'icon-add',
           		text: 'Add Student',
				id:'btnAdd',
            	handler: function() {
               location.href='addedit-student.php'; 
			   }
        	},'-',
           { 
            text: 'Delete Student',
			id:'btnDelete',
            handler: confirmDeleteStudents, 
            iconCls:'remove',
			ref: '../removeButton',
			disabled: true
      		},' | ',{xtype: 'tbtext',text: 'Branch:'},' ',BranchCombo,{width:3},
			{xtype: 'tbtext',text: 'Semester:'},' ',SemesterCombo,{width:3},
			{xtype: 'tbtext',text: 'Division:'},' ',DivisionCombo
	  ], 
        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,
				branch_id: Ext.getCmp('branch_id').getValue(),
				semester_id:  Ext.getCmp('semester_id').getValue(),
				division_id:  Ext.getCmp('division_id').getValue()
            });
        },
        scope: this
    }
});


 	var StudentWindow = new Ext.Window({
        title: 'View Student Information',
        height: 415,
        width: 960,
        layout: 'fit',
		modal:true,
		border: false,
		closeAction:'close',
		collapsible:'true',				
		items: grid
    })
	 
	var varWidth =  (screen.width - StudentWindow.width)/2;
	StudentWindow.setPosition(varWidth,((screen.height/4)-85));	 
	StudentWindow.show();
	loadingMask.hide();


	if(flgAdd == "true"){
		Ext.getCmp('btnAdd').enable();
	}
	else{
		Ext.getCmp('btnAdd').disable();
	}
	
	if(flgEdit == "false"){
		grid.getColumnModel().setHidden(1, true);
	}
	Ext.getCmp('branch_id').focus(true,1000);
});
</script>
<!-- end custom CSS/JS -->
<div id="abcd" align="center"></div>
</div>
<?php require "_footer.php";?>
