var labelArray;
labelArray = [ 	['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 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();
                }
            }
        }
    });  	
store = new Ext.data.JsonStore({
       	autoDestroy: true,
        url:'data/vendor-grid-filter.php',
        remoteSort: true,
        sortInfo: {
            field: 'vendor_id',
            direction: 'ASC'
        },        
        idProperty: 'vendor_id',
        root: 'data',
        totalProperty: 'total',
        fields: [{
            name: 'vendor_id',
			type: 'int'
        }, {
            name: 'vendor_orgname'
        }, {
            name: 'vendor_address'
        }, {
            name: 'vendor_phone1',
			type: 'int'
        }, {
            name: 'vendor_phone2',
			type: 'int'
        }, {
            name: 'vendor_email'
        }, {
            name: 'vendor_website'
        },{
            name: 'district_id'
        }, {
            name: 'vendor_balance'
        }, {
            name: 'vendor_cpname1'
        }, {
            name: 'vendor_cpdesignation1'
        }, {
            name: 'vendor_cpmobile1'
        },{
            name: 'vendor_cpemail1'
        }, {
            name: 'vendor_tinno'
        }, {
            name: 'vendor_cstno'
        }, {
            name: 'vendor_servicetaxno'
        }, {
            name: 'vendor_panno'
        }, {
            name: 'vendor_remark'
        }, {
            name: 'account_id'
        },{
            name: 'vendor_baltype'
        }
		] 
    });
	  var filters = new Ext.ux.grid.GridFilters({
        encode: encode,
        local: false,                                      
		filters: [{
				  type: 'numeric',
            dataIndex: 'vendor_id',
			 phpMode: true
        }, {
			type: 'string',
            dataIndex: 'vendor_orgname',
			phpMode: true

        }, {
            dataIndex: 'vendor_address',
			type: 'string'
        }, {
            dataIndex: 'vendor_phone1',
			type: 'string'
        }, {
            dataIndex: 'vendor_phone2',
			type: 'string'
        }, {
            dataIndex: 'vendor_email',
			type: 'string'
        }, {
            dataIndex: 'vendor_website',
			type: 'string'
        }]
    });
	
var createColModel = function (finish, start) {
        var columns = [
		sm2,
		{
            dataIndex: 'vendor_id',
			header: 'Vendor ID',
			hidden:true,
			filterable: true
        }, {
            dataIndex: 'vendor_orgname',
			header: 'Vendor Name',
			filterable: true,
			width: 140
			
        }, {
            dataIndex: 'vendor_address',
			header: 'Address',
			hidden:true
        }, {
            dataIndex: 'vendor_phone1',
			header: 'Contact No',
			width: 110
			
        }, {
            dataIndex: 'vendor_phone2',
			header: 'Phone No2',
			hidden:true
        }, {
            dataIndex: 'vendor_email',
			header: 'Email Id',
			hidden:true
        }, {
            dataIndex: 'vendor_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: 500,    
        width: 300,
        layout: 'fit',
		columnLines:true,
		selModel:  new Ext.grid.RowSelectionModel({
		singleSelect: true,
		listeners: {
			rowselect: function(sm, row, rec) {
				Ext.getCmp("vendorgridForm").getForm().loadRecord(rec);
				
				 grid.removeButton.enable();
				// alert(Ext.getCmp("account_id").getValue());
				//address Replace<br\>
				var str_add = Ext.getCmp('vendor_address').getValue();
				str_add = str_add.replace(/<br\/>/g,"\r\n");
				Ext.getCmp('vendor_address').setValue(str_add);
				
				//Remark Replace<br\>
				var str_remark= Ext.getCmp('vendor_remark').getValue();
				str_remark = str_remark.replace(/<br\/>/g,"\r\n");
				Ext.getCmp('vendor_remark').setValue(str_remark);
				
			}
		 }
		}),
        plugins: [filters],
        listeners: {
            render: {
                fn: function(g){
					 store.reload({
                        params: {
                            start: 0,
                            limit: 20  
                        }
                    });
					 g.getSelectionModel().selectRow(0);
                   
                   
                }
            }
        }  ,
		tbar:[
         { 
		    	iconCls: 'icon-add',
           		text: 'Add Vendor',
				ref: '../removeButton',
            	handler: function() {
					
					Ext.getCmp("vendorgridForm").getForm().reset();
					grid.getSelectionModel().clearSelections();
					grid.removeButton.disable();
               
			    }
              
		            
      		},'-',
			{text: 'Delete Vendor',
            handler: confirmdeletevendor,  
            iconCls:'remove',
			ref: '../removeButton',
			disabled: true
			}
	  ], 
        bbar: new Ext.PagingToolbar({
            store: store,
            pageSize: 20,
			displayInfo: true,
            plugins: [filters]
        })
    });

    grid.getBottomToolbar().add([
        '->',
      {
            text: 'Clear Filter Data',
            handler: function () {
                grid.filters.clearFilters();
            } 
        }    
    ]);
	
	store.on({
		'beforeload': {
    		fn: function(store, options){
            	options.params || (options.params = {}); 
            	Ext.apply(options.params, {
            		pageNo: this.pageNumber
            	});
        	},
        	scope: this
    	}
	});
		
function confirmdeletevendor(){
if(grid.selModel.getCount() == 1)
{
	  Ext.MessageBox.confirm('Confirmation','You are about to delete a Vendor. Continue?', deleteVendor);
} } 
function deleteVendor(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.vendor_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/vendor-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();
				Ext.getCmp("vendorgridForm").getForm().reset();
					grid.getSelectionModel().clearSelections();
					grid.removeButton.disable();
                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');      
              }
         });
      }  
  }
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
	
});
Ext.onReady(function(){
    Ext.QuickTips.init();
 var flgalert = 0;
 var vendorgridForm = new Ext.FormPanel({
        id: 'vendorgridForm',
        frame: true,
		url:'save-vendor.php',
        bodyStyle:'padding:5px',
        layout: 'column', 
        items: [{
            columnWidth: 0.3,
            layout: 'fit',
            items:[grid]
        },{
            columnWidth: 0.7,
            xtype: 'fieldset',
			defaults: {border:false},
            autoHeight: true,
			bodyStyle: Ext.isIE ? 'padding:0 0 0px 5px;' : 'padding:0px 0px;',
            items: [{
			layout: 'column', 
			 defaults: {
             bodyStyle: 'padding-left:8px;'
        },
			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,
						tabIndex:1,
						//triggerAction:'all',
						value:'Purchase A/c',
						editable:true,
						mode:'local',
						store: groupstore
						
					},
					 {
							xtype: 'textfield',
							name: 'vendor_orgname',
							id:'vendor_orgname',
							tabIndex:1,
							labelSeparator:'',	
							fieldLabel :labelArray[0] ,
							width:200,
							allowBlank:false
					},{
							   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      : '90%',
				defaultType : 'field',
				items       : [
					{
						xtype  : 'container',
						autoEl : {},
						layout : 'form',
						columnWidth : .7,
						items  : [
							{
								xtype      : 'numberfield',
								fieldLabel :'Balance',
								name       : 'vendor_balance',
								id         : 'vendor_balance',
								tabIndex:4,
								allowBlank:true,	
								anchor     : '-2'
								,autoCreate: {tag: 'input', type: 'text',  maxlength: '10'}
							}
						]
					
					},
					{
						xtype       : 'container',
						autoEl      : {},
						layout      : 'form',
						columnWidth : .3,
						labelWidth  : 1,
						items       : [
							{
								xtype: 'combo'
								,name: 'vendor_baltype'
								,id:'vendor_baltype'
							    ,fieldLabel: ''
								,forceSelection:true
								,displayField:'dis_opbalance'
								,valueField: 'val_opbalance'
								,hiddenName:'vendor_baltypehidden'
								,allowBlank:true
								,triggerAction:'all'
								,tabIndex:4
								,mode:'local',
								editable:false
								,store: storeopbalance
								,anchor     : '-13'
							}			
						]
					}
								
				]
			
			},{ 
					 		height:20
						},{
							xtype: 'label',
							text: 'Contact Person',
							style: 'padding:0px 0px',
							cls: 'x-form-item myBold'
					 }, {
							xtype: 'textfield',
							name: 'vendor_cpname1',
							id:'vendor_cpname1',
							labelSeparator:'',	
							fieldLabel :labelArray[3] ,
							width:200,
							allowBlank:true,
							tabIndex:4
					 },{
							xtype:'combo',
							name:'vendor_cpdesignation1',
							id:'vendor_cpdesignation1',
							hiddenName: 'hiddenvendor_cpdesignation1',		
							displayField:'designation_name',
							valueField: 'designation_id',
							fieldLabel :'Designation: ',
							width:200,										
							tabIndex:10,
							labelSeparator:'',
							allowBlank:true,
							triggerAction:'all',
							mode:'local',
							store: designationstore,
							editable:true,
							forceSelection:true,
						    tabIndex:5
					},{
							xtype: 'textfield',
							name: 'vendor_cpmobile1',
							id:'vendor_cpmobile1',
							labelSeparator:'',	
							fieldLabel :labelArray[5] ,
							width:200,
							allowBlank:true,
							minLength:10,
							maxLength:13,
							 tabIndex:6,
							autoCreate: {tag: 'input', type: 'text',  maxlength: '13'}
							,enableKeyEvents: true
							,listeners:{
								keyup: validphoneno
							}
					 },{
							xtype: 'textfield',
							name: 'vendor_cpemail1',
							id:'vendor_cpemail1',
							labelSeparator:'',	
							fieldLabel :labelArray[6] ,
							width:200,
							 tabIndex:7,
							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: 'vendor_remark',
						id:'vendor_remark',
						style:'padding:0px 0px 0px 0px',
					    width:200,
						tabIndex:12,
						height:97,
						allowBlank:true
				}]
			},{	
            columnWidth: 0.5,
			layout: 'form',
			labelWidth:70,
			items: [{
							xtype: 'label',
							text: 'Address',
							cls: 'x-form-item myBold'	
					 },{ 
						xtype: 'textarea',
						name: 'vendor_address',
						id:'vendor_address',
					    width:200,
						height:100,
						tabIndex:3,
						labelSeparator:'',	
						fieldLabel :labelArray[2] ,
						allowBlank:true
				},{ 
					 		height:20
						},{
							xtype: 'label',
							text: 'Tax IDs',
							style: 'padding:0px 0px',
							cls: 'x-form-item myBold'	
					 }, {
							xtype: 'textfield',
							name: 'vendor_tinno',
							id:'vendor_tinno',
							fieldLabel :'TIN No',
							width:200,
							allowBlank:true,
							tabIndex:8,
							minLength:5,
							maxLength:50,
							autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
							
    				 },{
							xtype:'textfield',
							name:'vendor_cstno',
							id:'vendor_cstno',
							width:200,										
							tabIndex:10,
							fieldLabel :'CST No',
							allowBlank:true,
							tabIndex:9,
							minLength:5,
							maxLength:50,
							autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
					},{
							xtype: 'textfield',
							name: 'vendor_panno',
							id:'vendor_panno',
							fieldLabel :'PAN No',
							width:200,
							tabIndex:10,
							allowBlank:true,
							minLength:5,
							maxLength:50,
							autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
					 },{
							xtype: 'textfield',
							name: 'vendor_servicetaxno',
							id:'vendor_servicetaxno',
							fieldLabel :'Service Tax No',
							width:200,
							allowBlank:true,
							tabIndex:11,
							minLength:5,
							maxLength:50,
							autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
														
					 },{ 
					 		height:10
					},{
							xtype: 'label',
							text: 'Custom Info',
							style: 'padding:0px 0px',
							cls: 'x-form-item myBold'	
					 },{
							xtype: 'textfield',
							name: 'vendor_phone1',
							id:'vendor_phone1',	
							fieldLabel :'Phone1' ,
							width:200,
							tabIndex:13,
							allowBlank:true,
							minLength:10,
							maxLength:13,
							autoCreate: {tag: 'input', type: 'text',  maxlength: '13'}
							,enableKeyEvents: true
							,listeners:{
								keyup: validphoneno
							}
					 },{
							xtype: 'textfield',
							name: 'vendor_phone2',
							id:'vendor_phone2',
							fieldLabel :'Phone2' ,
							width:200,
							tabIndex:14,
							allowBlank:true,
							minLength:10,
							maxLength:13,
							autoCreate: {tag: 'input', type: 'text',  maxlength: '13'}
							,enableKeyEvents: true
							,listeners:{
								keyup: validphoneno
							}
					 },{
							xtype: 'textfield',
							name: 'vendor_email',
							id:'vendor_email',
							fieldLabel :'Email' ,
							width:200,
							tabIndex:15,
							allowBlank:true,
							vtype:'email',
							autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
					 },{
							xtype: 'textfield',
							name: 'vendor_website',
							id:'vendor_website',
							fieldLabel :'Website' ,
							width:200,
							tabIndex:16,
							allowBlank:true,
							vtype:'url',
							autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
					 },{
							xtype: 'textfield',
							name: 'vendor_id',
							id:'vendor_id',
							hidden:true,
							height:10
					 },{
							xtype: 'textfield',
							name: 'account_id',
							id:'account_id',
							hidden:true,
							height:10
					 }]
			}],
			buttonAlign: 'center',
		    buttons:[
		  {
            	text: 'Save',
				iconCls: 'icon-save',
				tabIndex:17,
				handler: function () {
					vendorgridForm.getForm().submit({
						waitMsg: 'Saving...',		
						success: function () {
										
								  Ext.MessageBox.show({
										   title: 'Message',
										   msg: 'Data has been saved',
										   buttons: Ext.MessageBox.OK,
										   icon:Ext.MessageBox.INFO
										  });	
										store.load();
										grid.getSelectionModel().clearSelections();
										vendorgridForm.getForm().reset();
							
												 							    							 
						},
						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:18,
				handler: function () {
						vendorgridForm.getForm().reset();
						grid.getSelectionModel().clearSelections();
						grid.removeButton.disable();

						
				}	
        	},
			{
            	text: 'Close',
				iconCls: 'icon-close',
				tabIndex:19,
				handler: function(){
					
						vendorWindow.close();
				}
        	}
		]
			     
        }/*,
				{
					title: 'Vendor Product',
					id:'tbl2',
					// items: [userGrid]
				},{
					title: 'Order History',
					closable: true
				}*/]}
        ]
    });
	
 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.";
     }
    }
   });
  });
 vendorgridForm.getForm().findField('vendor_orgname').on('blur',function (){
		var vendorname=vendorgridForm.getForm().findField('vendor_orgname').getValue();
		var vendorid=vendorgridForm.getForm().findField('vendor_id').getValue();	
		var resbool="";		
		if(vendorname!="")
		{			
			Ext.Ajax.request({
					  loadMask: true,
					  sync : true,
					  url: 'data/vendorrepeat-entry.php',
					  params: {vendorname: vendorname,vendorid:vendorid},
					  success: function(resp) {
						resbool=Ext.decode(resp.responseText).success;	
								if(resbool=='false')
								{
									Ext.MessageBox.show({
									   title: 'Error',
									   msg: 'Vendor Name already exists!',
									   buttons: Ext.MessageBox.OK,
									   icon:Ext.MessageBox.ERROR
									});
								
									vendorgridForm.getForm().findField('vendor_orgname').reset();											
									Ext.getCmp('vendor_orgname').focus('', 10);
									}
										
					  }				
					});		
		}

	});	
 
 	var vendorWindow = new Ext.Window({
        title: 'Vendor Information',
		width:1000,		
		height:550,	
        frame: true,
		border: false,
		modal:true,
		layout: 'fit',
		closeAction:'close',
		collapsible:true,
		items: vendorgridForm
		

	});
	var varWidth =  (screen.width - vendorWindow.width)/5;
	vendorWindow.setPosition(varWidth,((screen.height/4)-110));
	vendorWindow.show();
	Ext.getCmp('groupname').focus(true,500);
	
});