var selqty=0;
var labelArray1;
labelArray1 = [ 	['Customer :<span class="comp">*</span>'],
				['Remark :<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;
	 
	  	
store1 = new Ext.data.JsonStore({
		autoLoad:true,
       	autoDestroy: true,
        url:'data/customerinvoice-grid-filter.php',
        remoteSort: true,
        sortInfo: {
            field: 'customerinvoice_id',
            direction: 'ASC'
        },        
        idProperty: 'customerinvoice_id',
        root: 'data',
        totalProperty: 'total',
        fields: [{
            name: 'customerinvoice_id',
			type: 'int'
        },
		{
			name:'customer_id'
		},{
			name:'customer_orgname'
		},{
			name:'customer_address'
		}, {
            name: 'customerinvoice_no'
        }, {
            name: 'customerinvoice_date'
        },{
            name: 'remark'
        },
		{
            name: 'year_id'
        },
		{
            name: 'status'
        },{
		  name:'dueamount'
		 },
		 {
			 name:'tamount'
		 }] 
    });
	  var filter1 = new Ext.ux.grid.GridFilters({
        encode: encode,
        local: false,                                      
		filters: [{
				  type: 'numeric',
            dataIndex: 'customerinvoice_id',
			 phpMode: true
        },
		{
			type: 'string',
            dataIndex: 'customerinvoice_no',
			phpMode: true

        },{
            dataIndex: 'customer_orgname',
			type: 'string',
			phpMode: true
        }, {
            dataIndex: 'customerinvoice_date',
			type: 'date'
        }]
    });
	
var createColModel1 = function (finish, start) {
        var columns = [
		{
            dataIndex: 'customerinvoice_id',
			header: 'Vendor ID',
			hidden:true,
			filterable: true
        }, {
            dataIndex: 'customerinvoice_no',
			header: 'INo',
			filterable: true,
			width: 45
			
        },{
			id:'customer_orgname',
			name:'customer_orgname',
            dataIndex: 'customer_orgname',
			header: 'Customer Name',
			filterable: true,
			width: 165
        },  {
            dataIndex: 'customerinvoice_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/getcustomer.php',  
    baseParams: {cmd:'movies' },
    root: 'movies',
	totalProperty: 'count',
    id: 'customer_id',
    fields: [
		{ name: 'customer_id', mapping: 'customer_id' },
		{ name: 'customer_orgname', mapping: 'customer_orgname' },
		{ name: 'customer_address', mapping: 'customer_address' }
    ]
});


var custname_store = new Ext.data.Store({
		url: 'data/getcustomername1.php',          
		reader: new Ext.data.JsonReader({			
		fields: ['customer_id','customer_orgname','customer_address','amount_desc','dueamount'],
		root: 'rows'
		}),autoLoad:true
	});

var myMask;
var gridmask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait while data is loading...",store:store1});  
Ext.onReady(function(){
    Ext.QuickTips.init();
	myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait while data is loading..."});  
var movieTpl = new Ext.XTemplate(
    '<tpl for="."><div class="movie-item">',
        '<h2>{customer_orgname}</h2>',
        '{customer_address}',
    '</div></tpl>'
);

var titleSearch = {
	
    xtype: 'combo',
	id:'customer_id',
	name:'customer_id',
	mode:'local',
    labelSeparator:'',
	//hiddenName: 'customer_idhedden',	
	fieldLabel :labelArray1[0] ,
    store: custname_store,
    displayField: 'customer_orgname',
	valueField: 'customer_id',
    emptyText: 'Type 3 letters of Customer name',
	tabIndex:1,
    width: 210,
	forceSelection:true,
	allowBlank:false,
    triggerAction: 'all',
 	listeners:{select:{fn:function(combo, value) 
	{	  	 			 
		 var varcustid=0; 
		
		 varcustid=combo.getValue('customer_id'); 											      
		 
		 var custid = vendorgridForm.getForm().findField('customer_id').getValue(); 
		 
		 Ext.getCmp('customer_id1').setValue(custid);
		 Ext.Ajax.request(
		 {
			  loadMask: true,
			  sync : true,
			  url:'data/getaddress.php',
			  params: {customer_id: custid},
			  waitMsg:'Loading',
			  failure: function() {
					 Ext.MessageBox.show({
						   title: 'Error',
						   msg: 'Invalid ',
						   buttons: Ext.MessageBox.OK,
						   icon:Ext.MessageBox.ERROR
						  });
			},
			success: function(resp) 
			{ 
					varcsno=Ext.decode(resp.responseText).add;
					if(varcsno != "")
					{ 
					vendorgridForm.getForm().findField('customer_address').setValue(varcsno); 			
					}
					else
					{	  
						 Ext.getCmp("customer_address").reset();											     
					}
			}				
		});
		
	}}},
}

///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/customerinvoice-product-grid-data.php',
	reader: reader,
	successProperty: 'success',
	sortInfo: {field: 'id', direction: 'ASC'},
	groupField: 'id'
});

  var gridView = new Ext.grid.GridView({ 
    getRowClass : function (row, index) { 
      var cls = ''; 
      var data = row.data; 
	
	  if(data.status=='Cancelled') 
			{ 
				cls = 'red-row' ;
				
			}
	
		
      return cls; 
   } 
}); 
var grid1 = new Ext.grid.GridPanel({
        store: store1,
        colModel: createColModel1(40), 
        loadMask: true,
		frame: true,
		enableColLock:false,
		height: 500,    
        width: 300,
        layout: 'fit',
		view: gridView,
		columnLines:true,
		selModel:  new Ext.grid.RowSelectionModel({
		singleSelect: true,
		listeners: {
			rowselect: function(sm, row, rec) {
				myMask.show();				
				Ext.getCmp('btnSave').disable();
				Ext.getCmp("vendorgridForm").getForm().loadRecord(rec);
				
				if(rec.data.status == 'Cancelled')
					{Ext.getCmp('statusflag').setValue(true);}
				else
					{Ext.getCmp('statusflag').setValue(false);}
				
				Ext.getCmp('customer_id').setValue(rec.data.customer_orgname);
				Ext.getCmp('customer_id1').setValue(rec.data.customer_id);
				
				
				InvoiceproductDataStore.load({params:{
							customerinvoice_id:rec.data.customerinvoice_id
					 },'callback':function(){
						 myMask.hide();
						 if(rec.data.status == 'Paid')	
						  {
						   Ext.getCmp('btnSave').disable();
						   Ext.getDom('headertitle').innerHTML = "this invoice is Paid and dueamount is = "+rec.data.dueamount+"";
						  }
						 else if(rec.data.status == 'DuePayment' && rec.data.dueamount!== rec.data.tamount)
						 {
							  Ext.getCmp('btnSave').disable();
							  Ext.getDom('headertitle').innerHTML = "this invoice is Partial Paid and dueamount is = "+rec.data.dueamount+"";
						 }
						 else
						  {
						     Ext.getCmp('btnSave').enable();
							 Ext.getDom('headertitle').innerHTML = "this invoice is newly Generated and dueamount is = "+rec.data.dueamount+"";
						  }
					 }
				 });
				 InvoiceTaxDataStore.removeAll();
				 InvoiceTaxDataStore.load({params:{
			     		customerinvoice_id:rec.data.customerinvoice_id
		  		 }});				
				
			}
		 }
		}),
        plugins: [filter1],
		
		tbar: [
		   new Ext.form.TriggerField({
                xtype: 'triggerfield',
				id:'searchinvoice',
                triggerClass: 'x-form-clear-trigger',
               	emptyText:'Inv No',
				width:60,
				//style:'margin-right:10px;',
				enableKeyEvents: true,
				listeners: {
							 keyup: function(){store1.filter('customerinvoice_no',this.getValue(),false);}
				},
				onTriggerClick : function(){
					this.reset();
					store1.filter('customerinvoice_no','',true)			
				  }

            }),
		    new Ext.form.TriggerField({
                xtype: 'triggerfield',
				id:'searchtrigger',
                triggerClass: 'x-form-clear-trigger',
               	emptyText:'Search Customer',
				width:165,
				enableKeyEvents: true,
				listeners: {
							 keyup: function(){store1.filter('customer_orgname',this.getValue(),true);}
				},
				onTriggerClick : function(){
					this.reset();
					store1.filter('customer_orgname','',true)			
				  }

            })
			]
       
    });

   
	

	
	var tax;

    // define a custom summary function
    Ext.grid.GroupSummary.Calculations['totalCost'] = function(v, record, field){
	
       	Ext.getCmp('customerinvoice_nettotal').setValue(v + (record.data.product_qty * record.data.product_rate));
		Ext.getCmp('customerinvoice_grosstotal').setValue(Math.round(v + (record.data.product_qty * record.data.product_rate)));
		
		vat1=(Ext.getCmp('customerinvoice_nettotal').getValue()*4)/100;
		if(vat1 > 0)
		{
		vat2=(Ext.getCmp('customerinvoice_nettotal').getValue()*1)/100;
		Ext.getCmp('customerinvoice_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',
				hidden:true
            },
            {
                id:'product_name',
                header:'Product',
                width: 140,
                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: 30,
                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: 50,
                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: 60,
                sortable: false,
                groupable: false,
                renderer: function(v, params, record){
					 return Ext.util.Format.indianMoney (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('customer_id').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('customerinvoice_grosstotal').setValue(0);
				}
			           
				
            }
        },
		     {
             iconCls: 'icon-add',
            text: 'Add New Product',
			tabIndex:6,
            handler: function(){
			ProductWindow.show();
			Ext.getCmp("ProductgridForm").getForm().reset();
					prodgrid.getSelectionModel().clearSelections();
					prodgrid.removeButton.disable();

						 
					
            }
        }
		      ], 
        frame: true,
        width: 555,
        height: 180,
        clicksToEdit: 1
    });
	 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/customerinvoice-tax-grid-data.php',
	reader: Taxreader,
	successProperty: 'success',
	sortInfo: {field: 'taxid', direction: 'ASC'},
	groupField: 'taxid'
});
	/*InvoiceTaxDataStore.on('load', function(store, records) 
	{*/
    	Ext.grid.GroupSummary.Calculations['totalTax'] = function(v, record, field){
		Ext.getCmp('customerinvoice_taxtotal').setValue(v + ((Ext.getCmp('customerinvoice_nettotal').getValue() * record.data.tax_percentage)/100));
		var grosstotal= parseFloat(Ext.getCmp('customerinvoice_nettotal').getValue()) + parseFloat(Ext.getCmp('customerinvoice_taxtotal').getValue()); 
		Ext.getCmp('customerinvoice_grosstotal').setValue(Math.round((grosstotal*100)/100));
	return v + ((Ext.getCmp('customerinvoice_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('customerinvoice_taxtotal').setValue((Ext.getCmp('customerinvoice_nettotal').getValue() * record.data.tax_percentage)/100);
             	return Ext.util.Format.indianMoney ((Ext.getCmp('customerinvoice_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('customerinvoice_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('customerinvoice_taxtotal').setValue(0);
				}
				if(remove==-1)
				{
					//Ext.getCmp('customerinvoice_taxtotal').setValue(0);
					 
					Ext.getCmp('customerinvoice_grosstotal').setValue(Math.round(Ext.getCmp('customerinvoice_nettotal').getValue()*100)/100);
				}
			           
				
            }
        }], 
        frame: true,
        width: 555,
        height: 135,
        clicksToEdit: 1
    });
	 Taxgrid.getSelectionModel().on('selectionchange', function(sm){
        Taxgrid.removeBtn.setDisabled(sm.getCount() < 1);
    });
//endtaxgrid
	
var flgalert = 0;
 var vendorgridForm = new Ext.FormPanel({
        id: 'vendorgridForm',
        frame: true,
		url:'save-customerinvoice.php',
        bodyStyle:'padding:5px',
        layout: 'column', 
		height:498,	
        items: [{
            columnWidth: 0.3,
            layout: 'fit',
            items:[grid1]
        },{
            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:5px;'
        },
			items: [{
				columnWidth: 0.60,
				labelWidth:74,
				layout: 'form',
				items:[{
					columnWidth: 1,
					layout: 'column',	
					items:[
					{columnWidth: .880,
					layout: 'form',
					items:[titleSearch]},
					{columnWidth: .1,
					layout: 'form',	
						
					items:[{xtype:'button',
						   //text:'Add',
						  iconCls:'icon-add',
						  btnAlign:'left',
						  tooltip:'Add or update Customer Details',
							handler: function ()
							{
							 CustomerWindow.show();
 							 CustomergridForm.getForm().reset();
 							grid.getSelectionModel().clearSelections();
							//grid.removeButton.disable();
							 store.load();
							}
							}]}]},
							{
							xtype: 'textarea',
							name: 'customer_address',
							id:'customer_address',
							labelSeparator:'',	
							fieldLabel :'Address :' ,
							width:210,
							height:35,
							tabIndex:3,
							allowBlank:true
					 },
							{
							xtype: 'textarea',
							name: 'remark',
							id:'remark',
							labelSeparator:'',	
							fieldLabel :labelArray1[1] ,
							width:210,
							height:25,
							tabIndex:3,
							allowBlank:true
					 }]
			},{	
            columnWidth: 0.40,
			layout: 'form',
			labelWidth:75,
			items: [{
							xtype: 'textfield',
							name: 'customerinvoice_no',
							id:'customerinvoice_no',	
							labelSeparator:'',	
							fieldLabel :labelArray1[2] ,
							width:130,
							tabIndex:2,
							readOnly:true,
							allowBlank:false,
							minLength:1,
							maxLength:50
							
							
					 },{
							xtype: 'datefield',
							name: 'customerinvoice_date',
							id:'customerinvoice_date',
							labelSeparator:'',	
							fieldLabel :labelArray1[3] ,
							width:120,
							tabIndex:4,
							value:new Date(),
							allowBlank:false
							
							
					 },
					 {
						 height:10
					 },
					 {
								xtype:'checkbox',
								id: 'headerflag',
								name: 'headerflag',
								style:"margin-bottom:4px",
								fieldLabel: 'Print Header',
								checked :false
							}]
			},
			{columnWidth: 1,
				layout: 'form',
				items:[invoicegrid,{height:5},Taxgrid]},
					{
						 columnWidth: 1,
						layout: 'column',
						items:[{
				columnWidth: 0.5,
				layout: 'form',
				labelWidth:100,
				items:[{
								xtype:'checkbox',
								id: 'statusflag',
								name: 'statusflag',
								labelSeparator:'',
								labelStyle: 'margin-left:0px;margin-top:0px;font-weight: bold; color:#F12536',
								fieldLabel: 'Cancel Invoice ?',
								style:"margin-bottom:4px",
								checked :false
						}]},{
				columnWidth: 0.5,
				layout: 'form',
				items:[{
							xtype: 'textfield',
							name: 'customerinvoice_grosstotal',
							id:'customerinvoice_grosstotal',
							labelStyle: 'margin-left:0px;margin-top:0px;font-weight: bold; color:#F12536',
							fieldLabel :'Gross Total ',
							readOnly:true,
							width:170
						}]}] },{
							xtype: 'textfield',
							name: 'customerinvoice_id',
							id:'customerinvoice_id',
							hidden:true
					 },{
							xtype: 'textfield',
							name: 'customer_id1',
							id:'customer_id1',
							hidden:true
					 },{
							xtype: 'textfield',
							name: 'customerinvoice_nettotal',
							id:'customerinvoice_nettotal',
							hidden:true
						},{
							xtype: 'textfield',
							name: 'customerinvoice_taxtotal',
							id:'customerinvoice_taxtotal',
							hidden:true
						}],
			buttonAlign: 'center',
		    buttons:[
			{
            	text: 'Blank Invoice',
				iconCls: 'icon-view',
				tabIndex:9,
				handler: function(){
					
					
					
						vendorgridForm.getForm().getEl().dom.target = '_blank';
						 if(Ext.getCmp('headerflag').getValue() == true)
						 
								vendorgridForm.getForm().getEl().dom.action = 'report-form-customer-invoice-result1.php';
						 else
							vendorgridForm.getForm().getEl().dom.action = 'report-form-customer-invoice-result.php';
							
						
						vendorgridForm.getForm().getEl().dom.submit(
						{
							waitMsg: 'Saving...',
							success: function (){},
							failure: function (){
								Ext.Msg.alert ('Error Message','Please fill up complete form.');
							}
						});	
						
				}
        	},
			{
            	text: 'View Invoice',
				iconCls: 'icon-view',
				tabIndex:9,
				handler: function(){
					
					if(Ext.getCmp('customerinvoice_id').getValue()!="")
					{
					
						vendorgridForm.getForm().getEl().dom.target = '_blank';
						 if(Ext.getCmp('headerflag').getValue() == true)
						 
								vendorgridForm.getForm().getEl().dom.action = 'report-form-customer-invoice-result1.php';
						 else
							vendorgridForm.getForm().getEl().dom.action = 'report-form-customer-invoice-result.php';
							
						
						vendorgridForm.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',
				id:'btnSave',
				name:'btnSave',
				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++;
						}
						vendorgridForm.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
										  });	
								store1.load();
								grid1.getSelectionModel().clearSelections();
								vendorgridForm.getForm().reset();
								InvoiceproductDataStore.removeAll(); 
								InvoiceTaxDataStore.removeAll(); 
								get_InvoiceNo();
								Ext.getCmp('searchtrigger').reset();
								Ext.getCmp('searchinvoice').reset();
								
							
												 							    							 
						},
						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 () {
					
						vendorgridForm.getForm().reset();
						grid1.getSelectionModel().clearSelections();
						
						invoicegrid.stopEditing();
						InvoiceproductDataStore.removeAll(); 
						Taxgrid.stopEditing();
 						InvoiceTaxDataStore.removeAll(); 
						get_InvoiceNo();
						 Ext.getDom('headertitle').innerHTML = "";
						 Ext.getCmp('btnSave').enable();
						 store1.load();
						Ext.getCmp('searchtrigger').reset();
						Ext.getCmp('searchinvoice').reset();

						
				}	
        	},
			{
            	text: 'Close',
				iconCls: 'icon-close',
				tabIndex:12,
				handler: function(){
					    myMask.hide();
						gridmask.hide();
						vendorWindow.close();
						
						
				}
        	}
		]
			     
        }]}
        ]
    });
	
 grid1.on('render', function() {
   grid1.tip = new Ext.ToolTip({
    view: grid1.getView(),
    target: grid1.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.";
     }
    }
   });
  });
  CustomerWindow.on('hide',function(){
		store.load();
		custname_store.load();
	});
ProductWindow.on('hide',function(){
		
		productstore.load();
	});  
/*  invoicegrid.on('validateedit',function validateedit(e) {
		if(e.field=="product_qty")
		{ invoicegrid.stopEditing();
			if(e.value > 0)
			{
				selqty=e.value;
				e.cancel=true;	
				
				Ext.MessageBox.confirm('Confirmation','Do u Want to Insert Serial Number For This Product?', showserialno);
			}
			
			
	    }
});*/

var CreditAccountfieldSet = {
		id:'formParamsTableau',
	    labelWidth:70,
        autoScroll:true,
        title: '',
	    items:[{        	
				items:[{
        		id:'formParamsTableau_CreditAmount',
				name:'creditamount',
        		layout: 'form'
        	}]
        }]				
  }
function account()
{	
   var Add_CreditAmount=Ext.getCmp("formParamsTableau_CreditAmount");
  
   for(i=1;i<=selqty;i++)
   {
   		var txtcreditAmount =new Ext.form.TextField({			          
						allowBlank:false,
						width:250,
						fieldLabel :'Serial No' + i,
						id:"srno"+i,
						name:"srno"+i,
						enableKeyEvents: true,
						autoCreate: {tag: 'input', type: 'text',  maxlength: '50'}
						
				});
		
				Add_CreditAmount.add(txtcreditAmount);
   }
				inquiryForm.doLayout();	
}

var inquiryForm = new Ext.FormPanel({
        frame: true,
		url:'save-support.php',
        bodyStyle: 'padding:5px',
		autoHeight: true,
		width:350,	
			defaults: {
            border: false
           },	
            items: [CreditAccountfieldSet]
    });	
	var winserial = new Ext.Window({
				title: 'Assign Serial Number',
				layout: 'fit',
				modal:true,
				closeAction:'hide',
				autoHeight: true,
				autoDestroy :true,
				items: inquiryForm
			});
	
 
function showserialno(btn){
	
	if(btn=='yes'){
		
	winserial.show();
	
	account();
	}
}
	
	
	get_InvoiceNo();
	
	function get_InvoiceNo(){
			
	Ext.Ajax.request({
		loadMask: true,
		sync : true,
		url: 'data/get_invoiceNo.php',
		
		success: function(resp){
			var value=Ext.decode(resp.responseText).count;
			
			if(value==','){
				
			 Ext.MessageBox.show({
					title: 'Error',
					msg: 'Ro.No Not Found.',
					buttons: Ext.MessageBox.OK,
					icon:Ext.MessageBox.ERROR
				});
			} 
			else{
				var arr_data = new Array();
				arr_data =  value.split(",");
				Ext.getCmp('customerinvoice_no').setValue(arr_data[0]);
				
			}					
		}				
	});	}	
	
	  
 	var vendorWindow = new Ext.Window({
        title: 'Customer Invoice Information<span id="headertitle" style="padding-left:200px;color:#940019"></span>',
		id:'vendorWindow',
		name:'vendorWindow',
		width:850,		
		height:560,	
        frame: true,
		border: false,
		modal:true,
		layout: 'fit',
		closeAction:'close',
		collapsible:true,
		items: vendorgridForm
		

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