var labelArray;
labelArray = [
			 	['Book Issue No. :'],
				['Issue Date :<span class="comp">*</span>'],
				['Book Register :<span class="comp">*</span>'],
				['Member Type :<span class="comp">*</span>'],
				['Student Section :'],
				['Member Id :<span class="comp">*</span>'],
				['Member Name :<span class="comp">*</span>'],
				['Total Issueable Book:<span class="comp">*</span>'],
				['Total Issued Book :<span class="comp">*</span>'],
				['Book Reg. No :<span class="comp">*</span>'],
				['Book Name :<span class="comp">*</span>'],
				['Return Date :<span class="comp">*</span>']
			];

Ext.onReady(function(){
	Ext.QuickTips.init();
 	
	var win;
	
	var dt = new Date();

	var xg = Ext.grid;
	
	var sectionstore = new Ext.data.ArrayStore({
		fields: ['section_id','section_name'],
		data: Ext.student.section
	});
	
	var sm2 = new xg.CheckboxSelectionModel({
        listeners: {
            selectionchange: function(sm){
				if (sm.getCount() && flgDelete=='true') {
                    issuebooklist.removeButton.enable();
                } else {
                    issuebooklist.removeButton.disable();
                }
            }
        }
    });
	
	var storeissuebooklist = new Ext.data.JsonStore({
		 idProperty: 'book_regno',
		fields: ['book_id','book_regno','book_name',{name:'book_retdate',type:'date'}]
		 
	});
	
	var issuebooklist = new Ext.grid.GridPanel({
    	store: storeissuebooklist,
		sm: sm2,
		columns: [
			{	
				header    : 'Book Reg No',
				dataIndex : 'book_regno',
				width:.2
			},
			{	
				header    : 'Book Name',
				dataIndex : 'book_name',
				width:.6
			},
			{	
				header    : 'Return Date',
				dataIndex : 'book_retdate',
				width     : .2
			},sm2
		],
    	autoExpandColumn: 'title-col',
   		height: 228,
   		loadMask: true,
    	columnLines: true,
    	viewConfig: {
        	forceFit: true
    	},
		tbar: [{},'->',
        	{
				text: 'Delete',
            	handler: confirmDeleteSelection,  
            	iconCls:'remove',
				ref: '../removeButton',
				disabled: true
			}
	  	] 
	});
	
	var storemembercategory= new Ext.data.ArrayStore({
    	fields: ['val_membercategory','dis_membercategory'],
	    data: [['1','Student'],['2','Employee'],['3','Other']]
    });
	
	var registerstore = new Ext.data.ArrayStore({
		fields: ['register_id','register_name'],
		data: Ext.library.register	
	});
	
	var fieldset2 = Ext.apply({
		autoScroll : true,
		border: false,
		items : [issuebooklist]
	});
	
	var fieldset1 = {
		xtype       : 'fieldset',
		id			: 'fieldset1',
		name		: 'fieldset1',
		defaultType : 'field',
		labelWidth  : 125,
		border: false,
		items : [
			{
				xtype       : 'container',
				autoEl      : {},
				layout      : 'column',
				defaultType : 'field',
				items       : [
					{
						xtype  : 'container',
						autoEl : {},
						layout : 'form',
						columnWidth : .5,
						items  : [
							{
								xtype      : 'textfield',
								labelSeparator:'',	
								fieldLabel :labelArray[0] ,
								name       : 'txtbookissueno',
								id         : 'txtbookissueno',
								hiddenName:'registerno',
								disabled:true,
								readOnly   : true,
								width      : 80,
								autoCreate : {tag: 'input', type: 'text',  maxlength: '10'}
							}
						]
					
					},
					{
						xtype       : 'container',
						autoEl      : {},
						layout      : 'form',
						columnWidth : .5,
						labelWidth  : 80,
						items       : [
							{ 
								xtype: 'datefield',
								name: 'book_issuedate',
								id:'book_issuedate',
								labelSeparator:'',	
								fieldLabel :labelArray[1] ,
								value:dt,
								maxValue:new Date('<?php echo date("d M Y H:i:s")?>'),
						     	vtype: 'daterange',
								endDateField: 'book_returndate'
							}			
						]
					}
								
				]
			
			},
			{
				xtype: 'combo',
				name: 'book_registerid',
				id:'book_registerid',
				labelSeparator:'',	
				fieldLabel :labelArray[2] ,
				hiddenName:'registerid',				
				displayField:'register_name',
				valueField:'register_id',
				width:200,
				cancelable:true,
				forceSelection:true,
				
				disabled:true,
				triggerAction:'all',
				mode:'local',
				selectOnFocus: true,
				store: registerstore
			},
			{
				xtype       : 'container',
				autoEl      : {},
				layout      : 'column',
				defaultType : 'field',
				items       : [
					{
						xtype  : 'container',
						autoEl : {},
						layout : 'form',
						columnWidth : .43,
						items  : [
							{
								xtype: 'combo',
								name: 'membercategory',
								id:'membercategory',
								labelSeparator:'',	
								fieldLabel :labelArray[3] ,
								forceSelection:true,
								displayField:'dis_membercategory',
								valueField: 'val_membercategory',
								hiddenName:'member_type',
								
								triggerAction:'all',
								editable:true,
								mode:'local',
								width: 80,
								disabled   : true,
								store: storemembercategory
							}
						]
					
					},
					{
						xtype       : 'container',
						autoEl      : {},
						layout      : 'form',
						columnWidth : .57,
						labelWidth  : 160,
						items       : [
							{
								xtype : 'button',
								autoEl : {},
								layout : 'form',
								columnWidth : .1,
								name: 'search_grno',
								id:'search_grno',
								iconCls: 'icon-search',
								tooltip: 'Find Member',
								fieldLabel:'',
								disabled:true,
								handler: function (){
									if(Ext.getCmp('membercategory').getValue()!=""){
										OpenSearchWindow(); 
									}
									else{
										Ext.MessageBox.show({
					   						title: 'Error',
											msg: 'Please Select Member Type.',
											buttons: Ext.MessageBox.OK,
											icon:Ext.MessageBox.ERROR
					  					});
									}
								}
		                	}			
						]
					}
								
				]
			
			},
			{
				xtype:'combo',
				name:'student_section',
				id:'student_section',
				hiddenName:'hidsection',
				store: sectionstore,
				displayField: 'section_name',
				valueField: 'section_id',
				typeAhead: true,
				editable:false,
				mode: 'local',
				forceSelection: true,
				triggerAction: 'all',
				labelSeparator:'',	
				fieldLabel :labelArray[4] ,
				selectOnFocus: true,
				disabled: true,
				width:180	
			},
			{
				xtype      : 'numberfield',
				labelSeparator:'',	
				fieldLabel :labelArray[5] ,
				name       : 'grno',
				id         : 'txtgrno',
				width      : 80,
				disabled   : true,
				autoCreate : {tag: 'input', type: 'text',  maxlength: '10'}
			},
			{
				labelSeparator:'',	
				fieldLabel :labelArray[6] ,
				name       : 'membername',
				id         : 'membername',
				disabled   : true,
				readOnly   : true, 
				width      : 200,
				autoCreate : {tag: 'input', type: 'text',  maxlength: '50'}
			},
			{
				xtype       : 'container',
				autoEl      : {},
				border      : false,
				layout      : 'column',
				defaultType : 'field',
				items       : [
					{
						xtype       : 'container',
						autoEl      : {},
						layout      : 'form',
						columnWidth : .5,
						labelWidth  : 125,
						items       : [
							{
								xtype      : 'textfield',
								labelSeparator:'',	
				fieldLabel :labelArray[7] ,
								name       : 'txttotalIssueablebook',
								id         : 'txttotalIssueablebook',
								readOnly   : true,
								disabled   : true,
								width      : 30,
								autoCreate : {tag: 'input', type: 'text',  maxlength: '10'}
							}			
						]
					},
					{
						xtype  : 'container',
						autoEl : {},
						layout : 'form',
						columnWidth : .5,
						labelWidth:125,
						items  : [
							{
								xtype      : 'textfield',
								labelSeparator:'',	
								fieldLabel :labelArray[8] ,
								name       : 'txttotalissuedbook',
								id         : 'txttotalissuedbook',
								readOnly   : true,
								disabled   : true,
								width      : 30,
								autoCreate : {tag: 'input', type: 'text',  maxlength: '10'}
							}
						]
					
					}
								
				]
			
			},
			{
				xtype       : 'container',
				autoEl      : {},
				layout      : 'column',
				defaultType : 'field',
				items       : [
					{
						xtype  : 'container',
						autoEl : {},
						layout : 'form',
						columnWidth : .2,
						labelAlign:'top',
						items  : [
							{
								xtype      : 'textfield',
								labelSeparator:'',	
								fieldLabel :labelArray[9] ,
								name       : 'txtbookregno',
								id         : 'txtbookregno',
								width      : 80,
								disabled   : true,
								autoCreate : {tag: 'input', type: 'text',  maxlength: '10'}
							}
						]
					
					},
					{
						xtype  : 'container',
						autoEl : {},
						layout : 'form',
						columnWidth : .43,
						labelAlign:'top',
						items  : [
							{
								xtype      : 'textfield',
								labelSeparator:'',	
								fieldLabel :labelArray[10] ,
								name       : 'txtbookname',
								readOnly   : true,
								id         : 'txtbookname',
								width      : 200,
								disabled   : true,
								autoCreate : {tag: 'input', type: 'text',  maxlength: '10'}
							}
						]
					
					},
					{
						xtype       : 'container',
						autoEl      : {},
						layout      : 'form',
						columnWidth : .21,
						labelAlign:'top',
						items       : [
							{    
								xtype: 'datefield',
								name: 'book_returndate',
								id:'book_returndate',
								labelSeparator:'',	
								fieldLabel :labelArray[11] ,
								vtype: 'daterange',
							    startDateField:'book_issuedate'
								,disabled   : true
							}
						]
					},
					{
						xtype       : 'container',
						autoEl      : {},
						layout      : 'form',
						columnWidth : .1,
						items       : [
							{   
								xtype: 'button',
								autoEl: {},
								layout: 'form',
								columnWidth: 1,
								name:'btnadd',
								id:'btnadd',
								text:'Add',
								disabled:true,
								tooltip:'Add Book',
								style:{margin:'16px 0px 0px 5px'},
								handler: function (){
									var rem_book = Ext.getCmp('txttotalIssueablebook').getValue()-Ext.getCmp('txttotalissuedbook').getValue();
									if(rem_book>storeissuebooklist.getCount()){
										if(Ext.getCmp('txtbookregno').getValue()!="" && 
										   Ext.getCmp('txtbookname').getValue()!="" && 
										   Ext.getCmp('book_returndate').getValue()!=""){
											var div_all_record = {
												book_regno : Ext.getCmp('txtbookregno').getValue(),
												book_name  : Ext.getCmp('txtbookname').getValue(),
												book_retdate : Ext.getCmp('book_returndate').getRawValue(),
												book_id : Ext.getCmp('book_id').getValue()
											};
											var storecount = storeissuebooklist.getCount();
											div_all_record_modified = new storeissuebooklist.recordType(div_all_record,storecount);
											storeissuebooklist.insert(storecount, div_all_record_modified);
											Ext.getCmp('txtbookregno').reset();
											Ext.getCmp('txtbookname').reset();
											Ext.getCmp('book_returndate').reset();
										}
										else{
											Ext.MessageBox.show({
												title: 'Error',
												msg:'Please fill all require information.',
												buttons: Ext.MessageBox.OK,
												icon:Ext.MessageBox.ERROR
										
											});
										}
									}
									else{
										Ext.MessageBox.show({
											title: 'Error',
											msg:'You are selected maximum book limit.',
											buttons: Ext.MessageBox.OK,
											icon:Ext.MessageBox.ERROR
										});
									}
								}
		                  	}			
						]
					},
					{
						xtype  : 'container',
						autoEl : {},
						layout : 'form',
						columnWidth : .06,
						labelAlign:'top',
						items  : [{
							xtype: 'textfield',
							name: 'griddata',
							id:'griddata',
							hidden:true
						},{
							xtype: 'textfield',
							name: 'book_id',
							id:'book_id',
							hidden:true
						}
						,{
							xtype: 'textfield',
							name: 'member_id',
							id:'member_id',
							hidden:true
						}
						]
					}
				]
			
			}
		]
	}
	
	var BookIssueForm= new Ext.FormPanel({
		id: 'myFormPanel',
		url:'save-book-issue.php',
		method:'post',
		align:"center",
        frame:true,
        bodyStyle:'padding:5px 5px 0',
		items	:[fieldset1,fieldset2]
	});
	
	var buttons = [
		{   
			text:'Add New',
			name:'btnAdd',
			id:'btnAdd',
			handler: function(){
				Ext.Ajax.request({
					url: 'data/getIssueGeneralData.php',
					params: {action:'maxissueno'},
					waitMsg:'Loading',
					success: function(resp){
						issueid=Ext.decode(resp.responseText).issueno;
						Ext.getCmp('txtbookissueno').setValue(issueid); 			
					}				
				});
				resetForm()
				Ext.getCmp('btnAdd').disable();
				Ext.getCmp('txtbookissueno').enable();
				Ext.getCmp('book_issuedate').enable();
				Ext.getCmp('book_registerid').enable();
				//Ext.getCmp('book_registerid').focus();
				Ext.getCmp('btnSave').enable();
			 SetLibraryValue('',registerstore,'book_registerid','book_registerid');
			}
		},{
			text: 'Save',
		   	name: 'btnSave',
		   	id: 'btnSave',
		   	handler: function(){
				CopyStoreToForm(storeissuebooklist);
				BookIssueForm.getForm().submit({
					waitMsg: 'Saving...',
					success: function (){
						Ext.getCmp('btnSave').disable();
						resetForm();
					},
					failure: function (){		
						Ext.MessageBox.show({
						   title: 'Error',
						   msg: 'Please fill up complete form.',
						   buttons: Ext.MessageBox.OK,
						   icon:Ext.MessageBox.ERROR
						});
					}
				});
			}
		},{
			text: 'Reset',
			handler: function(){
				resetForm()
			}
		},{
			text: 'Close',
			handler: function(){
				BookIssueWindow.close();
			}
		}
	];
	
	var  BookIssueWindow = new Ext.Window({
			title : 'Book Issue',						
			width:550,		
			height:550,		
			border: false,
			modal:true,
			layout: 'fit',
			closeAction:'close',
			collapsible:true,
			
			items:[BookIssueForm],
			buttonAlign: 'center',
			buttons: buttons
	});

	Ext.getCmp('book_registerid').on('select',function(){
		Ext.getCmp('membercategory').enable();
		Ext.getCmp('txtbookregno').reset();
		Ext.getCmp('txtbookname').reset();
		Ext.getCmp('book_returndate').reset();
		Ext.getCmp('search_grno').enable();
	});
	
	Ext.getCmp('student_section').on('select',function(){
		Ext.getCmp('txtgrno').enable();
		Ext.getCmp('membername').enable();
		Ext.getCmp('txttotalIssueablebook').enable();
		Ext.getCmp('txttotalissuedbook').enable();
	});
	
	Ext.getCmp('membercategory').on('select',function(){
		var vartxtgrno = Ext.getCmp('txtgrno');
		var membername = Ext.getCmp('membername');
		Ext.getCmp('txtgrno').reset();
		Ext.getCmp('membername').reset();
		Ext.getCmp('txttotalIssueablebook').reset();
		Ext.getCmp('txttotalissuedbook').reset();
		cat_name = Ext.getCmp('membercategory').getValue();
		if(cat_name==1){
			Ext.getCmp('student_section').enable();
			vartxtgrno.disable();
			Ext.getCmp('membername').disable();
			Ext.getCmp('txttotalIssueablebook').disable();
			Ext.getCmp('txttotalissuedbook').disable();
			Ext.get(vartxtgrno.getEl().up('div.x-form-item').query('label[for='+vartxtgrno.id+']')[0]).update('Student GR.No:');
			Ext.get(membername.getEl().up('div.x-form-item').query('label[for='+membername.id+']')[0]).update('Student Name:');
		}
		else if(cat_name==2){
			vartxtgrno.enable();
			Ext.getCmp('membername').enable();
			Ext.getCmp('txttotalIssueablebook').enable();
			Ext.getCmp('txttotalissuedbook').enable();
			Ext.getCmp('student_section').reset();
			Ext.getCmp('student_section').disable();
			Ext.get(vartxtgrno.getEl().up('div.x-form-item').query('label[for='+vartxtgrno.id+']')[0]).update('Employee Salary No:');
			Ext.get(membername.getEl().up('div.x-form-item').query('label[for='+membername.id+']')[0]).update('Employee Name:');
		}
		else{
			vartxtgrno.enable();
			Ext.getCmp('membername').enable();
			Ext.getCmp('txttotalIssueablebook').enable();
			Ext.getCmp('txttotalissuedbook').enable();
			Ext.getCmp('student_section').reset();
			Ext.getCmp('student_section').disable();
			Ext.get(vartxtgrno.getEl().up('div.x-form-item').query('label[for='+vartxtgrno.id+']')[0]).update('Member Id:');
			Ext.get(membername.getEl().up('div.x-form-item').query('label[for='+membername.id+']')[0]).update('Member Name:');
		}
	});
	
	Ext.getCmp('txtbookregno').on('blur',function (){
		var bookregno1 = Ext.getCmp('txtbookregno').getValue();
		var bookregid1 = Ext.getCmp('book_registerid').getValue();
		if(bookregno1!=""){
			BookIssueForm.getForm().load({
				params:{bookregno: bookregno1,bookregid: bookregid1},
				url: 'data/getBookData.php',
				waitMsg:'Loading',
				success: function(){
					Ext.getCmp('btnadd').enable();					
					// START code for duplicate check in list
					var duplicate = storeissuebooklist.find('book_id',Ext.getCmp('book_id').getValue());
					if(duplicate!="-1"){
						Ext.MessageBox.show({
						   title: 'Error',
						   msg: 'This book is already selected in list.',
						   buttons: Ext.MessageBox.OK,
						   icon:Ext.MessageBox.ERROR
						});
						Ext.getCmp('txtbookregno').reset();
						Ext.getCmp('txtbookname').reset();
						BookIssueForm.getForm().findField('txtbookregno').focus(true,500);
					}
					// END code for duplicate check in list
					
					returndate();
				},
				failure: function(form,action) {
					var failresponse = action.result.msg;
					if(failresponse==1){
						varmsg='Book already issued.';
					}
					else{
						varmsg='Invalid Book Register No.';
					}
			    	Ext.MessageBox.show({
					   title: 'Error',
					   msg: varmsg,
					   buttons: Ext.MessageBox.OK,
					   icon:Ext.MessageBox.ERROR
					});
				Ext.getCmp('txtbookregno').reset();
				Ext.getCmp('txtbookname').reset();
				Ext.getCmp('book_returndate').reset();
				BookIssueForm.getForm().findField('txtbookregno').focus(true,500);
				
			}});
		}
		else{
			Ext.getCmp('txtbookname').reset();
		}
	});
	
	Ext.getCmp('txtgrno').on('blur',function (){
		Ext.getCmp('membername').reset();
		Ext.getCmp('txttotalIssueablebook').reset();
		Ext.getCmp('txttotalissuedbook').reset();
		
		var varmember_id   = Ext.getCmp('member_id').getValue();
		var membercatid = Ext.getCmp('membercategory').getValue();
		var vartxtgrno  = Ext.getCmp('txtgrno').getValue();
		var sectionid   = Ext.getCmp('student_section').getValue();
		
		if(vartxtgrno!=""){
			BookIssueForm.getForm().load({
				params:{member_id:varmember_id,txtgrno: vartxtgrno,category: membercatid,section: sectionid},
				url: 'data/getMemberData.php',
				waitMsg:'Loading',
				success: function() {			
					Ext.getCmp('txtbookregno').enable();
					Ext.getCmp('txtbookname').enable();
					Ext.getCmp('book_returndate').enable();
					BookIssueForm.getForm().findField('txtbookregno').focus(true,500);
				},
				failure: function() {
			    	Ext.MessageBox.show({
					   title: 'Error',
					   msg: 'Member is not available.',
					   buttons: Ext.MessageBox.OK,
					   icon:Ext.MessageBox.ERROR
					  });
					Ext.getCmp('txtgrno').reset();
					Ext.getCmp('membername').reset();
					Ext.getCmp('txttotalIssueablebook').reset();
					Ext.getCmp('txttotalissuedbook').reset();
				}});
			}
		else
		{
			Ext.getCmp('membername').reset();
		}
	});
	
	Ext.getCmp('book_issuedate').on('blur',function (){
		returndate();										 
	});
	
	Ext.getCmp('btnSave').disable();
	
	function CopyStoreToForm(store){
	  var json = '[';
	  store.each(function(store){
		  json += Ext.util.JSON.encode(store.data) + ',';
	  });
	  json = json.substring(0, json.length - 1);
	  json += ']';
	  Ext.getDom('griddata').value = json
	};
	
	function OpenSearchWindow(){
		if(Ext.getCmp('membercategory').getValue()==3){
			// code for MEMBER SEARCH
			OpenMemberSearch();	
		}
		else if(Ext.getCmp('membercategory').getValue()==2){
			// code for EMPLOYEE SEARCH
			OpenEmployeeSearch();			
		}
		else{
			// code for STUDENT SEARCH
			OpenStudentSearch();
		}
	}
	
	function confirmDeleteSelection(){
		if(issuebooklist.selModel.getCount() == 1) 
		{
		  Ext.MessageBox.confirm('Confirmation','You are about to delete a Book Selection. Continue?', deleteBook);
		} else if(issuebooklist.selModel.getCount() > 1){
		  Ext.MessageBox.confirm('Confirmation','Delete these Selected Books?', deleteBook);
		} 
	  }
	
	function deleteBook(btn){
		if(btn=='yes'){
			var selections = issuebooklist.selModel.getSelections();
		    var count = issuebooklist.selModel.getCount();
			for(i = 0; i< count; i++){
		 	 	storeissuebooklist.removeAt(storeissuebooklist.indexOf(selections[i]));
			}
		}  
  	}
	
	function resetForm(){
		BookIssueForm.getForm().reset();
		Ext.getCmp('btnAdd').enable();
		Ext.getCmp('book_registerid').disable();
		Ext.getCmp('membercategory').disable();
		Ext.getCmp('txtgrno').disable();
		Ext.getCmp('membername').disable();
		Ext.getCmp('txtbookregno').disable();
		Ext.getCmp('txtbookname').disable();
		Ext.getCmp('book_returndate').disable();
		Ext.getCmp('search_grno').disable();
		Ext.getCmp('txttotalIssueablebook').disable();
		Ext.getCmp('txttotalissuedbook').disable();
		Ext.getCmp('btnSave').disable();
		Ext.getCmp('book_issuedate').disable();
		Ext.getCmp('txtbookissueno').disable();	
		Ext.getCmp('student_section').disable();	
		storeissuebooklist.removeAll();
	}
	
	function returndate(){
		// START code for set return date
		var issue_date = Ext.getCmp('book_issuedate').getValue();
		issue_date.setDate(issue_date.getDate() + BookReturnDays);
		Ext.getCmp('book_returndate').setValue(issue_date);
		// END code for set return date	
	}
	
	//sectionstore.load();
	//registerstore.load();
	
	var varWidth =  (screen.width - BookIssueWindow.width)/2;
	BookIssueWindow.setPosition(varWidth,((screen.height/4)-190));
	BookIssueWindow.show();
});