var labelArray;
labelArray = [
			 	['Subgroup Code :'],
				['Subgroup Name :<span class="comp">*</span>']
			];

Ext.onReady(function() {
	Ext.QuickTips.init();
 	
	var subgroupliststore = new Ext.data.Store({
		url: 'data/getAccountSubGroup.php',
		totolProperty:'total',
		reader: new Ext.data.JsonReader({			
        	fields: [{name:'subgroup_id',type:'int'}, 'subgroup_name'],
            root: 'rows'
       	}),autoLoad:true
    });
	
	var storeaccounteffect= new Ext.data.ArrayStore({
    	fields: ['dis_accounteffect'],
	    data: [['Profit & Loss'],['Balance Sheet']]
    });
	
	var storeopbalance= new Ext.data.ArrayStore({
    	fields: ['dis_opbalance'],
	    data: [['Credit'],['Debit']]
    });
	var flgalert = 0;
	var departmentLV = new Ext.ListView({
		store         : subgroupliststore,
		width:300,
		singleSelect  : true,
	
		style         : 'background-color: #FFFFFF;',
		columns       : [
			{
				header    : 'Subgroup Code',
				name	  : 'subgroup_id',
				id		  : 'subgroup_id',
				width 	  : 0.3,
				dataIndex : 'subgroup_id'
			},
			{
				header    : 'Subgroup Name',
				dataIndex : 'subgroup_name',
				width 	  : 0.5
			}
		],
		listeners : {
				click : function(thisView, index) {
					
						var record = thisView.store.getAt(index);
						var txtSubgroupCode = Ext.getCmp('subgroupcode');
						var txtSubgroupName = Ext.getCmp('subgroupname');
						txtSubgroupCode.setValue(record.get('subgroup_id'));
						txtSubgroupName.setValue(record.get('subgroup_name'));
						txtSubgroupCode.enable();
						txtSubgroupName.enable();
						Ext.getCmp('btnSave').enable();
						Ext.getCmp('btndelete').enable();
					
            	}
		}
	});
	
	var AccountSubGroupWindow;
	
	var onSuccessOrFail = function(form, action) {
		var formPanel = Ext.getCmp('myFormPanel');
		formPanel.el.unmask();
		var result = action.result;
		if (result.success) {
			account.getForm().findField('subgroupcode').reset();	
			account.getForm().findField('subgroupname').reset();
			
			account.getForm().findField('subgroupcode').disable();	
			account.getForm().findField('subgroupname').disable();	
			subgroupliststore.load();
		}
	};
	    
	var fieldset1 = {
		xtype       : 'fieldset',
		id			: 'fieldset1',
		name		: 'fieldset1',
		frame		: true,
		border      : false,
		defaultType : 'field',
		labelWidth:130,
		items : [
			{
				labelSeparator:'',	
				fieldLabel :labelArray[0] ,
				name       : 'subgroupcode',
				id         : 'subgroupcode',
				width      : 150,
				readOnly   : true,
				disabled   : true
			},
			{
				xtype:'textfield',
				labelSeparator:'',	
				fieldLabel :labelArray[1] ,
				name       : 'subgroupname',
				id         : 'subgroupname',
				width      : 150,
				allowBlank : false,
				disabled   : true
				,autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
			}
		]
	}
	
	var fieldset2 = Ext.apply({},{
		flex       : 1,
		labelWidth : 50,
		autoScroll : true,
		items      : [departmentLV]
	});
	
	var account= new Ext.FormPanel({
		id		: 'myFormPanel',
		method	:'post',
		border	: false,
		layout	:'fit',
		frame	:true,
		items	:[fieldset1]
	});
	
	var fieldsetContainer = {
		xtype  : 'container',
		autoEl : {},
		layout : 'hbox',
		anchor : '100%',
		height : 220,
		layoutConfig : {
				align : 'stretch'
			},
				defaults : {
				flex : 1
			},
	
		items  : [
			account,
			fieldset2
		]
	};
	
	var buttons = [{   
					   text:'Add New',
					   name: 'btnAdd',
						id: 'btnAdd',
						iconCls:'icon-add',
						handler: function(){
							
							var txtSubgroupCode = Ext.getCmp('subgroupcode');
							var txtSubgroupName = Ext.getCmp('subgroupname');
							txtSubgroupCode.enable();
							txtSubgroupName.enable();
							account.getForm().findField('subgroupname').focus(); 
							txtSubgroupName.reset();
							Ext.getCmp('btnAdd').disable();
							Ext.getCmp('btnSave').enable();
							Ext.Ajax.request({
									  loadMask: true,
									  sync : true,
									  url: 'data/getAccountCode.php',
									  params: {action:'subgroup'},
									  waitMsg:'Loading',
									  success: function(resp) {
										varcodeno=Ext.decode(resp.responseText).idno;
										txtSubgroupCode.setValue(varcodeno); 			
									  }				
							});
						}
				   },{
					   text: 'Save',
					   name: 'btnSave',
					   id: 'btnSave',
					   iconCls:'icon-save',
					   handler: function(){
						    var txtSubgroupCode = Ext.getCmp('subgroupcode');
							var txtSubgroupname = Ext.getCmp('subgroupname');
							if(txtSubgroupname.getValue()!=""){
								totalstore = subgroupliststore.getCount();
								
								if(totalstore>0)
								{
									var first = parseInt(subgroupliststore.getAt(0).data.subgroup_id);
									var last = parseInt(subgroupliststore.getAt(totalstore-1).data.subgroup_id);
									if(txtSubgroupCode.getValue()>Math.max(first,last)){
										var formPanel = Ext.getCmp('myFormPanel');
											formPanel.getForm().submit({
											url     : 'save-acsubgroup.php',
											params  : { action: 'save'},
											success : onSuccessOrFail,
											failure : onSuccessOrFail
										});
									}
									else{
										var formPanel = Ext.getCmp('myFormPanel');
											formPanel.getForm().submit({
											url     : 'save-acsubgroup.php',
											params  : { action: 'edit'},
											success : onSuccessOrFail,
											failure : onSuccessOrFail
										});
									}
								}
								else{
									var formPanel = Ext.getCmp('myFormPanel');
										formPanel.getForm().submit({
										url     : 'save-acsubgroup.php',
										params  : { action: 'save'},
										success : onSuccessOrFail,
										failure : onSuccessOrFail
									});	
								}
								
						}
							else{
								Ext.MessageBox.show({
									 title: 'Error',
									  msg:'Please fill complete form ',
									   buttons: Ext.MessageBox.OK,
									   icon:Ext.MessageBox.ERROR
									
								});
							}
							Ext.getCmp('btnSave').disable();
								Ext.getCmp('btnAdd').enable();
						}
							
					},{
					   text: 'Reset',
					   iconCls:'icon-reset',
					   handler: function(){
						    var txtSubgroupCode = Ext.getCmp('subgroupcode');
							var txtSubgroupname = Ext.getCmp('subgroupname');
							txtSubgroupCode.reset();
							txtSubgroupname.reset();
							departmentLV.clearSelections(true); 
							txtSubgroupCode.disable();
							txtSubgroupname.disable();
							Ext.getCmp('btnAdd').enable();
							Ext.getCmp('btnSave').disable();
							Ext.getCmp('btndelete').disable();
						}
						  
				   },{
					   text: 'Delete',
					    iconCls:'remove',
						id:'btndelete',
						disabled:true,
							handler: function(){
						    	var txtSubgroupCode = Ext.getCmp('subgroupcode');
								txtSubgroupCode.enable();
								
								////
								Ext.Ajax.request({
									loadMask: true,
									sync : true,
									url: 'data/getSubGroupRelatedRecord.php',
									params: {account_subgroupid: txtSubgroupCode.getValue()},
									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.?', deleteAccount);
									}				
								});	
								////
								
								Ext.getCmp('btnSave').disable(); 
								Ext.getCmp('btndelete').disable();       
							}
					                  
						  
				},{
					   text: 'Close',
					   iconCls:'icon-close',
					   handler: function(){
						 
						  AccountSubGroupWindow.close();
					}
				   }];
	
	function deleteAccount(btn){
		if(btn=='yes')
			{
			
			
				var formPanel = Ext.getCmp('myFormPanel');
					formPanel.getForm().submit({
					url     : 'save-acsubgroup.php',
					params  : { action: 'delete'},
					success : onSuccessOrFail,
					failure : onSuccessOrFail
				});
				
			}
			
			
		
	}
	
	Ext.getCmp('subgroupname').on('blur',function (){
		var txtSubgroupName = Ext.getCmp('subgroupname');
		var txtSubgroupCode = Ext.getCmp('subgroupcode').getValue();
		var subgroupname = txtSubgroupName.getValue();	
		if(subgroupname!=""){
			Ext.Ajax.request({
			  url: 'data/getDuplicateAccountName.php',
			  params: {action:'subgroup',name:subgroupname,id:txtSubgroupCode},
			  waitMsg:'Loading',
			  success: function(resp) {
				varduplicate=Ext.decode(resp.responseText).duplicate;
				if(varduplicate){
					txtSubgroupName.reset();
					Ext.MessageBox.show({
						title: 'Error',
						msg:'SubGroup Name is already exists',
						buttons: Ext.MessageBox.OK,
						icon:Ext.MessageBox.ERROR
									
					});
					
				}
			  }				
		});
		}
	});
	
	if(!AccountSubGroupWindow){	
		var  AccountSubGroupWindow=new Ext.Window({
			title      : 'Account Sub Group Information',
			height     : 292,
			url:'saveAccountgroup.php',
			layout     : 'form',
			labelWidth : 100,
			width      : 670,
			border: false,
			closable   : true,
		    collapsible:'true',
			modal:true,
			bodyStyle  : 'padding: 5px',
			items      : fieldsetContainer,
			buttonAlign: 'right',
			buttons: buttons
		})
	}
	Ext.getCmp('btnSave').disable();
	var varWidth =  (screen.width - AccountSubGroupWindow.width)/2;
	AccountSubGroupWindow.setPosition(varWidth,((screen.height/4)-100));
	AccountSubGroupWindow.show();
});