var labelArray;
labelArray = [ 	['Vendor Name :<span class="comp">*</span>'],
				['Payment Type :<span class="comp"></span>'],
				['Invoice No :<span class="comp">*</span>'],
				['Date :<span class="comp">*</span>']			
		
			];
	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();
                }
            }
        }
    }); 
	Ext.override(Ext.Editor, {
    onBlur: function() {
        if (this.allowBlur === true && this.editing) {
            this.completeEdit();
        }
    }
});
 	
store = new Ext.data.JsonStore({
       	autoDestroy: true,
        url:'data/invoice-grid-filter.php',
        remoteSort: true,
        sortInfo: {
            field: 'invoice_id',
            direction: 'ASC'
        },        
        idProperty: 'invoice_id',
        root: 'data',
        totalProperty: 'total',
        fields: [{
            name: 'invoice_id',
			type: 'int'
        },
		{
			name:'vendor_id'
		},{
			name:'vendor_orgname'
		}, {
            name: 'invoice_no'
        }, {
            name: 'invoice_date'
        },{
            name: 'invoice_paymenttype'
        }] 
    });
	  var filters = new Ext.ux.grid.GridFilters({
        encode: encode,
        local: false,                                      
		filters: [{
				  type: 'numeric',
            dataIndex: 'invoice_id',
			 phpMode: true
        },{
            dataIndex: 'vendor_orgname',
			type: 'string'
        },{
			type: 'string',
            dataIndex: 'invoice_no',
			phpMode: true

        }, {
            dataIndex: 'invoice_date 	',
			type: 'date'
        }]
    });
	
var createColModel = function (finish, start) {
        var columns = [
		sm2,
		{
            dataIndex: 'invoice_id',
			header: 'INVOICE ID',
			hidden:true,
			filterable: true
        }, {
            dataIndex: 'vendor_orgname',
			header: 'Vendor Name'
        }, {
            dataIndex: 'invoice_no',
			header: 'Invoice No',
			filterable: true,
			width: 140
			
        }, {
            dataIndex: 'invoice_date',
			header: 'Date',
			hidden:true
        }];
		return new Ext.grid.ColumnModel({
            columns: columns.slice(start || 0, finish),
            defaults: {
                sortable: true
            }
        });
    };
	

		



var moviesDataStore = new Ext.data.JsonStore({
    url: 'data/getvendor.php',  
    baseParams: {cmd:'movies' },
    root: 'movies',
	 totalProperty: 'count',
    id: 'vendor_id',
    fields: [
		{ name: 'vendor_id', mapping: 'vendor_id' },
		{ name: 'vendor_orgname', mapping: 'vendor_orgname' },
		{ name: 'vendor_address', mapping: 'vendor_address' }
    ]
});


Ext.onReady(function(){
    Ext.QuickTips.init();
	

var movieTpl = new Ext.XTemplate(
    '<tpl for="."><div class="movie-item">',
        '<h2>{vendor_orgname}</h2>',
        '{vendor_address}',
    '</div></tpl>'
);

var titleSearch = {
    xtype: 'combo',
	id:'vendorid',
	name:'vendorid',
    labelSeparator:'',	
	fieldLabel :labelArray[0] ,
    store: moviesDataStore,
    displayField: 'vendor_orgname',
    typeAhead: false,
    loadingText: 'Searching...',
    emptyText: 'Type 3 letters of vandor name',
    minChars: 3,
	tabIndex:1,
    width: 200,
	allowBlank:false,
   // pageSize: 15,
    //hideTrigger: true,
    triggerAction: 'all',
    tpl: movieTpl,
    itemSelector: 'div.movie-item',
    onSelect: function(record) {
		Ext.getCmp('vendor_id').setValue(record.data.vendor_id);
        this.setValue(record.data.vendor_orgname);
        this.collapse();
		
    }
}

///invoice
 var Productdata = Ext.data.Record.create([
	 		{name: 'id', type: 'string'},
            {name: 'product_name', type: 'string'},
            {name: 'product_qty', type: 'float'},
            {name: 'product_rate', type: 'float'},
            {name: 'product_cost', type: 'float'}]);
			
			
   
	
	var productstore = new Ext.data.Store
	({
		reader: new Ext.data.JsonReader
		({
			id:'product_id',
			fields:['product_id','product_name'],
			root: 'product'
		}),
		proxy: new Ext.data.HttpProxy
		({
			url: 'data/getproduct.php'
		}),autoLoad:true
		
	});
	
	var product_combo = new Ext.form.ComboBox({
				name:'product',
				id:'product',
				displayField:'product_name',
				valueField: 'product_id',
				width:50,	
				allowBlank:false,
				triggerAction:'all',
				mode:'local',
				store: productstore,
				editable:true,
				forceSelection:true
				
	});
	 var reader = new Ext.data.JsonReader({
		  root: 'griddata',
		  idProperty: 'ip',
          fields: [
			{name: 'id', type: 'string'},
            {name: 'product_name', type: 'string'},
            {name: 'product_qty', type: 'float'},
            {name: 'product_rate', type: 'float'},
            {name: 'product_cost', type: 'float'}
        ]

    });
	
var InvoiceproductDataStore = new Ext.data.GroupingStore({
    url: 'data/invoice-product-grid-data.php',
	reader: reader,
	successProperty:'success',
	sortInfo: {field: 'id', direction: 'ASC'},
	groupField: 'id'
});

function confirmdeleteInvoice(){
if(grid.selModel.getCount() == 1)
{
	  Ext.MessageBox.confirm('Confirmation','You are about to delete a Invoice. Continue?', deleteInvoice);
} } 
function deleteInvoice(btn){
    if(btn=='yes'){
         var selections = grid.selModel.getSelections();
         var prez = [];
         for(i = 0; i< grid.selModel.getCount(); i++){
          prez.push(selections[i].json.invoice_id);
         }
         var encoded_array = Ext.encode(prez);
		 Ext.Ajax.request({  
            waitMsg: 'Please Wait',
            url:'data/invoice-grid-delete.php', 
            params: { 
               task: "DELETEEMP", 
               ids:  encoded_array
			   }, 
            success: function(response){
              var result=eval(response.responseText);
              switch(result){
              case 1: 
			  	store.reload();
				grid.getSelectionModel().clearSelections();
				InvoicegridForm.getForm().reset();
				InvoiceproductDataStore.removeAll(); 
				InvoiceTaxDataStore.removeAll(); 
                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 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("InvoicegridForm").getForm().loadRecord(rec);
				Ext.getCmp('vendorid').setValue(rec.data.vendor_orgname);
				grid.removeButton.enable();
				InvoiceproductDataStore.load({params:{
			     		invoice_id:rec.data.invoice_id
		  		 }});
				 InvoiceTaxDataStore.load({params:{
			     		invoice_id:rec.data.invoice_id
		  		 }});
				
				
				
			}
		 }
		}),
        plugins: [filters],
        listeners: {
            render: {
                fn: function(g){
					 store.reload({
                        params: {
                            start: 0,
                            limit: 20  
                        }
                    });
					 g.getSelectionModel().selectRow(0);
                   
                   
                }
            }
        }  ,
		tbar:[
         { 
		    	iconCls: 'icon-add',
           		text: 'Add Invoice',
				ref: '../removeButton',
            	handler: function() {
					
					Ext.getCmp("InvoicegridForm").getForm().reset();
					grid.getSelectionModel().clearSelections();
					grid.removeButton.disable();
               
			    }
              
		            
      		},'-',
			{text: 'Delete Invoice',
            handler: confirmdeleteInvoice,  
            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
    	}
	});
	
	var tax;

    // define a custom summary function
    Ext.grid.GroupSummary.Calculations['totalCost'] = function(v, record, field){
       	Ext.getCmp('invoice_nettotal').setValue(v + (record.data.product_qty * record.data.product_rate));
		Ext.getCmp('invoice_grosstotal').setValue(Math.round(v + (record.data.product_qty * record.data.product_rate)));
		
		vat1=(Ext.getCmp('invoice_nettotal').getValue()*4)/100;
		if(vat1 > 0)
		{
		vat2=(Ext.getCmp('invoice_nettotal').getValue()*1)/100;
		Ext.getCmp('invoice_taxtotal').setValue(tax);
		}
		 return v + (record.data.product_qty * record.data.product_rate);
		
    };

	// utilize custom extension for Group Summary
      var summary = new Ext.grid.GroupSummary();


    var invoicegrid = new xg.EditorGridPanel({
        ds:InvoiceproductDataStore,
		forceValidation: true,
		selModel:  new Ext.grid.RowSelectionModel({singleSelect: true}),
		 columns: [
		  new Ext.grid.RowNumberer(),
		  {
                header: 'Id',
                dataIndex: 'id',
				width: 10,
				hidden:true
            },
            {
                id:'product_name',
                header:'Product',
                width: 100,
                sortable: true,
                dataIndex:'product_name',
                hideable: true,
                summaryRenderer: function(v, params, data){
                    return ('Net Total:');
                },
                editor:product_combo,
				renderer: function(val)
				{
						var r = product_combo.store.getById(val);
						return r ? r.get('product_name') : '';
				}
            },{
                header: 'QTY',
                width: 20,
                sortable: true,
                dataIndex: 'product_qty',
                // summaryType: 'sum',
                renderer : function(v){
                    return v +' Nos';
                },
                editor: new Ext.form.NumberField({
                   allowBlank: false,
                   allowNegative: false,
                   style: 'text-align:left'
                })
            },{
                header: 'Rate',
                width: 20,
                sortable: true,
               /// renderer: Ext.util.Format.indianMoney ,
                dataIndex: 'product_rate',
                //summaryType: 'average',
                editor: new Ext.form.NumberField({
                    allowBlank: false,
                    allowNegative: false,
                    style: 'text-align:left'
                })
            },{
                id: 'product_cost',
                header: 'Cost',
                width: 50,
                sortable: false,
                groupable: false,
                renderer: function(v, params, record){
					 return Ext.util.Format.indianMoney (record.data.product_qty * record.data.product_rate);
					//return (record.data.product_qty * record.data.product_rate);
                },
                dataIndex: 'product_cost',
                summaryType: 'totalCost',
                summaryRenderer: Ext.util.Format.indianMoney 
            }
        ],
		

        view: new Ext.grid.GroupingView({
            forceFit: true,
            showGroupName: false,
            enableNoGroups: true,
			enableGroupingMenu: false,
            hideGroupedColumn: false,
			//groupTextTpl:"" ,
			hideHeaders:true


        }),

      plugins: summary,
	   tbar: [{
             iconCls: 'icon-add',
            text: 'Add item',
			tabIndex:5,
            handler: function(){
				if(Ext.getCmp('vendorid').getValue()!="")
				{
                var e = new Productdata({
					id:'Invoice',
					product_name:'',
					product_qty:1,
					product_rate:0,
                    product_cost: ''
                });
				
                invoicegrid.stopEditing();
				var insert=(invoicegrid.store.getCount());
                invoicegrid.store.insert(insert, e);
                invoicegrid.getView().refresh();
                invoicegrid.getSelectionModel().selectRow(insert);
                invoicegrid.startEditing(insert,2);
				}
				else
				{
					Ext.MessageBox.show({
										   title: 'Error',
										   msg: 'Please Select vendor.',
										   buttons: Ext.MessageBox.OK,
										   icon:Ext.MessageBox.ERROR
										  });	
					
					}
            }
        },{
            ref: '../removeBtn',
            iconCls:'remove',
			tabIndex:6,
            text: 'Delete item',
            disabled: true,
            handler: function(){
                invoicegrid.stopEditing();
                var s = invoicegrid.getSelectionModel().getSelections();
                for(var i = 0, r; r = s[i]; i++){
					      	 invoicegrid.store.remove(r);
				}
				var remove=(invoicegrid.store.getCount()-1);
				if(remove!=-1)
				{
						invoicegrid.getSelectionModel().selectRow(remove);
				        invoicegrid.startEditing(remove,2);
				}
				if(remove==-1)
				{
				 Taxgrid.store.removeAll();	
				 Ext.getCmp('invoice_grosstotal').setValue(0);
				}
			           
				
            }
        }], 
        frame: true,
        width: 600,
        height: 190,
        clicksToEdit: 1,
		frame:false
    });
	 invoicegrid.getSelectionModel().on('selectionchange', function(sm){
     invoicegrid.removeBtn.setDisabled(sm.getCount() < 1);
    });
	
//end invoice

///tax grid
var total
 var tax = Ext.data.Record.create([
	 		{name: 'taxid', type: 'string'},
            {name: 'tax_name', type: 'string'},
            {name: 'tax_percentage', type: 'float'},
            {name: 'tax_amount', type: 'float'}]);

var Taxtstore = new Ext.data.Store
	({
		reader: new Ext.data.JsonReader
		({
			id:'tax_id',
			fields:['tax_id','tax_name'],
			root: 'rows'
		}),
		proxy: new Ext.data.HttpProxy
		({
			url: 'data/gettax.php'
		}),autoLoad:true
		
	});
	var tax_combo = new Ext.form.ComboBox({
				name:'tax',
				id:'tax',
				displayField:'tax_name',
				valueField: 'tax_id',
				width:200,										
				allowBlank:false,
				triggerAction:'all',
				mode:'local',
				store: Taxtstore,
				editable:true,
				forceSelection:true
	});

 var Taxreader = new Ext.data.JsonReader({
	 	root: 'taxgriddata',
		idProperty: 'it',
        fields: [
			{name: 'taxid', type: 'string'},
            {name: 'tax_name', type: 'string'},
            {name: 'tax_percentage', type: 'float'},
            {name: 'tax_amount', type: 'float'}
        ]

    });
var InvoiceTaxDataStore = new Ext.data.GroupingStore({
    url: 'data/invoice-tax-grid-data.php',
	reader: Taxreader,
	successProperty: 'success',
	sortInfo: {field: 'taxid', direction: 'ASC'},
	groupField: 'taxid'
});
			
    // define a custom summary function
    Ext.grid.GroupSummary.Calculations['totalTax'] = function(v, record, field){
	Ext.getCmp('invoice_taxtotal').setValue(v + ((Ext.getCmp('invoice_nettotal').getValue() * record.data.tax_percentage)/100));
	/*if(Ext.getCmp('invoice_taxtotal').getValue()!=0)
	{*/
		//alert(Ext.getCmp('invoice_taxtotal').getValue());
		var grosstotal= parseFloat(Ext.getCmp('invoice_nettotal').getValue()) + parseFloat(Ext.getCmp('invoice_taxtotal').getValue()); 
		Ext.getCmp('invoice_grosstotal').setValue(Math.round((grosstotal*100)/100));
	//}
	return v + ((Ext.getCmp('invoice_nettotal').getValue() * record.data.tax_percentage)/100);
		
    };

	// utilize custom extension for Group Summary
      var summary = new Ext.grid.GroupSummary();
      var Taxgrid = new xg.EditorGridPanel({
        ds: InvoiceTaxDataStore,
		selModel:  new Ext.grid.RowSelectionModel({singleSelect: true}),
		 columns: [
		  new Ext.grid.RowNumberer(),
		  {
                header: 'Id',
                dataIndex: 'taxid',
				width: 10,
				hidden:true
            },
            {
                id: 'tax_name',
                header: 'Taxes',
                width: 100,
                sortable: true,
                dataIndex: 'tax_name',
                hideable: true,
                summaryRenderer: function(v, params, data){
                    return ('Tax Total :');
                },
                editor:tax_combo,
				renderer: function(value)
				{
						var r = Taxtstore.getById(value);
						return r ? r.get('tax_name') : '';
				}
            },{
                header: 'Rate',
                width: 20,
                sortable: true,
                dataIndex: 'tax_percentage',
                // summaryType: 'sum',
                renderer : function(v){
                    return v +'%';
                },
                editor: new Ext.form.NumberField({
                   allowBlank: false,
                   allowNegative: false,
                   style: 'text-align:left'
                })
            },{
                id: 'tax_amount',
                header: 'Cost',
                width: 50,
                sortable: false,
                groupable: false,
                renderer: function(v, params, record){
			Ext.getCmp('invoice_taxtotal').setValue((Ext.getCmp('invoice_nettotal').getValue() * record.data.tax_percentage)/100);
             return Ext.util.Format.indianMoney ((Ext.getCmp('invoice_nettotal').getValue() * record.data.tax_percentage)/100);
               },
                dataIndex: 'tax_amount',
                summaryType: 'totalTax',
                summaryRenderer: Ext.util.Format.indianMoney 
            }
        ],
		

        view: new Ext.grid.GroupingView({
            forceFit: true,
            showGroupName: false,
            enableNoGroups: true,
			enableGroupingMenu: false,
            hideGroupedColumn: false,
			//groupTextTpl:"" ,
			hideHeaders:true


        }),

      plugins: summary,
	   tbar: [{
             iconCls: 'icon-add',
            text: 'Add TAX',
			tabIndex:7,
            handler: function(){
				if(invoicegrid.store.getCount() >0 )
				{
					if(Ext.getCmp('invoice_nettotal').getValue()!=0)
					{
							if(Taxgrid.store.getCount()==0)
							{
							var f = new tax({
									taxid:'Tax',
									tax_name:'1',
									tax_percentage:4,
									tax_amount: ''
								});
								
								Taxgrid.stopEditing();
								var insert=(Taxgrid.store.getCount());
								Taxgrid.store.insert(insert, f);
								Taxgrid.getView().refresh();
								//Taxgrid.getSelectionModel().selectRow(insert);
								//Taxgrid.startEditing(insert,2);
								var f1 = new tax({
									taxid:'Tax',
									tax_name:'2',
									tax_percentage:1,
									tax_amount: ''
								});
								Taxgrid.stopEditing();
								var insert=(Taxgrid.store.getCount());
								Taxgrid.store.insert(insert, f1);
								Taxgrid.getView().refresh();
								//Taxgrid.getSelectionModel().selectRow(insert);
								//Taxgrid.startEditing(insert,2);
							}
							else
							{
							
							
							var f = new tax({
								taxid:'Tax',
								tax_name:'',
								tax_percentage:0,
								tax_amount:''
							});
							Taxgrid.stopEditing();
							var insert=(Taxgrid.store.getCount());
							Taxgrid.store.insert(insert, f);
							Taxgrid.getView().refresh();
							Taxgrid.getSelectionModel().selectRow(insert);
							Taxgrid.startEditing(insert,2);
						  
						   }
					}
						else
						{
							Ext.MessageBox.show({
										   title: 'Error',
										   msg: 'Net total Must be greter Than 0.',
										   buttons: Ext.MessageBox.OK,
										   icon:Ext.MessageBox.ERROR
										  });	
						}
				}
				else
				{
					Ext.MessageBox.show({
										   title: 'Error',
										   msg: 'Please Add product.',
										   buttons: Ext.MessageBox.OK,
										   icon:Ext.MessageBox.ERROR
										  });				
				}
            }
        },
			 {
            ref: '../removeBtn',
            iconCls:'remove',
			tabIndex:8,
            text: 'Delete Tax',
            disabled: true,
            handler: function(){
                Taxgrid.stopEditing();
                var s = Taxgrid.getSelectionModel().getSelections();
                for(var i = 0, r; r = s[i]; i++){
					  Taxgrid.store.remove(r);
		
				}
				var remove=(Taxgrid.store.getCount()-1);
				if(remove!=-1)
				{
						Taxgrid.getSelectionModel().selectRow(remove);
				        Taxgrid.startEditing(remove,2);
						Ext.getCmp('invoice_taxtotal').setValue(0);
				}
				if(remove==-1)
				{
					//Ext.getCmp('invoice_taxtotal').setValue(0);
					 
					Ext.getCmp('invoice_grosstotal').setValue(Math.round(Ext.getCmp('invoice_nettotal').getValue()*100)/100);
				}
			           
				
            }
        }], 
        frame: true,
        width: 600,
        height: 150,
        clicksToEdit: 1,
		frame:false
    });
	 Taxgrid.getSelectionModel().on('selectionchange', function(sm){
     Taxgrid.removeBtn.setDisabled(sm.getCount() < 1);
    });
//endtaxgrid
	
var flgalert = 0;
 var InvoicegridForm = new Ext.FormPanel({
        id: 'InvoicegridForm',
        frame: true,
		url:'save-invoice.php',
        bodyStyle:'padding:5px',
        layout: 'column', 
		height:498,	
        items: [{
            columnWidth: 0.3,
            layout: 'fit',
            items:[grid]
        },{
            columnWidth: 0.7,
            xtype: 'fieldset',
			defaults: {border:false},
            autoHeight: true,
			bodyStyle: Ext.isIE ? 'padding:0 0 5px 15px;' : 'padding:0px 0px;',
            items: [{
            //title: 'Invoice Information',
			layout: 'column', 
			 defaults: {
             bodyStyle: 'padding:8px;'
        },
			items: [{
				columnWidth: 0.5,
				labelWidth:95,
				layout: 'form',
				items:[/*{
							xtype: 'label',
							text: 'Basic',
							style: 'padding:0px 0px',
							cls: 'x-form-item myBold',	
					 	},*/titleSearch,{
							xtype: 'textfield',
							name: 'invoice_paymenttype',
							id:'invoice_paymenttype',
							labelSeparator:'',	
							fieldLabel :labelArray[1] ,
							width:100,
							tabIndex:3,
							allowBlank:true
					 }]
			},{	
            columnWidth: 0.5,
			layout: 'form',
			labelWidth:75,
			items: [/*{
							xtype: 'label',
							text: 'Address',
							cls: 'x-form-item myBold',	
					 },*/{
							xtype: 'textfield',
							name: 'invoice_no',
							id:'invoice_no',	
							labelSeparator:'',	
							fieldLabel :labelArray[2] ,
							width:150,
							tabIndex:2,
							allowBlank:false,
							minLength:2,
							maxLength:50
							
							
					 },{
							xtype: 'datefield',
							name: 'invoice_date',
							id:'invoice_date',
							labelSeparator:'',	
							fieldLabel :labelArray[3] ,
							width:100,
							tabIndex:4,
							allowBlank:false
							
							
					 }]
			},
			{columnWidth: 1,
				layout: 'form',
				items:[invoicegrid,Taxgrid]},{
						 columnWidth: 1,
						layout: 'form',
						items:[{
							xtype: 'textfield',
							name: 'invoice_grosstotal',
							id:'invoice_grosstotal',
							labelStyle: 'margin-left:210px;font-weight: bold; color:#F12536',
							fieldLabel :'Gross Total ',
							readOnly:true
							//hidden:true
						}] },{
							xtype: 'textfield',
							name: 'invoice_id',
							id:'invoice_id',
							hidden:true
					 },{
							xtype: 'textfield',
							name: 'vendor_id',
							id:'vendor_id',
							hidden:true
					 },{
							xtype: 'textfield',
							name: 'invoice_nettotal',
							id:'invoice_nettotal',
							hidden:true
						},{
							xtype: 'textfield',
							name: 'invoice_taxtotal',
							id:'invoice_taxtotal',
							hidden:true
						},{
							xtype: 'textfield',
							name: 'tempqty',
							id:'tempqty',
							hidden:true
						}],
			buttonAlign: 'center',
		    buttons:[/*{
            	text: 'View Invoice',
				iconCls: 'icon-view',
				tabIndex:12,
				handler: function(){
					
					if(Ext.getCmp('invoice_id').getValue()!="")
					{
					
						InvoicegridForm.getForm().getEl().dom.target = '_blank';
						InvoicegridForm.getForm().getEl().dom.action = 'report-form-vendor-invoice-result.php';
						InvoicegridForm.getForm().getEl().dom.submit(
						{
							waitMsg: 'Saving...',
							success: function (){},
							failure: function (){
								Ext.Msg.alert ('Error Message','Please fill up complete form.');
							}
						});	
						}
					else
					{
						Ext.MessageBox.show({
										   title: 'Error',
										   msg: 'Please Select record or save record.',
										   buttons: Ext.MessageBox.OK,
										   icon:Ext.MessageBox.ERROR
										  });
						
					}
				}
        	},*/
		  {
            	text: 'Save',
				iconCls: 'icon-save',
				tabIndex:10,
				handler: function () {
					var p=0;
					var productidarray = new Array();	
					var productqtyarray = new Array();
					var productratearray = new Array();
					var t=0;
					var taxidarray = new Array();	
					var taxpercentagearray = new Array();
					if(invoicegrid.store.getCount()!=0)
					{
						for(var i = 0, len = invoicegrid.store.getCount(); i < len; i++){
							record = invoicegrid.store.getAt(i);
							productid= record.data.product_name;
							productqty= record.data.product_qty;
							productrate= record.data.product_rate;
							productidarray[p] =  productid;
							productqtyarray[p]=  productqty;
							productratearray[p] = productrate;
							p++;
						}
						for(var i = 0, len = Taxgrid.store.getCount(); i < len; i++){
						record = Taxgrid.store.getAt(i);
						taxid = record.data.tax_name;
						taxpercentage=record.data.tax_percentage;
						
							taxidarray[t] =  taxid;
							taxpercentagearray[t]=taxpercentage;
							t++;
						}
						InvoicegridForm.getForm().submit({
						waitMsg: 'Saving...',	
						params:{
								productid: Ext.util.JSON.encode(productidarray),
								productqty: Ext.util.JSON.encode(productqtyarray),
								productrate: Ext.util.JSON.encode(productratearray),
								taxid: Ext.util.JSON.encode(taxidarray),
								taxpercentade: Ext.util.JSON.encode(taxpercentagearray)
							},	
						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();
										InvoicegridForm.getForm().reset();
										InvoiceproductDataStore.removeAll(); 
										InvoiceTaxDataStore.removeAll(); 
							
												 							    							 
						},
						failure: function () {		
							Ext.MessageBox.show({
										   title: 'Error',
										   msg: 'Please fill complete form.',
										   buttons: Ext.MessageBox.OK,
										   icon:Ext.MessageBox.ERROR
										  });
						}
					});
					}
					else
					{
						alert("please select atlist one product");	
					}
					
				}
          	},
			{
		    	text: 'Reset',
				iconCls: 'icon-reset',
				tabIndex:11,
				handler: function () {
					
						InvoicegridForm.getForm().reset();
						grid.getSelectionModel().clearSelections();
						grid.removeButton.disable();
						
						invoicegrid.stopEditing();
						InvoiceproductDataStore.removeAll(); 
						Taxgrid.stopEditing();
 						InvoiceTaxDataStore.removeAll(); 
						
				}	
        	},
			{
            	text: 'Close',
				iconCls: 'icon-close',
				tabIndex:12,
				handler: function(){
						InvoiceWindow.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.";
     }
    }
   });
  });
    var Multistring = "";
	var DataArray=new Array();
    var counter=0;
	var p=0;
   invoicegrid.on('validateedit',function validateedit(e) {
	/*alert(e.record.data['product_name']);
	if(e.record.data['product_name']=="")
	{
		Ext.MessageBox.show({
	   title: 'Error',
	   msg: 'Please select Product First',
	   buttons: Ext.MessageBox.OK,
	   icon:Ext.MessageBox.ERROR
	  });
	}  */
   if(e.field=="product_qty")
	{ if(e.value > 0)
		{
			//e.cancel=true;
			Ext.Msg.confirm('Confirmation', 'Do u Want to Insert Serial Number For This Product?', function(btn, text){
			if (btn == "yes"){
				
				var productid=e.record.data['product_name'];
					
				r=product_combo.store.getById(productid);
				var wintitle ="Serial No For " + r.get('product_name');
				var Srnodata = Ext.data.Record.create([
           		{name: 'product_id',type: 'int'},
				{name: 'product_srno',type: 'float'}]);
				
			var SrnoDataStore = new Ext.data.ArrayStore({
				fields: [{name: 'product_id',type: 'int'},
						{name: 'product_srno', type: 'float'}]
			});
			 var Sirnogrid = new xg.EditorGridPanel({
					store:SrnoDataStore,
					forceValidation: true,
					selModel:  new Ext.grid.RowSelectionModel({singleSelect: true}),
					columns: [
					  new Ext.grid.RowNumberer(),
					  {
							header: 'Serial No',
							width: 230,
							sortable: true,
							dataIndex: 'product_srno',
							editor: new Ext.form.TextField({
							   allowBlank: false,
							   allowNegative: false,
							   style: 'text-align:left'
							})
						}
					],
					width: 270,
					clicksToEdit: 1,
					autoHeight: true,
					frame:false,
					stateful: true,
        			stateId: 'grid'
					
				});
		       var win = new Ext.Window({
			   title: wintitle,
						pageX: 100,
						pageY: 100,
						width:280,
						height:100,	
						closeAction:'hide',
						autoHeight: true,
						items:Sirnogrid
					});
					      win.doLayout();
						  win.show();
						  //alert(e.originalValue);
						  var count=e.value;
						  var arlene = Multistring.match(e.row);
							if(arlene==null)
							{
								Multistring+=e.row + ",";
								 for(i=1;i<=count;i++)
								  {
									 var insertsrdata = new Srnodata({
												product_id:productid,
												product_srno:''
										});
										var insert=(Sirnogrid.store.getCount());
										Sirnogrid.store.insert(insert,insertsrdata);
										Sirnogrid.getView().refresh();
										Sirnogrid.getSelectionModel().selectRow(0);
										Sirnogrid.startEditing(0,0);
									}	
							}
							else
							{
								
								
								
								count=e.value - e.originalValue;
									Sirnogrid.store.loadData(DataArray);
									Sirnogrid.store.filter('product_id',productid);
								if(e.value > e.originalValue)
								{
									for(i=1;i<=count;i++)
									{
										 var insertsrdata = new Srnodata({
													product_id:productid,
													product_srno:''
											});
											var insert=(Sirnogrid.store.getCount());
											Sirnogrid.store.insert(insert,insertsrdata);
											Sirnogrid.getView().refresh();
											Sirnogrid.getSelectionModel().selectRow(0);
											Sirnogrid.startEditing(0);
									}
							    
								}
								
								
							}
							
						 								
							win.show();	
							win.syncShadow();	
							
							/*function editStore(Se) {
								if (Se.field == 'product_srno') {
									alert(Se.value);
									 if(Se.value.dirty)
										 {
											alert("Empty Data not Allow"); 
										 }
								  }
								
							 }*/
							 
							win.on('beforehide',function(){
								var cnt=0;
							if(Sirnogrid.store.getCount()!=0)
							{
							 var len = Sirnogrid.store.getCount(); 
							 for(var i = 0; i < len; i++){
								record = Sirnogrid.store.getAt(i);
								if(record.data.product_srno!="")
								{
									DataArray[p] = [record.data.product_id,record.data.product_srno];							
									p++;
								}else
								{
									cnt++;
									
								}
							}
								if(cnt>0)
								{	alert("Empty Data not Allow");
								 	win.show(this);
								}
								DataArray=sortAndRemoveDuplicates(DataArray);
								alert("Real Array"+DataArray);
							}else
							{
								alert("Empty Not Allow");
								 win.show();
							}
						 });			 
			  	}
			});
		}
	}
});
 	var InvoiceWindow = new Ext.Window({
        title: 'Invoice Information',
		width:1000,		
		height:550,	
        frame: true,
		border: false,
		modal:true,
		layout: 'fit',
		collapsible:true,
		closeAction:'close',
		items: InvoicegridForm
	});
	var varWidth =  (screen.width - InvoiceWindow.width)/5;
	InvoiceWindow.setPosition(varWidth,((screen.height/4)-110));
	InvoiceWindow.show();
	Ext.getCmp('vendorid').focus(true,500);
});