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


Ext.onReady(function() {
	Ext.QuickTips.init();
 	
	var groupstore= new Ext.data.ArrayStore({
    	fields: ['val_group','dis_group'],
	    data: [['P','Primary Group'],['D','Derived Group']]
  	}); 
 	var accountgroupliststore = new Ext.data.Store({
		url: 'data/getAccountgroup.php',
		totolProperty:'total',
		reader: new Ext.data.JsonReader({			
        	fields: [{name:'account_groupid',type:'int'}, 'account_groupname','account_type','acc_type_code'],
            root: 'rows'
       	}),autoLoad:true
    });
	var flgalert = 0;
	var departmentLV = new Ext.ListView({
		store         :   accountgroupliststore,
		singleSelect  : true,
		width:310,
		columns       : [
			{
				header    : 'Group Code',
				dataIndex : 'account_groupid',
				width : 0.2
			},
			{
				header    : 'Accout Group Name',
				dataIndex : 'account_groupname',
				width : 0.5
			},
			{
				header    : 'Group Type',
				dataIndex : 'account_type',
				width : 0.27
			}
			
		],
		listeners : {
			click : function(thisView, index) {
				
					var record = thisView.store.getAt(index);
					var txtaccountgroupCode = Ext.getCmp('groupcode');
					var txtaccountgroupName = Ext.getCmp('groupname');
					var txtaccountgrouptype = Ext.getCmp('grouptype');
					txtaccountgroupCode.setValue(record.get('account_groupid'));
					txtaccountgroupName.setValue(record.get('account_groupname'));
					txtaccountgrouptype.setValue(record.get('acc_type_code'));
					txtaccountgrouptype.setRawValue(record.get('account_type'));
					txtaccountgroupCode.enable();
					txtaccountgroupName.enable();
					txtaccountgrouptype.enable();
					Ext.getCmp('btnSave').enable();
					Ext.getCmp('btndelete').enable();
					Ext.getCmp('btnAdd').enable();
			
            }
		}
	
	});
		
	var AccountGroupWindow;
     
	var fieldset1 = {
		xtype       : 'fieldset',
		border      : false,
		labelWidth  : 140,
		defaultType : 'field',
			items : [
			{
				labelSeparator:'',	
				fieldLabel :labelArray[0] ,
				name       : 'groupcode',
				id         : 'groupcode',
				readOnly   : true,
				disabled    : true
			},
			{
				xtype:'textfield',
				labelSeparator:'',	
				fieldLabel :labelArray[1] ,
				name       : 'groupname',
				id         :  'groupname',
				allowBlank:false,
				disabled    : true,
				autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
			},
			{
				
				xtype: 'combo',
				name: 'grouptype',
				id:'grouptype',
				labelSeparator:'',	
				fieldLabel :labelArray[2] ,
				forceSelection:true,				
				displayField:'dis_group',
				valueField: 'val_group',
				hiddenName:'group_type',
				width: 130,
				allowBlank: false,
				editable: false, 
				triggerAction:'all',
				mode:'local',												
				store:groupstore,
				disabled    : true
			}	
		]
	}

 	var account= new Ext.FormPanel({
		id: 'myFormPanel',
		method:'post',
		border: false,
		layout:'fit',
		frame:true,
		items:[fieldset1]
	});
	
   	var fieldset2 = Ext.apply({}, {
		flex:1,
		labelWidth:50,
		autoScroll:true,
		items:[departmentLV]
	});
  
  	var fieldsetContainer = {
		xtype  : 'container',
		autoEl : {},
		layout : 'hbox',
		anchor : '100%',
		height  : 190,
		layoutConfig : {
     		align : 'stretch'
        },
        defaults : {
            flex : 1
        },
		items  : [
			account,
			fieldset2
		]
	}

	var onSuccessOrFail = function(form, action) {
		var formPanel = Ext.getCmp('myFormPanel');
		formPanel.el.unmask();
		var result = action.result;
		if (result.success) {
			accountgroupliststore.load();
			account.getForm().findField('groupcode').reset();	
			account.getForm().findField('groupname').reset();	
			account.getForm().findField('grouptype').reset();
			account.getForm().findField('groupcode').disable();	
			account.getForm().findField('groupname').disable();	
			account.getForm().findField('grouptype').disable();
			Ext.getCmp('btnSave').disable();
		}
	}

	function deleteAccount(btn){
		if(btn=='yes'){
			var formPanel = Ext.getCmp('myFormPanel');
				formPanel.getForm().submit({
				url     : 'save-acgroup.php',
				params  : { action: 'delete'},
				success : onSuccessOrFail,
				failure : onSuccessOrFail
			});
		}
	}

	Ext.getCmp('groupname').on('blur',function (){
		var groupName = Ext.getCmp('groupname');
		var txtgroupcode = Ext.getCmp('groupcode').getValue();
		var vargroupname = groupName.getValue();				   
		if(vargroupname!=""){
			Ext.Ajax.request({
				url: 'data/getDuplicateAccountName.php',
				params: {action:'group',name:vargroupname,id:txtgroupcode},
				waitMsg:'Loading',
				success: function(resp) {
					varduplicate=Ext.decode(resp.responseText).duplicate;
					if(varduplicate){
						groupName.reset();
						Ext.MessageBox.show({
							title: 'Error',
							msg:'Account Group Name is already exists',
							buttons: Ext.MessageBox.OK,
							icon:Ext.MessageBox.ERROR
						});
					}
				}				
			});
		}
	});

	if(!AccountGroupWindow){	
		var  AccountGroupWindow=new Ext.Window({
		title      : 'Account Group Information',
		height     : 265,
		url:'saveAccountgroup.php',
		layout     : 'fit',
		labelWidth : 100,		
		width      : 690,
		modal:true,
		border: false,
		closable   : true,
		    collapsible:'true',
		bodyStyle  : 'padding: 5px',
		items      : fieldsetContainer,
	 	buttonAlign: 'right',
		buttons: [
			{
				text:'Add New',
				name: 'btnAdd',
				iconCls:'icon-add',
				id: 'btnAdd',
				handler: function(){
					var txtaccountgroupCode = Ext.getCmp('groupcode');
					var txtaccountgroupName = Ext.getCmp('groupname');
					var txtaccountgrouptype = Ext.getCmp('grouptype');
					txtaccountgroupCode.enable();
					txtaccountgroupName.enable();
					txtaccountgrouptype.enable();
					account.getForm().findField('groupname').focus(); 
					txtaccountgroupName.reset();
					txtaccountgrouptype.reset();
					Ext.getCmp('btnAdd').disable();
					Ext.getCmp('btnSave').enable();
					Ext.Ajax.request({
						loadMask: true,
						sync : true,
						url: 'data/getAccountCode.php',
						params: {action:'group'},
						waitMsg:'Loading',
						success: function(resp) {
							varcodeno=Ext.decode(resp.responseText).idno;
							txtaccountgroupCode.setValue(varcodeno); 			
						}					
					});	
				}
			},
			{
				text: 'Save',
				name: 'btnSave',
				iconCls:'icon-save',
				id: 'btnSave',
				handler: function(){
					var txtaccountgroupName = Ext.getCmp('groupname');
					var txtaccountgrouptype = Ext.getCmp('grouptype');
					if(txtaccountgroupName.getValue()!="" && txtaccountgrouptype.getValue()!=""){
						totalstore = accountgroupliststore.getCount();
						if(totalstore>0){
							var first = parseInt(accountgroupliststore.getAt(0).data.account_groupid);
							var last = parseInt(accountgroupliststore.getAt(totalstore-1).data.account_groupid);
							var txtaccountgroupCode = Ext.getCmp('groupcode').getValue();
							if(txtaccountgroupCode>Math.max(first,last)){
								var formPanel = Ext.getCmp('myFormPanel');
								formPanel.getForm().submit({
									url     : 'save-acgroup.php',
									params  : { action: 'save'},
									success : onSuccessOrFail,
									failure : onSuccessOrFail
								});
							}
							else{
								var formPanel = Ext.getCmp('myFormPanel');
								formPanel.getForm().submit({
									url     : 'save-acgroup.php',
									params  : { action: 'edit'},
									success : onSuccessOrFail,
									failure : onSuccessOrFail
								});
							}
						}
						else{
							var formPanel = Ext.getCmp('myFormPanel');
							formPanel.getForm().submit({
								url     : 'save-acgroup.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('btnAdd').enable();
				}  
			},
		    {
				text: 'Reset',
				iconCls:'icon-reset',
				handler: function(){
					var txtaccountgroupCode = Ext.getCmp('groupcode');
					var txtaccountgroupName = Ext.getCmp('groupname');
					var txtaccountgrouptype = Ext.getCmp('grouptype');
					txtaccountgroupCode.reset();
					txtaccountgroupName.reset();
					txtaccountgrouptype.reset();
					txtaccountgroupCode.disable();
					txtaccountgroupName.disable();
					txtaccountgrouptype.disable();
					Ext.getCmp('btnAdd').enable();
					Ext.getCmp('btnSave').disable();
					Ext.getCmp('btndelete').disable();
					departmentLV.clearSelections(true); 
				}
			},
			{
				text: 'Delete',
				id:'btndelete',
				 iconCls:'remove',
				disabled:true,
				handler: function(){
					var txtaccountgroupCode = Ext.getCmp('groupcode');
					txtaccountgroupCode.enable();
					
					Ext.Ajax.request({
						loadMask: true,
						sync : true,
						url: 'data/getGroupRelatedRecord.php',
						params: {account_groupid: txtaccountgroupCode.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();
				}
			},
			{
				text: 'Close',
				iconCls:'icon-close',
				handler: function(){
					
					AccountGroupWindow.close();
				}
			}
		]
	})
}
Ext.getCmp('btnSave').disable();
var varWidth =  (screen.width - AccountGroupWindow.width)/2;
AccountGroupWindow.setPosition(varWidth,((screen.height/4)-100));
AccountGroupWindow.show();
});