
//alert(returnId);
//alert(customer_id);

var labelArray2;
labelArray2 = [ 	['Org.Name :<span class="comp">*</span>'],
				['Balance :<span class="comp"></span>'],
				['Address :<span class="comp"></span>'],
				['Name :<span class="comp"></span>'],
				['Phone :<span class="comp"></span>'],
				['Mobile :<span class="comp"></span>'],
				['Email :<span class="comp"></span>'],
				['Website :<span class="comp"></span>'],
				['Name :<span class="comp"></span>']			
		
			];

var districtsore = new Ext.data.Store({
			url: 'data/getdistrictcode.php',          
	        reader: new Ext.data.JsonReader({			
                fields: ['dist_id','dist_nameeng'],
                root: 'rows'
            }),autoLoad:true
        });
var cust_org_store = new Ext.data.Store({
			url: 'data/getorgname.php',          
	        reader: new Ext.data.JsonReader({			
                fields: ['customer_orgname'],
                root: 'rows'
            }),autoLoad:true
        });		
var storeopbalance= new Ext.data.ArrayStore({
    	fields: ['val_opbalance','dis_opbalance'],
	    data: [['C','Credit'],['D','Debit']]
    });	
		
var groupstore = new Ext.data.Store({
		url: 'data/getGroupSubgroup.php', 
		totolProperty:'total',
	    reader: new Ext.data.JsonReader({			
        	fields: ['account_groupid', 'account_groupname'],
            root: 'rows1'
     	})
  	});  
	groupstore.load({params:{action:'group'}});
	var encode = false;
	var local = false;
	var xg = Ext.grid;
	 
	/* var sm2 = new xg.CheckboxSelectionModel({
        listeners: {
        selectionchange: function(sm) {
                if (sm.getCount()) {
                    grid.removeButton.enable();
                } else {
                    grid.removeButton.disable();
                }
            }
        }
    });  */
		
	function confirmdeletecustomer(){
		if(grid.selModel.getCount() == 1)
		{
		  Ext.MessageBox.confirm('Confirmation','You are about to delete a Customer. Continue?', deleteSchool);
		} else if(grid.selModel.getCount() > 1){
		  Ext.MessageBox.confirm('Confirmation','Delete these Customer(s)?', deleteSchool);
		} 
  } 
function deleteSchool(btn){
    if(btn=='yes'){
         var selections = grid.selModel.getSelections();
         var prez = [];
		 var acountid = [];
         for(i = 0; i< grid.selModel.getCount(); i++){
          prez.push(selections[i].json.customer_id);
		  acountid.push(selections[i].json.account_id);
         }
		 
         var encoded_array = Ext.encode(prez);
		  var acountid_array = Ext.encode(acountid);
		
         Ext.Ajax.request({  
            waitMsg: 'Please Wait',
            url:'data/customer-grid-delete.php', 
            params: { 
               task: "DELETEEMP", 
               ids:  encoded_array,
			   acountids:acountid_array 
			   }, 
            success: function(response){
              var result=eval(response.responseText);
              switch(result){
              case 1: 
			  	store.reload();
				        CustomergridForm.getForm().reset();
						grid.getSelectionModel().clearSelections();
						//grid.removeButton.disable();
						cust_org_store.load();
                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');      
              }
         });
      }  
  }
  	
store = new Ext.data.JsonStore({
       	autoDestroy: true,
        url:'data/customer-grid-filter.php',
        remoteSort: true,
				autoLoad:true,
				
        sortInfo: {
            field: 'customer_id',
            direction: 'ASC'
        },        
        idProperty: 'customer_id',
        root: 'data',
       // totalProperty: 'total',
        fields: [{
            name: 'customer_id',
			type: 'int'
        }, {
            name: 'customer_orgname'
        }, {
            name: 'customer_address'
        }, {
            name: 'customer_phone1',
			type: 'int'
        }, {
            name: 'customer_phone2',
			type: 'int'
        }, {
            name: 'customer_email'
        }, {
            name: 'customer_website'
        },{
            name: 'district_id'
        }, {
            name: 'customer_balance'
        }, {
            name: 'customer_cpname1'
        }, {
            name: 'customer_cpdesignation1'
        }, {
            name: 'customer_cpmobile1'
        },{
            name: 'customer_cpemail1'
        },{
            name: 'customer_tinno'
        }, {
            name: 'customer_cstno'
        }, {
            name: 'customer_servicetaxno'
        }, {
            name: 'customer_panno'
        }, {
            name: 'customer_remark'
        }, {
            name: 'account_id'
        }, {
            name: 'customer_baltype'
        }] 
    });
    var filters = new Ext.ux.grid.GridFilters({
        encode: encode,
        local: false,                                      
		filters: [{
				  type: 'numeric',
            dataIndex: 'customer_id',
			 phpMode: true
        }, {
			type: 'string',
            dataIndex: 'customer_orgname',
			phpMode: true

        }, {
            dataIndex: 'customer_address',
			type: 'string'
        }, {
            dataIndex: 'customer_phone1',
			type: 'string'
        }, {
            dataIndex: 'customer_phone2',
			type: 'string'
        }, {
            dataIndex: 'customer_email',
			type: 'string'
        }, {
            dataIndex: 'customer_website',
			type: 'string'
        }]
    });
	
var createColModel = function (finish, start) {
        var columns = [
		
		{
            dataIndex: 'customer_id',
			header: 'Vendor ID',
			hidden:true,
			filterable: true
        }, {
			id: 'customer_orgname',
			name: 'customer_orgname',
            dataIndex: 'customer_orgname',
			header: 'Customer Name',
			filterable: true,
			filter: {type: 'string'},
			width: 140
			
        }, {
            dataIndex: 'customer_address',
			header: 'Address',
			hidden:true
        }, {
            dataIndex: 'customer_phone1',
			header: 'Contact No',
			width: 110
			
        }, {
            dataIndex: 'customer_phone2',
			header: 'Phone No2',
			hidden:true
        }, {
            dataIndex: 'customer_email',
			header: 'Email Id',
			hidden:true
        }, {
            dataIndex: 'customer_website',
			header: 'URL',
			hidden:true
        }];
		return new Ext.grid.ColumnModel({
            columns: columns.slice(start || 0, finish),
            defaults: {
                sortable: true
            }
        });
    };
	
var grid = new Ext.grid.GridPanel({
        store: store,
        colModel: createColModel(40), 
        loadMask: true,
		frame: true,
		enableColLock:false,
		height: 505, 
		//selectedIndex: cust_id,   
        width: 300,
        layout: 'fit',
		columnLines:true,
		selModel:  new Ext.grid.RowSelectionModel({
		singleSelect: true,
		listeners: {
			rowselect: function(sm, row, rec) {
				Ext.getCmp("CustomergridForm").getForm().loadRecord(rec);
				
				Ext.getCmp("customer_id").setValue(rec.data.customer_id);
				//alert(Ext.getCmp("account_id").getValue());
				
				// grid.removeButton.enable();
				//address Replace<br\>
				var str_add = Ext.getCmp('customer_address').getValue();
				str_add = str_add.replace(/<br\/>/g,"\r\n");
				Ext.getCmp('customer_address').setValue(str_add);
				
				//Remark Replace<br\>
				var str_remark= Ext.getCmp('customer_remark').getValue();
				str_remark = str_remark.replace(/<br\/>/g,"\r\n");
				Ext.getCmp('customer_remark').setValue(str_remark);
				
			}
		 }
		}),
        plugins: [filters],
       
		tbar: [new Ext.form.TriggerField({
                xtype: 'triggerfield',
                triggerClass: 'x-form-clear-trigger',
               	emptyText:'Search Customer',
				width:275,
				enableKeyEvents: true,
				listeners: {
							 keyup: function(){store.filter('customer_orgname',this.getValue(),true);}
				},
				onTriggerClick : function(){
					this.reset();
					store.filter('customer_orgname','',true)			
				  }

            })]
    });

		
var designationstore = new Ext.data.Store
({
	reader: new Ext.data.JsonReader
	({
		fields:['designation_id','designation_name'],
		root: 'rows'
	}),
	proxy: new Ext.data.HttpProxy
	({
		url: 'data/getdesignation.php'
	}),autoLoad:true
	
});
	function rating(v) {
        if (v == 0) return "No"
        if (v == 1) return "Yes"
    }
var flgalert = 0;

				

 var CustomergridForm = new Ext.FormPanel({
        id: 'CustomergridForm',
        frame: true,
		loadMast:true,
		url:'save-customer.php',
        layout: 'column', 
        items: [{
            columnWidth: 0.3,
            layout: 'fit',
            items:[grid]
        },{
            columnWidth: 0.7,
            xtype: 'fieldset',
			height: 525,  
			defaults: {border:false},
			bodyStyle: 'padding:8px;',
            items: [{
          	layout: 'column', 
			items: [{
				columnWidth: 0.5,
				labelWidth:70,
				layout: 'form',
				items:[{
							xtype: 'label',
							text: 'Basic',
							style: 'padding:0px 0px',
							cls: 'x-form-item myBold'	
					 },{
						xtype: 'combo',
						name: 'groupname',
						id:'groupname',
						fieldLabel :'A/C Group',
						forceSelection:true,
						displayField:'account_groupname',
						valueField: 'account_groupid',
						hiddenName:'accgroupid',
						allowBlank:false,
						width:200,
						//triggerAction:'all',
						value:'Sales A/c',
						editable:true,
						mode:'local',
						store: groupstore
						
					},
					{
							   xtype: 'combo',
							   name: 'customer_orgname',
							   id:'customer_orgname',
							  
							   tabIndex:1,
							   labelSeparator:'',	
							   fieldLabel :labelArray2[0] ,
							   displayField:'customer_orgname',
							   valueField: 'customer_orgname',
							   width: 200,
							   blankText: '',
							   emptyText:'',
							   allowBlank:false,
							   triggerAction:'all',
							   mode:'local',			
							   selectOnFocus: false,	
							   store: cust_org_store,
							   forceSelection:false,
							   editable:true
					}
					 ,{
							   xtype: 'combo',
							   name: 'district_id',
							   id:'district_id',
							   hiddenName: 'hiddendist_code',
							   tabIndex:2,
							   labelSeparator:'',	
							   fieldLabel :'District :<span class="comp">*</span>',
							   displayField:'dist_nameeng',
							   valueField: 'dist_id',
							   width: 200,
							   blankText: '',
							   emptyText:'',
							   allowBlank:false,
							   triggerAction:'all',
							   mode:'local',			
							   selectOnFocus: true,	
							   store: districtsore,
							   forceSelection:true,
							   editable:true
					},{
				xtype       : 'container',
				autoEl      : {},
				border      : false,
				layout      : 'column',
				anchor      : '87%',
				defaultType : 'field',
				items       : [
					{
						xtype  : 'container',
						autoEl : {},
						layout : 'form',
						columnWidth : .7,
						items  : [
							{
								xtype      : 'numberfield',
								labelSeparator:'',	
							    fieldLabel :'Balance :<span class="comp"></span>',
								tabIndex:3,
								name       : 'customer_balance',
								id         : 'customer_balance',
								allowBlank:true,	
								anchor     : '-2'
								,autoCreate: {tag: 'input', type: 'text',  maxlength: '10'}
							}
						]
					
					},
					{
						xtype       : 'container',
						autoEl      : {},
						layout      : 'form',
						columnWidth : .3,
						labelWidth  : 1,
						items       : [
							{
								xtype: 'combo',
								tabIndex:4
								,name: 'customer_baltype'
								,id:'customer_baltype'
							    ,fieldLabel: ''
								,forceSelection:true
								,displayField:'dis_opbalance'
								,valueField: 'val_opbalance'
								,hiddenName:'balance_typehidden'
								,allowBlank:true
								,triggerAction:'all'
								,mode:'local',
								editable:false
								,store: storeopbalance
								,anchor     : '-13'
							}			
						]
					}
								
				]
			
			},{ 
					 		height:30
						},{
							xtype: 'label',
							text: 'Contact Person1',
							style: 'padding:0px 0px',
							cls: 'x-form-item myBold'
					 }, {
							xtype: 'textfield',
							name: 'customer_cpname1',
							id:'customer_cpname1',
							labelSeparator:'',	
							fieldLabel :labelArray2[3] ,
							width:200,
							allowBlank:true,
							tabIndex:6
					 },{
							xtype:'combo',
							name:'customer_cpdesignation1',
							id:'customer_cpdesignation1',
							hiddenName: 'hiddencustomer_cpdesignation1',		
							displayField:'designation_name',
							valueField: 'designation_id',
							labelSeparator:'',	
							fieldLabel :'Desig. :<span class="comp"></span>',
							width:200,										
							tabIndex:10,
							allowBlank:true,
							triggerAction:'all',
							mode:'local',
							store: designationstore,
							editable:true,
							forceSelection:true,
						    tabIndex:7
					},{
							xtype: 'textfield',
							name: 'customer_cpmobile1',
							id:'customer_cpmobile1',
							labelSeparator:'',	
							fieldLabel :'Mobile :<span class="comp"></span>',
							width:200,
							allowBlank:true,
							minLength:10,
							maxLength:13,
							 tabIndex:8,
							autoCreate: {tag: 'input', type: 'text',  maxlength: '13'}
							,enableKeyEvents: true
							,listeners:{
								keyup: validphoneno
							}
					 },{
							xtype: 'textfield',
							name: 'customer_cpemail1',
							id:'customer_cpemail1',
							labelSeparator:'',	
							fieldLabel :labelArray2[6] ,
							width:200,
							 tabIndex:9,
							allowBlank:true,
							vtype:'email',
							autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
					 },{ 
					 		height:20
						},{
							xtype: 'label',
							text: 'Remark',
							style: 'padding:0px 0px',
							cls: 'x-form-item myBold'	
					 },{ 
						xtype: 'textarea',
						name: 'customer_remark',
						id:'customer_remark',
						style:'padding:0px 0px 0px 0px',
					    width:200,
						tabIndex:14,
						height:100,
						allowBlank:true
				}]
			},{	
            columnWidth: 0.5,
			layout: 'form',
			labelWidth:70,
			items: [{
							xtype: 'label',
							text: 'Address',
							cls: 'x-form-item myBold'	
					 },{ 
						xtype: 'textarea',
						name: 'customer_address',
						id:'customer_address',
					    width:200,
						height:100,
						tabIndex:5,
						labelSeparator:'',	
						fieldLabel :labelArray2[2] ,
						allowBlank:true
				},{ 
					 		height:29
						},{
							xtype: 'label',
							text: 'Tax IDs',
							style: 'padding:0px 0px',
							cls: 'x-form-item myBold'	
					 }, {
							xtype: 'textfield',
							name: 'customer_tinno',
							id:'customer_tinno',
							fieldLabel :'Serial No',
							width:200,
							allowBlank:true,
							tabIndex:10,
							minLength:5,
							maxLength:50,
							autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
							
    				 },{
							xtype:'textfield',
							name:'customer_cstno',
							id:'customer_cstno',
							width:200,										
							tabIndex:10,
							fieldLabel :'GST No',
							allowBlank:true,
							tabIndex:11,
							minLength:5,
							maxLength:50,
							autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
					},{
							xtype: 'textfield',
							name: 'customer_panno',
							id:'customer_panno',
							fieldLabel :'PAN No',
							width:200,
							tabIndex:12,
							allowBlank:true,
							minLength:5,
							maxLength:50,
							autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
					 },{
							xtype: 'textfield',
							name: 'customer_servicetaxno',
							id:'customer_servicetaxno',
							fieldLabel :'Service Tax No',
							width:200,
							allowBlank:true,
							tabIndex:13,
							minLength:5,
							maxLength:50,
							autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
														
					 },{ 
					 		height:12
					},{
							xtype: 'label',
							text: 'Custome Info',
							style: 'padding:0px 0px',
							cls: 'x-form-item myBold'	
					 },{
							xtype: 'textfield',
							name: 'customer_phone1',
							id:'customer_phone1',	
							labelSeparator:'',	
							fieldLabel :'Phone1 :<span class="comp"></span>',
							width:200,
							tabIndex:15,
							allowBlank:false,
							minLength:10,
							maxLength:13,
							autoCreate: {tag: 'input', type: 'text',  maxlength: '13'}
							,enableKeyEvents: true
							,listeners:{
								keyup: validphoneno
							}
					 },{
							xtype: 'textfield',
							name: 'customer_phone2',
							id:'customer_phone2',
							fieldLabel :'Phone2' ,
							width:200,
							tabIndex:16,
							allowBlank:true,
							minLength:10,
							maxLength:13,
							autoCreate: {tag: 'input', type: 'text',  maxlength: '13'}
							,enableKeyEvents: true
							,listeners:{
								keyup: validphoneno
							}
					 },{
							xtype: 'textfield',
							name: 'customer_email',
							id:'customer_email',
							fieldLabel :'Email' ,
							width:200,
							tabIndex:17,
							allowBlank:true,
							vtype:'email',
							autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
					 },{
							xtype: 'textfield',
							name: 'customer_website',
							id:'customer_website',
							fieldLabel :'Website' ,
							width:200,
							tabIndex:18,
							allowBlank:true,
							vtype:'url',
							autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
					 },{
							xtype: 'textfield',
							name: 'customer_id',
							id:'customer_id',
							hidden:true
					 },
					 {
							xtype: 'textfield',
							name: 'account_id',
							id:'account_id',
							hidden:true
					 },
					 {
						xtype:'hidden',
						id:'returnId',
						name:'returnId',
						hidden:true
			         }   ]
			}],
			buttonAlign: 'center',
		    buttons:[
		    {
            	text: 'Save',
				iconCls: 'icon-save',
				tabIndex:19,
				handler: function () {
					CustomergridForm.getForm().submit({
						waitMsg: 'Saving...',
						params:{customer_id:Ext.getCmp('customer_id').getValue()},		
						success: function (res,req) {
									
								if(returnId == "1"){											 
							     window.location = 'addedit-custsupport.php?customer_id='+ req.result.Id; 
								}
								else{	
										
								  Ext.MessageBox.show({
										   title: 'Message',
										   msg: 'Data has been saved',
										   buttons: Ext.MessageBox.OK,
										   icon:Ext.MessageBox.INFO
										  });
								}
										store.load();
										//grid.removeButton.disable();
										grid.getSelectionModel().clearSelections();
										CustomergridForm.getForm().reset();
										cust_org_store.load();
							
												 							    							 
						},
						failure: function () {		
							Ext.MessageBox.show({
										   title: 'Error',
										   msg: 'Please fill complete form.',
										   buttons: Ext.MessageBox.OK,
										   icon:Ext.MessageBox.ERROR
										  });
						}
					});
				}
          	},
			{
		    	text: 'Reset',
				iconCls: 'icon-reset',
				tabIndex:20,
				handler: function () {
						CustomergridForm.getForm().reset();
						grid.getSelectionModel().clearSelections();
						//grid.removeButton.disable();
							store.load();
						cust_org_store.load();
						
				}	
        	},
			{text: 'Delete Customer',
            handler: confirmdeletecustomer,  
            iconCls:'remove',
			ref: '../removeButton'
			
			},
			{
            	text: 'Close',
				iconCls: 'icon-close',
				tabIndex:21,
				handler: function(){
						CustomerWindow.hide();
						if(returnId == "1"){											 
							     window.location = 'addedit-custsupport.php';
								}
				}
        	}
		]
			     
        }]}
        ]
    });
	
 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 = "Please click here to edit record.";
     }
    }
   });
  });
  CustomergridForm.getForm().findField('customer_orgname').on('blur',function (){
	
		var custname=CustomergridForm.getForm().findField('customer_orgname').getValue();
		var custid=CustomergridForm.getForm().findField('customer_id').getValue();	
		var resbool="";		
		if(custname!="")
		{			
			Ext.Ajax.request({
					  loadMask: true,
					  sync : true,
					  url: 'data/customerrepeat-entry.php',
					  params: {custname: custname,custid:custid},
					  success: function(resp) {
						resbool=Ext.decode(resp.responseText).success;	
								if(resbool=='false')
								{
									Ext.MessageBox.show({
									   title: 'Error',
									   msg: 'Customer Name already exists!',
									   buttons: Ext.MessageBox.OK,
									   icon:Ext.MessageBox.ERROR
									});
								
									CustomergridForm.getForm().findField('customer_orgname').reset();											
									Ext.getCmp('customer_orgname').focus('', 10);
									}
										
					  }				
					});		
		}

	});	
 
 	var CustomerWindow = new Ext.Window({
        title: 'Customer Information',
		width:1000,		
		height:550,	
        frame: true,
		border: false,
		modal:true,
		layout: 'fit',
		closeAction:'hide',
		collapsible:true,
		items: CustomergridForm
		

	});

	var varWidth =  (screen.width - CustomerWindow.width)/5;
	CustomerWindow.setPosition(varWidth,((screen.height/4)-110));
	//Ext.getCmp('groupname').focus(true,500);
	/*if(mode == 'edit')
	{
		
	CustomergridForm.getForm().findField('customer_orgname').setValue('<?php echo $customer_orgname; ?>');
  	
	CustomergridForm.getForm().findField('groupname').setValue('<?php echo $account_groupid; ?>');
	CustomergridForm.getForm().findField('groupname').setRawValue('<?php echo $account_groupname; ?>');
    
    CustomergridForm.getForm().findField('district_id').setValue('<?php print $dist_id; ?>');
     CustomergridForm.getForm().findField('district_id').setRawValue('<?php print  $dist_nameeng; ?>');

     CustomergridForm.getForm().findField('customer_balance').setValue('<?php print $customer_balance; ?>');
     
     CustomergridForm.getForm().findField('customer_baltype').setValue('<?php print $val_opbalance; ?>');
     CustomergridForm.getForm().findField('customer_baltype').setRawValue('<?php echo $dis_opbalance; ?>');

     CustomergridForm.getForm().findField('customer_cpname1').setValue('<?php print $customer_cpname1; ?>');
     
     CustomergridForm.getForm().findField('customer_cpdesignation1').setValue('<?php print $designation_id; ?>');
     CustomergridForm.getForm().findField('customer_cpdesignation1').setRawValue('<?php echo $designation_name; ?>');		

     CustomergridForm.getForm().findField('customer_cpmobile1').setValue('<?php print $customer_cpmobile1; ?>');
	 CustomergridForm.getForm().findField('customer_cpemail1').setValue('<?php print $customer_cpemail1; ?>');
     CustomergridForm.getForm().findField('customer_remark').setValue('<?php print $customer_remark; ?>');
     CustomergridForm.getForm().findField('customer_address').setValue('<?php print $customer_address; ?>');
    CustomergridForm.getForm().findField('customer_tinno').setValue('<?php print $customer_tinno; ?>');
     CustomergridForm.getForm().findField('customer_cstno').setValue('<?php print  $customer_cstno; ?>');
     CustomergridForm.getForm().findField('customer_panno').setValue('<?php print $customer_panno; ?>');
     CustomergridForm.getForm().findField('customer_servicetaxno').setValue('<?php print $customer_servicetaxno; ?>');
	 CustomergridForm.getForm().findField('customer_phone1').setValue('<?php print $customer_phone1; ?>');
     CustomergridForm.getForm().findField('customer_phone2').setValue('<?php print $customer_phone2; ?>');
	 CustomergridForm.getForm().findField('customer_email').setValue('<?php print $customer_email; ?>');
     CustomergridForm.getForm().findField('customer_website').setValue('<?php print $customer_website; ?>');
     CustomergridForm.getForm().findField('customer_id').setValue('<?php print $customer_id; ?>');
     CustomergridForm.getForm().findField('account_id').setValue('<?php print $account_id; ?>');
}
*/