var labelArray;
labelArray = [
			 	['Account Code :<span class="comp">*</span>'],
				['Group Name :<span class="comp">*</span>'],
				['Account Name :<span class="comp">*</span>'],
				['Account Type :<span class="comp">*</span>'],
				['Sub Group :<span class="comp">*</span>'],
				['Account Effect :<span class="comp">*</span>'],				
				['Op.Balance :<span class="comp">*</span>'],
				['Address :'],
				['Phone :']				
			];
var accountliststore = new Ext.data.Store({
		url: 'data/getAccountMaster.php',
		totolProperty:'total',
		reader: new Ext.data.JsonReader({			
        	fields: [
				{name:'account_id',type:'int'}, 
				{name:'account_groupid',type:'int'}, 
				'account_type',
				'account_name',
				'account_opbalance',
				'account_crdr',
				'account_baldate',
				'account_address',
				'account_phone',
				'account_effect',
				'subgroup_id',
				'account_groupname',
				'subgroup_name'
			],
            root: 'rows'
       	}),autoLoad:false
    });
	
	var storeaccounttype= new Ext.data.ArrayStore({
    	fields: ['dis_accounttype'],
	    data: [['Personal & Trading Account'],['Bank Account'],['Cash Account'],['Other Account']]
    });

	var groupstore = new Ext.data.Store({
		url: 'data/getGroupSubgroup.php', 
		totolProperty:'total',
	    reader: new Ext.data.JsonReader({			
        	fields: ['account_groupid', 'account_groupname'],
            root: 'rows1'
     	})
  	});  
		
	var subgroupstore = new Ext.data.Store({
		url: 'data/getGroupSubgroup.php', 
		totolProperty:'total',
	    reader: new Ext.data.JsonReader({			
   			fields: ['subgroup_id', 'subgroup_name'],
        	root: 'rows1'
        })
  	}); 
	
	var storeaccounteffect= new Ext.data.ArrayStore({
    	fields: ['dis_accounteffect'],
	    data: [['Profit & Loss'],['Balance Sheet']]
    });
	
	var storeopbalance= new Ext.data.ArrayStore({
    	fields: ['val_opbalance','dis_opbalance'],
	    data: [['C','Credit'],['D','Debit']]
    });				
	
	var fieldset1 = {
		xtype       : 'fieldset',
		border      : false,
		defaultType : 'field',
		items : [
			{
				labelSeparator:'',	
				fieldLabel :labelArray[0] ,
				id:'accountcode',
				name: 'accountcode',
				width:164,
				readOnly   : true,
				disabled   : true
			},
			{
				xtype: 'combo',
				name: 'groupname',
				id:'groupname',
				labelSeparator:'',	
				fieldLabel :labelArray[1] ,
				forceSelection:true,
				displayField:'account_groupname',
				valueField: 'account_groupid',
				hiddenName:'accgroupid',
				allowBlank:false,
				triggerAction:'all',
				editable:true,
				mode:'local',
				disabled   : true,
				store: groupstore
				
			},
			{
				xtype: 'textfield',
				labelSeparator:'',	
				fieldLabel :labelArray[2] ,
				name: 'accountname',
				id: 'accountname',
				disabled   : true,
				allowBlank : false,
				width:164
				,autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
			},
			{
				xtype: 'combo',
				name: 'accounttype',
				id:'accounttype',
				disabled   : true,
				editable:true,
				labelSeparator:'',	
				fieldLabel :labelArray[3] ,
				forceSelection:true,
				displayField:'dis_accounttype',
				valueField: 'dis_accounttype',
				allowBlank:false,
				triggerAction:'all',
				mode:'local',
				store: storeaccounttype
			},
			{
				xtype: 'combo',
				name: 'subgroup',
				id:'subgroup',
				labelSeparator:'',	
				fieldLabel :labelArray[4] ,
				forceSelection:true,
				disabled   : true,
				editable:true,
				displayField:'subgroup_name',
				valueField: 'subgroup_id',
				hiddenName:'accsubgroupid',
				value:'None',
				triggerAction:'all',
				mode:'local',
				store: subgroupstore
			},
			{
				xtype: 'combo'
				,name: 'accounteffect'
				,id:'accounteffect'
				,disabled   : true
				,labelSeparator:''	
				,fieldLabel :labelArray[5] 
				,forceSelection:true
				,displayField:'dis_accounteffect'
				,valueField: 'dis_accounteffect'
				,allowBlank:false
				,editable:true
				,triggerAction:'all'
				,mode:'local'
				,store: storeaccounteffect
			},
			{
				xtype       : 'container',
				autoEl      : {},
				border      : false,
				layout      : 'column',
				anchor      : '100%',
				defaultType : 'field',
				items       : [
					{
						xtype  : 'container',
						autoEl : {},
						layout : 'form',
						columnWidth : .715,
						items  : [
							{
								xtype      : 'numberfield',
								labelSeparator:'',	
								fieldLabel :labelArray[6] ,
								name       : 'txtopbalance',
								id         : 'txtopbalance',
								disabled   : true,
								allowBlank:false,	
								anchor     : '-2'
								,autoCreate: {tag: 'input', type: 'text',  maxlength: '10'}
							}
						]
					
					},
					{
						xtype       : 'container',
						autoEl      : {},
						layout      : 'form',
						columnWidth : .285,
						labelWidth  : 1,
						items       : [
							{
								xtype: 'combo'
								,name: 'opbalance'
								,id:'opbalance'
							    ,fieldLabel: ''
								,forceSelection:true
								,displayField:'dis_opbalance'
								,valueField: 'val_opbalance'
								,hiddenName:'opbal'
								,allowBlank:false
								,triggerAction:'all'
								,mode:'local',
								disabled   : true,
								editable:false
								,store: storeopbalance
								,anchor     : '-13'
							}			
						]
					}
								
				]
			
			},{ xtype: 'textarea',
									   growAppend: "",
									   name: 'address',
									   id:'address',
									   labelSeparator:'',	
									   fieldLabel :labelArray[7] ,
									   maxLength: 500,disabled   : true,
									   maxLengthText: 'max 500 characters',
									   width: 168
										},
					  
			
			{
				xtype: 'textfield',
				labelSeparator:'',	
				fieldLabel :labelArray[8] ,
				name       : 'phone',
				disabled   : true,
				allowNegative:false,
				id:'phone',
				width:164
				,autoCreate: {tag: 'input', type: 'text',  maxlength: '13'}
				,enableKeyEvents: true
				,listeners:{
					keyup: validphoneno
				}
			}			
		]
	};
	
	var acmaster= new Ext.FormPanel({
		id:'myFormPanel',
		method:'post',
		height: 400,
		border: true,
		layout:'form',
		frame:true,
		items:[fieldset1]
	});
	var flgalert = 0;
	// List View Start
	var departmentLV = new Ext.ListView({
		store         : accountliststore,
		singleSelect  : true,
		style         : 'background-color: #FFFFFF;',
		columns       : [
			{
				header    : 'Account Name',
				dataIndex : 'account_name'
			}
		],
		listeners : {
			click : function(thisView, index) {
				
					var record = thisView.store.getAt(index);
					var accountcode 		= Ext.getCmp('accountcode');
					var accountgroupname 	= Ext.getCmp('groupname');
					var accountname 		= Ext.getCmp('accountname');
					var accounttype 		= Ext.getCmp('accounttype');
					var accountsubgroup 	= Ext.getCmp('subgroup');
					var accounteffect 		= Ext.getCmp('accounteffect');
					var accounttxtopbalance = Ext.getCmp('txtopbalance');
					var accountopbalance 	= Ext.getCmp('opbalance');
					var accountaddress 		= Ext.getCmp('address');
					var accountphone 		= Ext.getCmp('phone');
					
					var str_add = record.get('account_address');
					str_add = str_add.replace(/<br\/>/g,"\r\n");
					
					accountcode.setValue(record.get('account_id'));
					accountgroupname.setValue(record.get('account_groupid'));
					accountgroupname.setRawValue(record.get('account_groupname'));
					
					accountname.setValue(record.get('account_name'));
					accounttype.setValue(record.get('account_type'));
					
					accountsubgroup.setValue(record.get('subgroup_id'));
					accountsubgroup.setRawValue(record.get('subgroup_name'));
				
					accounteffect.setValue(record.get('account_effect'));
					accounttxtopbalance.setValue(record.get('account_opbalance'));
					accountopbalance.setValue(record.get('account_crdr'));
					accountphone.setValue(record.get('account_phone'));
					accountaddress.setValue(str_add);	
					accountcode.enable();
					accountgroupname.enable();
					accountname.enable();
					accountcode.enable();
					accounttype.enable();
					accountsubgroup.enable();
					accounteffect.enable();
					accounttxtopbalance.enable();
					accountopbalance.enable();
					accountphone.enable();
					accountaddress.enable();
					Ext.getCmp('btnSave').enable();
					Ext.getCmp('btnAdd').enable();
					Ext.getCmp('btndelete').enable();
            }
		}
	});
	// List View End	
	
	var fieldset2 = Ext.apply({},{
		autoScroll : true,
		border : true,
		items : [departmentLV]
	});
	
    var onSuccessOrFail = function(form, action) {
		var formPanel = Ext.getCmp('myFormPanel');
		formPanel.el.unmask();
		var result = action.result;
		if (result.success) {
			acmaster.getForm().findField('accountcode').reset();	
			acmaster.getForm().findField('groupname').reset();	
			acmaster.getForm().findField('accountname').reset();	
			acmaster.getForm().findField('accounttype').reset();	
			acmaster.getForm().findField('subgroup').reset();	
			acmaster.getForm().findField('accounteffect').reset();	
			acmaster.getForm().findField('txtopbalance').reset();	
			acmaster.getForm().findField('opbalance').reset();	
			acmaster.getForm().findField('address').reset();	
			acmaster.getForm().findField('phone').reset();	
			acmaster.getForm().findField('accountcode').disable();	
			acmaster.getForm().findField('groupname').disable();	
			acmaster.getForm().findField('accountname').disable();	
			acmaster.getForm().findField('accounttype').disable();	
			acmaster.getForm().findField('subgroup').disable();	
			acmaster.getForm().findField('accounteffect').disable();	
			acmaster.getForm().findField('txtopbalance').disable();	
			acmaster.getForm().findField('opbalance').disable();	
			acmaster.getForm().findField('address').disable();	
			acmaster.getForm().findField('phone').disable();
			accountliststore.load();
			Ext.getCmp('btnSave').disable();
			Ext.getCmp('btndelete').disable();
		}
	};
		
	var fieldsetContainer = {
		xtype:'container',
		autoEl:{},
		layout:'hbox',
		anchor:'100%',
		height: 370,
		layoutConfig:{align : 'stretch'},
		defaults:{flex : 1},
		items:[
			acmaster,
			fieldset2
		]
	};
	var buttons = [{   
					    text:'Add New',
						name: 'btnAdd',
						id: 'btnAdd',
						iconCls:'icon-add',
						handler: function(){
							var accountcode 		= Ext.getCmp('accountcode');
							var accountgroupname 	= Ext.getCmp('groupname');
							var accountname 		= Ext.getCmp('accountname');
							var accounttype 		= Ext.getCmp('accounttype');
							var accountsubgroup 	= Ext.getCmp('subgroup');
							var accounteffect 		= Ext.getCmp('accounteffect');
							var accounttxtopbalance = Ext.getCmp('txtopbalance');
							var accountopbalance 	= Ext.getCmp('opbalance');
							var accountaddress 		= Ext.getCmp('address');
							var accountphone 		= Ext.getCmp('phone');
							
							accountgroupname.enable();
							accountname.enable();
							accountcode.enable();
							accounttype.enable();
							accountsubgroup.enable();
							accounteffect.enable();
							accounttxtopbalance.enable();
							accountopbalance.enable();
							accountphone.enable();
							accountaddress.enable();
                			
							accountgroupname.reset();
							accountname.reset();
							accountcode.reset();
							accounttype.reset();
							accountsubgroup.reset();
							accounteffect.reset();
							accounttxtopbalance.reset();
							accountopbalance.reset();
							accountphone.reset();
							accountaddress.reset();
							Ext.getCmp('btnAdd').disable();
							Ext.getCmp('btnSave').enable();
											
							Ext.Ajax.request({
									  loadMask: true,
									  sync : true,
									  url: 'data/getAccountCode.php',
									  params: {action:'master'},
									  waitMsg:'Loading',
									  success: function(resp) {
									  varcodeno=Ext.decode(resp.responseText).idno;
									  accountcode.setValue(varcodeno); 	
									  accountgroupname.focus();
									  }				
							});
						}
				   },
				   {
					   text: 'Save',
					   name: 'btnSave',
					   id: 'btnSave',
					   iconCls:'icon-save',
					   handler: function(){
						    var accountcode 		= Ext.getCmp('accountcode');
							var accountgroupname 	= Ext.getCmp('groupname');
							var accountname 		= Ext.getCmp('accountname');
							var accounttype 		= Ext.getCmp('accounttype');
							var accountsubgroup 	= Ext.getCmp('subgroup');
							var accounteffect 		= Ext.getCmp('accounteffect');
							var accounttxtopbalance = Ext.getCmp('txtopbalance');
							var accountopbalance 	= Ext.getCmp('opbalance');
							var accountaddress 		= Ext.getCmp('address');
							var accountphone 		= Ext.getCmp('phone');
							if(accountcode.getValue()!=""){
								totalstore = accountliststore.getCount()-1;
								if(totalstore>0)
								{
									var i,flag=0;
									for(i=0; i<=totalstore; i++){
										if(accountliststore.getAt(i).data.account_id == accountcode.getValue())
										{
											flag = 1;
											break;
										}
									}
									if(flag == 1){
										var formPanel = Ext.getCmp('myFormPanel');
										formPanel.getForm().submit({
											url     : 'save-acmaster.php',
											params  : { action: 'edit'},
											success : onSuccessOrFail,
											failure : onSuccessOrFail
										});
									}
									else{
										var formPanel = Ext.getCmp('myFormPanel');
										formPanel.getForm().submit({
											url     : 'save-acmaster.php',
											params  : { action: 'save'},
											success : onSuccessOrFail,
											failure : onSuccessOrFail
										});
									}
								}
								else{
									var formPanel = Ext.getCmp('myFormPanel');
										formPanel.getForm().submit({
										url     : 'save-acmaster.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 accountcode 		= Ext.getCmp('accountcode');
							var accountgroupname 	= Ext.getCmp('groupname');
							var accountname 		= Ext.getCmp('accountname');
							var accounttype 		= Ext.getCmp('accounttype');
							var accountsubgroup 	= Ext.getCmp('subgroup');
							var accounteffect 		= Ext.getCmp('accounteffect');
							var accounttxtopbalance = Ext.getCmp('txtopbalance');
							var accountopbalance 	= Ext.getCmp('opbalance');
							var accountaddress 		= Ext.getCmp('address');
							var accountphone 		= Ext.getCmp('phone');
							
							accountcode.reset();
							accountgroupname.reset();
							accountname.reset();
							accounttype.reset();
							accountsubgroup.reset();
							accounteffect.reset();
							accounttxtopbalance.reset();
							accountopbalance.reset();
							accountphone.reset();
							accountaddress.reset();
							departmentLV.clearSelections(true); 
							accountcode.disable();
							accountgroupname.disable();
							accountname.disable();
							accounttype.disable();
							accountsubgroup.disable();
							accounteffect.disable();
							accounttxtopbalance.disable();
							accountopbalance.disable();
							accountphone.disable();
							accountaddress.disable();
							Ext.getCmp('btnAdd').enable();
							Ext.getCmp('btnSave').disable();
							Ext.getCmp('btndelete').disable();
                		}
						  
				   },
				   {
					   text: 'Delete',
					   iconCls:'remove',
					   disabled:true,
					   id:'btndelete',
					   handler: function(){
							var accountcode = Ext.getCmp('accountcode');
						   	accountcode.enable();
							if(accountcode.getValue()!="")
							{
							////
							Ext.Ajax.request({
								loadMask:true,
								sync:true,
								url:'data/getMasterRelatedRecord.php',
								params:{account_id: accountcode.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(); 
							}else
							{
									Ext.MessageBox.show({
										title: 'Error',
										msg:'Please selcet Record First',
										buttons: Ext.MessageBox.OK,
										icon:Ext.MessageBox.ERROR
									});
							}
						}
					},
				   {
					   text: 'Close',
					   id: 'btnClose',
					   iconCls:'icon-close',
					   name: 'btnclose',
					   handler: function(){
						   winAccountMaster.close();
					}
				   }];
	
	function deleteAccount(btn){
		if(btn=='yes'){
			Ext.getCmp('btndelete').disable(); 
				var formPanel = Ext.getCmp('myFormPanel');
					formPanel.getForm().submit({
					url     : 'save-acmaster.php',
					params  : { action: 'delete'},
					success : onSuccessOrFail,
					failure : onSuccessOrFail
				});
			
			
		}
	}
	
	var winAccountMaster = new Ext.Window({
		title      : 'Account Master Information',
		height     : 440,
		layout     : 'form',
		labelWidth : 100,
		border: false,
		width      : 650,
		closable   : true,
		collapsible:'true',
		closeAction:'hide',
		modal:true,
		bodyStyle  : 'padding: 5px',
		items      : fieldsetContainer ,
		buttons	   : buttons
	});
	
	Ext.getCmp('accountname').on('blur',function (){
		var groupName = Ext.getCmp('accountname');
		var txtaccountcode = Ext.getCmp('accountcode').getValue();
		var vargroupname = groupName.getValue();				   
		if(vargroupname!=""){
			Ext.Ajax.request({
				
				  url: 'data/getDuplicateAccountName.php',
				  params: {action:'master',name:vargroupname,id:txtaccountcode},
				  waitMsg:'Loading',
				  success: function(resp) {
					varduplicate=Ext.decode(resp.responseText).duplicate;
					if(varduplicate){
						groupName.reset();
						Ext.MessageBox.show({
							title: 'Error',
						   	msg:'Account Name is already exists',
						   	buttons: Ext.MessageBox.OK,
						   	icon:Ext.MessageBox.ERROR
										
						});
						
					}
				  }				
		});															
		}
	});
	
	Ext.getCmp('groupname').on('select',function (){
		var entered_name = accountliststore.find('account_groupname','Cash-In-Hand'); // 2
		if(entered_name != -1 ){
			var entered_id   = accountliststore.getAt(entered_name).data.account_id;      // 3
			var accountid    = Ext.getCmp('accountcode').getValue();
			var groupid      = Ext.getCmp('groupname');
			if(groupid.getRawValue()=="Cash-In-Hand" && entered_id!=accountid){
				groupid.reset();
				Ext.MessageBox.show({
					title: 'Error',
					msg:'Cash-In-Hand Group is already used.',
					buttons: Ext.MessageBox.OK,
					icon:Ext.MessageBox.ERROR
				});
				groupid.focus();
			}
		}
	});
		
	var varWidth =  (screen.width - winAccountMaster.width)/2;
	winAccountMaster.setPosition(varWidth,((screen.height/4)-100));
	Ext.getCmp('btnSave').disable();			
	
	function ShowAccountMaster(){
		winAccountMaster.show();
		
	}
	function HideAccountMaster(){
		winAccountMaster.hide();
		
	}
	