var AcceptCCNumber = false;
var invoices_store;
var pricetypecombovalue = 0;

var refreshProfileHeaderBalance;

Ext.onReady(function(){


/*
 * Class for saving grid state. Modeled on LayoutStateManager
 */
//used to search by customer name
var customerDropDownForInvoice = new Ext.form.ComboBox({
     tpl: '<tpl for="."><div qtip="id: {id}<br/>e-mail: {email}<br/>status: {statusname}<br/>type: {clienttypename}" class="x-combo-list-item"><span style="text-transform:capitalize;">{firstname} {lastname}</span></div></tpl>',
     store: allclientsstore,
     mode: 'remote',
     lazyRender: true,
     editable:false,
     triggerAction: 'all',
     selectOnFocus:true,
     listWidth:180,
     width: 143,
     applyTo: 'remote-users-invoice-search',
     onSelect: function(record){
         submitSearch(record.data.id);
         customerDropDownForInvoice.collapse();
     }
});
customerDropDownForInvoice.setValue(lang('Select a customer')+' ...');

Ext.grid.GridStateManager = function(){
     // default empty state
     this.state = {
        hidden: { },
        locked: { },
        widths: { }
    };
};

Ext.grid.GridStateManager.prototype = {
    init : function(grid, provider){
        this.provider = provider;
        this.grid = grid;
        var state = columnsavedstate;

        if(state) {
            state.hidden = state.hidden || { };
            for (var colId in state.hidden) {
              var colIndex = this.grid.getColumnModel().getIndexById(colId);
              if (!isNaN(colIndex) && colIndex >= 0) {
                this.grid.getColumnModel().setHidden(colIndex, state.hidden[colId]);
              }
            }
            state.locked = state.locked || { };
            for (var colId in state.locked) {
              var colIndex = this.grid.getColumnModel().getIndexById(colId);
              if (!isNaN(colIndex) && colIndex >= 0) {
                this.grid.getColumnModel().setLocked(colIndex, state.locked[colId]);
              }
            }
            state.widths = state.widths || { };
            for (var colId in state.widths) {
              var colIndex = this.grid.getColumnModel().getIndexById(colId);
              if (!isNaN(colIndex) && colIndex >= 0) {
                this.grid.getColumnModel().setColumnWidth(colIndex, state.widths[colId]);
              }
            }
            if (state.sortInfo) {
              //this.grid.getDataSource().setDefaultSort(state.sortInfo.field, state.sortInfo.direction);
            }
            if (state.colIds) {
              for (var i = 0; i < state.colIds.length; i++) {
                var savedColId = state.colIds[i];
                var initialColIndex = this.grid.getColumnModel().getIndexById(savedColId);
                if (!isNaN(initialColIndex) && initialColIndex > 0 && initialColIndex != i) {
                  this.grid.getColumnModel().moveColumn(initialColIndex, i);
                }
              }
            }
            this.state = state;
        }
        grid.getColumnModel().on("hiddenchange", this.onHiddenChange, this);
        // for some reason the widthchange event on ColumnModel always gives width = undefined
        // so have to list to the event on the grid directly
        grid.on("columnresize", this.onColumnResize, this);
        grid.getColumnModel().on("columnlockchange", this.onLockChange, this);
        grid.getColumnModel().on("columnmoved", this.onColumnMove, this);
        //grid.getDataSource().on("datachanged", this.onSort, this);
    },

    getStateKey : function() {
      return this.grid.id + "-grid-state";
    },

    storeState : function(){

        // Upadat the local var
        columnsavedstate = this.state;

        // Post it
        Ext.Ajax.request({
           url: 'index.php?fuse=admin&action=updateGridSavedState',
           success: function(xhr) {
                    },
           failure: function() {
                NE_log(1,"Failed from saving gridstate");
           },
           params: {gridcustomfield: 'InvoiceTicketGridState',
                     gridsavedstate: Ext.encode(gridsavedstate),
                     columnsavedstate: Ext.util.JSON.encode(this.state)
                     },
           method:'post'
        });
    },

    onHiddenChange : function(cm, colIndex, hidden){
        var colId = cm.getColumnId(colIndex);
        this.state.hidden[colId] = hidden;
        this.storeState();
    },

    onColumnResize : function(colIndex, width){
        var colId = this.grid.getColumnModel().getColumnId(colIndex);
        this.state.widths[colId] = width;
        this.storeState();
    },

    onLockChange : function(cm, colIndex, lockState){
        var colId = cm.getColumnId(colIndex);
        this.state.locked[colId] = lockState;
        this.storeState();
    },

    onColumnMove : function(cm, oldIndex, newIndex){
        // we do this one by saving array of current order of column ids
        var colIds = [];
        for(var i = 0; i < cm.getColumnCount(); i++){
            colIds.push(cm.getColumnId(i));
        }
        this.state.colIds = colIds;
        this.storeState();
    },

    onSort : function(dataSource){
        if (dataSource.sortInfo) {
          this.state.sortInfo = {field: dataSource.sortInfo.field, direction: dataSource.sortInfo.direction}
          this.storeState();
        }
    }
};

/*
 * @enhancements
 * Add method to Grid to restore state.
 */
Ext.apply(Ext.grid.GridPanel.prototype, {
  restoreState: function (provider) {
    if (!provider) {
      provider = Ext.state.Manager;
    }
    var sm = new Ext.grid.GridStateManager();
    sm.init(this, provider);
  }
});

    var from;

    function PopulateInvoiceFilters(){
        Ext.Ajax.request({
           url: 'index.php?fuse=billing&action=GetInvoiceFilters',
           success: function(xhr) {
                //clear the items from our combobox
                invoicetypecombo.getStore().removeAll();

                //go through our options and add to the UI
                var data = Ext.util.JSON.decode(xhr.responseText);
                //data.options.forEach(updateButtonsWithContent);
                for ( var i in data.options )
                {
                    updateButtonsWithContent( data.options[i] );
                }
                invoicetypecombo.setValue(gridsavedstate.invoicefilter);
           },
           failure: function() { },
           params: {foo: 'bar'}
        });
    }
    PopulateInvoiceFilters();

    invoices_store = new Ext.data.JsonStore({
        id: "invoices_store",
        root: 'invoices',
        totalProperty: 'totalcount',
        idProperty: 'invoiceid',
        remoteSort: true,
        listeners: {
          beforeload: function(){
                document.getElementById('invoicelistdescription').innerHTML = lang("Searching")+"...";
          },
          load: function(){
              var extra = "";
              if( (invoices_store.baseParams['customerid'] != undefined) && (invoices_store.baseParams['customerid']!=0) ) {
                  extra = lang("for UserId") + " (" +invoices_store.baseParams['customerid']+ ")";
              }
              document.getElementById('invoicelistdescription').innerHTML = lang("Viewing") + " "+invoicetypecombo.getRawValue()+" "+extra;
              document.getElementById('invoice').innerHTML = '';
          }
        },
        fields: [
            'id',
            'invoiceid',
            'billdate',
            //'description',
            'billappliesto',
            //'billpmtref',
            //'billamount',
            'billbalancedue',
            'simplebalancedue',
            'linkid',
            'customername',
            'paymenttype',
            'overdue',
            'customerid',
            'billstatus',
            'statusenum',
            'balancedue'
        ],
        // load using script tags for cross domain, if the data in on the same domain as
        // this page, an HttpProxy would be better
        proxy: new Ext.data.HttpProxy({
            url: 'index.php?fuse=billing&action=GetInvoiceList'
        })
    });

    invoices_store.setBaseParam('moduleview', 'billing invoice list');
    invoices_store.setDefaultSort(gridsavedstate.sortinfo.field, gridsavedstate.sortinfo.dir);
    invoices_store.setBaseParam('limit', gridsavedstate.displaysize);

    var sm = new Ext.grid.CheckboxSelectionModel({
        listeners:{
             'rowdeselect': function(model, rowIndex, record){
                    toggleButtons();
              },
              'rowselect': function(model, rowIndex, record){
                    toggleButtons();
              }
        }
    });

    function hideAllButtons(){
        Ext.getCmp('paymentbuttons').setDisabled(true);
        Ext.getCmp('paymentbuttons').hide();
        Ext.getCmp('processinvoicebutton').setDisabled(true);
        Ext.getCmp('processinvoicebutton').hide();
        Ext.getCmp('addvariablepaymentbutton').setDisabled(true);
        Ext.getCmp('addvariablepaymentbutton').hide();
        Ext.getCmp('applyaccountcreditbutton').setDisabled(true);
        Ext.getCmp('applyaccountcreditbutton').hide();
        Ext.getCmp('markinvoicepaidbutton').setDisabled(true);
        Ext.getCmp('markinvoicepaidbutton').hide();
        Ext.getCmp('markinvoiceunpaidbutton').setDisabled(true);
        Ext.getCmp('markinvoiceunpaidbutton').hide();
        
        Ext.getCmp('sendbuttons').setDisabled(true);
        Ext.getCmp('sendbuttons').hide();
        Ext.getCmp('sendinvoicebutton').setDisabled(true);
        Ext.getCmp('sendinvoicebutton').hide();
        Ext.getCmp('sendoverduebutton').setDisabled(true);
        Ext.getCmp('sendoverduebutton').hide();
        Ext.getCmp('sendreceiptbutton').setDisabled(true);
        Ext.getCmp('sendreceiptbutton').hide();
        
        Ext.getCmp('voidbuttons').setDisabled(true);
        Ext.getCmp('voidbuttons').hide();
        Ext.getCmp('voidbutton').setDisabled(true);
        Ext.getCmp('voidbutton').hide();
        Ext.getCmp('refundbutton').setDisabled(true);
        Ext.getCmp('refundbutton').hide();
        Ext.getCmp('creditinvoicebutton').setDisabled(true);
        Ext.getCmp('creditinvoicebutton').hide();
        
        Ext.getCmp('recalculateinvoicebutton').setDisabled(true);
        Ext.getCmp('recalculateinvoicebutton').hide();
        
        Ext.getCmp('deleteinvoicebutton').setDisabled(true);
        Ext.getCmp('deleteinvoicebutton').hide();
    }

    function toggleButtons(count){

        hideAllButtons();

        //Ext.getCmp('markinvoicepaidbutton').show();

        if(count == undefined){
            count = sm.getCount();
        }

        if(count > 0){
            Ext.Ajax.request({
                url:        "index.php?fuse=billing&action=GetInvoiceButtons",
                params:     {
                    invoices: getInvoiceItems()
                },
                autoAbort:  true,
                success:    function(xhr) {
                    var data = Ext.util.JSON.decode(xhr.responseText);
                    
                    //if(data.invoices == getInvoiceItems()){
                        if(data.error){
                           //msg(lang("There was an error performing this action"));
                        }else if(data.message){
                            msg(data.message);
                        }else{
                            var canPay  = false;
                            var canSend = false;
                            var canVoid = false;
                            
                            //msg(lang("Invoice(s) have been updated"));
                            if(data.buttons.markpaid){
                                canPay = true;
                                Ext.getCmp('markinvoicepaidbutton').show();
                                Ext.getCmp('markinvoicepaidbutton').setDisabled(false);
                            }else{
                                Ext.getCmp('markinvoicepaidbutton').setDisabled(true);
                                Ext.getCmp('markinvoicepaidbutton').hide();
                            }
                            
                            if(data.buttons.markunpaid){
                                canPay = true;
                                Ext.getCmp('markinvoiceunpaidbutton').show();
                                Ext.getCmp('markinvoiceunpaidbutton').setDisabled(false);
                            }else{
                                Ext.getCmp('markinvoiceunpaidbutton').setDisabled(true);
                                Ext.getCmp('markinvoiceunpaidbutton').hide();
                            }
                            
                            if(data.buttons.varpayment){
                                canPay = true;
                                Ext.getCmp('addvariablepaymentbutton').show();
                                Ext.getCmp('addvariablepaymentbutton').setDisabled(false);
                            }else{
                                Ext.getCmp('addvariablepaymentbutton').setDisabled(true);
                                Ext.getCmp('addvariablepaymentbutton').hide();
                            }
                            
                            if(data.buttons.applycredit){
                                canPay = true;
                                Ext.getCmp('applyaccountcreditbutton').show();
                                Ext.getCmp('applyaccountcreditbutton').setDisabled(false);
                            }else{
                                Ext.getCmp('applyaccountcreditbutton').setDisabled(true);
                                Ext.getCmp('applyaccountcreditbutton').hide();
                            }
                            
                            if(data.buttons.deleteinvoices){
                                Ext.getCmp('deleteinvoicebutton').show();
                                Ext.getCmp('deleteinvoicebutton').setDisabled(false);
                            }else{
                                Ext.getCmp('deleteinvoicebutton').setDisabled(true);
                                Ext.getCmp('deleteinvoicebutton').hide();
                            }
                            
                            if(data.buttons.send){
                                canSend = true;
                                Ext.getCmp('sendinvoicebutton').show();
                                Ext.getCmp('sendinvoicebutton').setDisabled(false);
                            }else{
                                Ext.getCmp('sendinvoicebutton').setDisabled(true);
                                Ext.getCmp('sendinvoicebutton').hide();
                            }
                            
                            if(data.buttons.sendreceipt){
                                canSend = true;
                                Ext.getCmp('sendreceiptbutton').show();
                                Ext.getCmp('sendreceiptbutton').setDisabled(false);
                            }else{
                                Ext.getCmp('sendreceiptbutton').setDisabled(true);
                                Ext.getCmp('sendreceiptbutton').hide();
                            }
                            
                            if(data.buttons.sendoverdue){
                                canSend = true;
                                Ext.getCmp('sendoverduebutton').show();
                                Ext.getCmp('sendoverduebutton').setDisabled(false);
                            }else{
                                Ext.getCmp('sendoverduebutton').setDisabled(true);
                                Ext.getCmp('sendoverduebutton').hide();
                            }
                            
                            if(data.buttons.voidinvoices){
                                canVoid = true;
                                Ext.getCmp('voidbutton').show();
                                Ext.getCmp('voidbutton').setDisabled(false);
                            }else{
                                Ext.getCmp('voidbutton').setDisabled(true);
                                Ext.getCmp('voidbutton').hide();
                            }
                            
                            if(data.buttons.refund){
                                canVoid = true;
                                Ext.getCmp('refundbutton').show();
                                Ext.getCmp('refundbutton').setDisabled(false);
                            }else{
                                Ext.getCmp('refundbutton').setDisabled(true);
                                Ext.getCmp('refundbutton').hide();
                            }
                            
                            if(data.buttons.credit){
                                canVoid = true;
                                Ext.getCmp('creditinvoicebutton').show();
                                Ext.getCmp('creditinvoicebutton').setDisabled(false);
                            }else{
                                Ext.getCmp('creditinvoicebutton').setDisabled(true);
                                Ext.getCmp('creditinvoicebutton').hide();
                            }
                            
                            if(data.buttons.process){
                                canPay = true;
                                AcceptCCNumber = data.buttons.acceptccnumber;
                                Ext.getCmp('processinvoicebutton').show();
                                Ext.getCmp('processinvoicebutton').setDisabled(false);
                            }else{
                                AcceptCCNumber = false;
                                Ext.getCmp('processinvoicebutton').setDisabled(true);
                                Ext.getCmp('processinvoicebutton').hide();
                            }
                            
                            if(data.buttons.recalculate){
                                canPay = true;
                                Ext.getCmp('recalculateinvoicebutton').show();
                                Ext.getCmp('recalculateinvoicebutton').setDisabled(false);
                            }else{
                                Ext.getCmp('recalculateinvoicebutton').setDisabled(true);
                                Ext.getCmp('recalculateinvoicebutton').hide();
                            }
                            
                            
                            if(canPay == true){
                                Ext.getCmp('paymentbuttons').show();
                                Ext.getCmp('paymentbuttons').setDisabled(false);
                            }else{
                                Ext.getCmp('paymentbuttons').setDisabled(true);
                                Ext.getCmp('paymentbuttons').hide();
                            }
                            
                            if(canSend == true){
                                Ext.getCmp('sendbuttons').show();
                                Ext.getCmp('sendbuttons').setDisabled(false);
                            }else{
                                Ext.getCmp('sendbuttons').setDisabled(true);
                                Ext.getCmp('sendbuttons').hide();
                            }
                            
                            if(canVoid == true){
                                Ext.getCmp('voidbuttons').show();
                                Ext.getCmp('voidbuttons').setDisabled(false);
                            }else{
                                Ext.getCmp('voidbuttons').setDisabled(true);
                                Ext.getCmp('voidbuttons').hide();
                            }
                        }
                    //}
                },
                failure:    function(){
                }
            });
        }
    }

   function getInvoiceItems()
   {
        //var arrayofids = new Array();
        var invoiceItems = "";
        rows = sm.getSelections();
        //var i = 0;
        for(x=0;x<rows.length;x++){
            var commavar = ",";
            if(x !=0){
               invoiceItems += commavar;
            }
            invoiceItems += rows[x].data.invoiceid;
          //  i++;
        }
        return invoiceItems;
    }

       /*
		var arrayofids = new Array();
        rows = sm.getSelections();
	    for(x=0;x<rows.length;x++){
	       arrayofids[x] = rows[x].data.invoiceid;
	    }
	    return arrayofids;*/

    var gridbb = new Ext.PagingToolbar({
        store: invoices_store,
        id: "invoicesgridpagingbar",
        pageSize: gridsavedstate.displaysize,
        listeners:{
            'change': function(bb,data){

                    if(data.total == 0) {var addBy = 0;} else {var addBy = 1;}
                    from = (data.activePage * bb.pageSize) - bb.pageSize + addBy;
                    to = from+ bb.pageSize - 1;
                    if(to>data.total) to = data.total;

				document.getElementById('invoicesgridpagingbar').style.display = ( data.pages > 1 ) ? '' : 'none';
				document.getElementById('invoicelistlabel').innerHTML = String.format('Displaying invoices {0} - {1}' + ' of ' + '{2}',from,to,data.total);
            }
        }
    });
    
    function renderNumber(value,p,record){
         url = "<span class='invoicelink'><a href='javascript:LoadInvoice("+record.data.invoiceid+",\"invoice\");'>"+ "Invoice #"+record.data.linkid +"</a></span>";
         pdf = "<span class='invoicepdflink'><a href='index.php?sessionHash="+gHash+"&fuse=billing&action=GeneratePDFInvoice&invoiceid=" + record.data.invoiceid + "' target='_blank'><img class='pdfimage' src='../templates/admin/images/document-pdf-text.png' border='0'  qtip='"+ lang('View PDF Invoice') +"' /></a></span>";
         number = url + pdf;
         return number ;
    }

    function renderStatus(value,p,record){
        //get priority color
        if(record.data.statusenum == -2){
            priorityclass="invoiceoverdue";
            p.css = priorityclass;
        }else if (record.data.statusenum == 0){
            //priorityclass="invoicenotpaid";
            //p.css = priorityclass;
        }else if(record.data.statusenum == 1){
            priorityclass="invoicepaid";
            p.css = priorityclass;
        }else if (record.data.statusenum == -1){
            priorityclass="invoicevoidrefund";
            p.css = priorityclass;
        }
        return String.format("{0}",record.data.billstatus);
    }

    function renderAppliesTo(value,p,record){
        if(record.data.billappliesto==""){
            appliesto = lang("None");
        }else{
            appliesto = record.data.billappliesto;
        }
        return appliesto;
    }

    function renderName(value,p,record){
         url = "<a href='index.php?fuse=clients&view=Admin_Profile_Contact&frmClientID="+record.data.customerid+"'>";
         return url + record.data.customername +"</a>";
    }

    function renderBalanceDue(value,p,record){
        return record.data.billbalancedue + "&nbsp;&nbsp;&nbsp;";
    }

    var expander = new Ext.ux.grid.RowExpander({
        enableCaching: false,
        listeners:{
           'expand': function(re,response,body,index){
               Ext.Ajax.request({
                    url: 'index.php?fuse=billing&action=Admin_GetInvoiceTransactions',
                    success: function(response){
                            var data = Ext.util.JSON.decode(response.responseText);
                            data.invoicetransactions = data.invoicetransactions;
                            body.innerHTML = data.invoicetransactions;
                    },
                    params: {invoiceid: response.data.invoiceid}
		});
            }
        }
    });

    var grid = new Ext.grid.GridPanel({
        id:'invoices-grid',
        el:'invoices-grid',
        autoHeight:true,
        store: invoices_store,
        trackMouseOver:true,
        disableSelection:true,
        loadMask: true,

        // grid columns
        columns:[
            expander,
            sm,
            {
            id: 'billdate',
            header: lang("Due Date"),
            dataIndex : "billdate",
            width: 70,
            sortable: true,
            align:"left"
        },
        {
            id: 'invoiceid',
            dataIndex: 'id',
            header: lang("Invoice"),
            width: 90,
            renderer: renderNumber,
            sortable: true,
            align:"center"
        },{
            id: 'customername',
            header: lang("Customer Name"),
            width: 300,
            renderer: renderName
        },{
            id: 'billappliesto',
            header: lang("Applies To"),
            renderer:renderAppliesTo,
            align:"center",
            hidden:true,
            width: 90
        },{
            id: 'paymentprocessor',
            header: lang("Gateway"),
            dataIndex : "paymenttype",
            width: 100,
            sortable: true,
            align:'center'
        },{
            id: 'billbalancedue', 
            header: lang("Amount Due"),
            width: 80,
            dataIndex: 'balancedue',
            renderer: renderBalanceDue,
            sortable: true,
            align:"right"
        },{
            id: 'status',
            header: lang("Status"),
            renderer: renderStatus,
            width: 50,
            align:"center"
        }],
        sm: sm,
        plugins: expander,
        stripeRows: true,
        // customize view config
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no invoices available to view at this time"),
            scrollOffset:1
        },
        // paging bar on the bottom
        bbar: gridbb,
        buttonAlign:'left',
        buttons:[
            {
                id:         'paymentbuttons',
                autoHeight: true, 
                arrowAlign: 'right',
                //xtype:      'splitbutton',
                text:       lang('Payment'),
                hidden:     true,
                menu:       new Ext.menu.Menu({
                    enableScrolling:  false,
                    shadow:false,
                    items:            [
                        {
                            id:       'processinvoicebutton',
                            text:     lang('Process'),
                            hidden:   true,
                            disabled: true,
                            onClick:  function(record){
                                btnButtonActionHandler(this);
                            }
                        },
                        {
                            id:       'addvariablepaymentbutton',
                            text:     lang('Add Payment'),
                            hidden:   true,
                            disabled: true,
                            onClick:  function(record){
                                btnButtonActionHandler(this);
                            }
                        },
                        {
                            id:       'applyaccountcreditbutton',
                            text:     lang('Apply Credit'),
                            hidden:   true,
                            disabled: true,
                            onClick:  function(record){
                                btnButtonActionHandler(this);
                            }
                        },
                        {
                            id:       'markinvoicepaidbutton',
                            text:     lang('Mark Paid'),
                            hidden:   true,
                            disabled: true,
                            onClick:  function(record){
                                btnButtonActionHandler(this);
                            }
                        },
                        {
                            id:       'markinvoiceunpaidbutton',
                            text:     lang('Mark Un-Paid'),
                            hidden:   true,
                            disabled: true,
                            onClick:  function(record){
                                btnButtonActionHandler(this);
                            }
                        }
                    ]
                })
            },
            {
                id:         'sendbuttons',
                autoHeight: true, 
                arrowAlign: 'right',
                //xtype:      'splitbutton',
                text:       lang('Send'),
                hidden:     true,
                menu:       new Ext.menu.Menu({
                    enableScrolling:  false,
                    shadow:false,
                    items:            [
                        {
                            id:       'sendinvoicebutton',
                            text:     lang('Send Invoice'),
                            hidden:   true,
                            disabled: true,
                            onClick:  function(record){
                                btnButtonActionHandler(this);
                            }
                        },
                        {
                            id:       'sendoverduebutton',
                            text:     lang('Send Overdue'),
                            hidden:   true,
                            disabled: true,
                            onClick:  function(record){
                                btnButtonActionHandler(this);
                            }
                        },
                        {
                            id:       'sendreceiptbutton',
                            text:     lang('Send Receipt'),
                            hidden:   true,
                            disabled: true,
                            onClick:  function(record){
                                btnButtonActionHandler(this);
                            }
                        }
                    ]
                })
            },
            {
                id:         'voidbuttons',
                autoHeight: true, 
                arrowAlign: 'right',
                //xtype:      'splitbutton',
                text:       lang('Void'),
                hidden:     true,
                menu:       new Ext.menu.Menu({
                    enableScrolling:  false,
                    shadow:false,
                    items:            [
                        {
                            id:       'voidbutton',
                            text:     lang('Void'),
                            hidden:   true,
                            disabled: true,
                            onClick:  function(record){
                                btnButtonActionHandler(this);
                            }
                        },
                        {
                            id:       'refundbutton',
                            text:     lang('Refund'),
                            hidden:   true,
                            disabled: true,
                            onClick:  function(record){
                                btnButtonActionHandler(this);
                            }
                        },
                        {
                            id:       'creditinvoicebutton',
                            text:     lang('Credit'),
                            hidden:   true,
                            disabled: true,
                            onClick:  function(record){
                                btnButtonActionHandler(this);
                            }
                        }
                    ]
                })
            },
            {
                id:       'recalculateinvoicebutton',
                text:     lang('Recalculate'),
                hidden:   true,
                disabled: true,
                onClick:  function(record){
                    btnButtonActionHandler(this);
                }
            },
            {
                id:       'deleteinvoicebutton',
                text:     lang('Delete'),
                hidden:   true,
                disabled: true,
                onClick:  function(record){
                    btnButtonActionHandler(this);
                }
            }
        ],
        listeners:  {
            'columnmove': function(oldIndex,newIndex){
                //alert(oldIndex);
                //alert(newIndex);
            },
            'sortchange' : function (grid,sortInfo){
                gridsavedstate.sortinfo.field = sortInfo.field;
                gridsavedstate.sortinfo.dir = sortInfo.direction;
                updateGridSavedState("InvoiceTicketGridState");
            }
        }
    });

grid.restoreState();


    function updateGridSavedState(customfield){
        Ext.Ajax.request({
           url: 'index.php?fuse=admin&action=updateGridSavedState',
           success: function(xhr) {
                    //msg('Settings Update Successfully');
                    },
           failure: function() {
                NE_log(1,"Failed from saving gridstate");
           },
           params: {gridcustomfield: customfield,
                     gridsavedstate: Ext.encode(gridsavedstate),
                     columnsavedstate: Ext.util.JSON.encode(columnsavedstate)
                     },
           method:'post'
        });
    }

    function processInvoices(btn, text){
        if(btn=="ok"){
            var confirmmsg = lang("Are you sure you want to process the selected account(s) with the CC number(s) on file?");
            var processItems = confirm(confirmmsg);
            
            if(processItems == false){
                grid.enable();
                return false;
            }
            
            var requesturl = "index.php?fuse=billing&action=Admin_ActOnInvoices";
            
            Ext.Ajax.request({
                url:      requesturl,
                params:   {
                    items:          getInvoiceItems(),
                    itemstype:      'invoices',
                    actionbutton:   "processinvoicebutton",
                    acceptccnumber: AcceptCCNumber,
                    passphrase:     text
                },
                success:  function(xhr){
                    //refreshgrid
                    grid.enable();
                    invoices_store.load({params:{start:0}});

                    var data = Ext.util.JSON.decode(xhr.responseText);
                    
                    if(data.error){
                        //we do not need to repopulate the filters if there was a validation error
                        msg(lang("There was an error performing this action"));
                    }else if(data.message){
                        msg(data.message);
                    }else{
                        msg(lang("Invoice(s) have been updated"));
                    }
                },
                failure:  function(){
                    grid.enable();
                }
            });
        }else{
            grid.enable();
        }
    }
    
    var btnButtonActionHandler = function(button){
        grid.disable();
        Ext.getCmp('paymentbuttons').menu.hide();
        Ext.getCmp('sendbuttons').menu.hide();
        Ext.getCmp('voidbuttons').menu.hide();
        requesturl = "index.php?fuse=billing&action=Admin_ActOnInvoices";
        var sendReceipt = "";
        if(button.id == "markinvoicepaidbutton"){
            var confirmmsg = lang("Do you want to send receipt(Ok=YES , Cancel=No) ?");
            sendReceipt = confirm(confirmmsg);
        }else if(button.id == "deleteinvoicebutton"){
            var confirmmsg = lang("Click OK if you are sure you want to delete the selected invoice(s).");
            var deleteItems = confirm(confirmmsg);
            if(deleteItems == false){
                grid.enable();
                return false;
            }
        }else if(button.id == "addvariablepaymentbutton"){
            if(sm.getCount() == 1){
                //Ext.getCmp('paymentbuttons').menu.hide();
                
                // Load a single JavaScript file and execute a callback when it finishes loading.
                ce.lazyLoad(
                    '../templates/admin/views/billing/AddVariablePayment.js',
                    function(){
                        var selectedRecord = sm.getSelected();
                        addvarpayment.AddVariablePayment(selectedRecord);
                    }
                );
                return false;
            }else{
                grid.enable();
                return false;
            }
        }else if(button.id == "processinvoicebutton"){
            if(AcceptCCNumber){
                if(/*@cc_on!@*/true){
                    Ext.MessageBox.getDialog().body.child('input').dom.type='password';
                }
                Ext.MessageBox.prompt('Validate Credit Card', 'Enter your passphrase:', processInvoices);
                return false;
            }else{
                var confirmmsg = lang("Are you sure you want to process the selected account(s)?");
                var processItems = confirm(confirmmsg);
                if(processItems == false){
                    grid.enable();
                    return false;
                }
            }
        }
        
        Ext.Ajax.request({
            url:      requesturl,
            params:   {
                items:          getInvoiceItems(),
                itemstype:      'invoices',
                actionbutton:   button.id,
                sendreceipt:    sendReceipt,
                acceptccnumber: AcceptCCNumber
            },
            success:  function(xhr){
                //refreshgrid
                grid.enable();
                invoices_store.load({params:{start:0}});
                
                var data = Ext.util.JSON.decode(xhr.responseText);
                
                if(data.error){
                    //we do not need to repopulate the filters if there was a validation error
                    if(data.message){
                        msg(lang("There was an error performing this action") + "<br>" + data.message);
                    }else{
                        msg(lang("There was an error performing this action"));
                    }
                }else if(data.message){
                    msg(data.message);
                }else{
                    msg(lang("Invoice(s) have been updated"));
                }
            },
            failure:  function(){
                grid.enable();
           }
        });
    }
    
    grid.render();
    
    

    // create the combo instance
    var combo = new Ext.form.ComboBox({
        triggerAction: 'all',
        lazyRender:true,
        editable:false,
        value: gridsavedstate.displaysize,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 0,
            fields: [
                'myId',
                'displayText'
            ],
            data: [[10, '10'], [25, '25'], [50, '50'], [150,'150'],[300,'300']]
        }),
        valueField: 'myId',
        width: 50,
        displayField: 'displayText',
        applyTo: 'numlistfilter',
        // all of your config options
        listeners:{
             'select': function(cb,record){
                invoices_store.setBaseParam('limit', record.data.myId);
                gridbb.pageSize = record.data.myId;
                invoices_store.load({params:{start:0}});
                gridsavedstate.displaysize = record.data.myId;
                updateGridSavedState("InvoiceTicketGridState");
             }
        }
    });
    combo.wrap.addClass("x-form-field-float-left");

    invoices_store.on('load',function(){
        toggleButtons(0);
        
        var data = invoices_store.reader.jsonData;

        if (trim(data.outstandingamount) == "") {
            document.getElementById('invoicesdetails-totals').style.display = "none";
        }else{
            additionalinfo = lang("Total")+": " + data.outstandingamount;
            document.getElementById('invoicesdetails-totals').innerHTML = additionalinfo;
            document.getElementById('invoicesdetails-totals').style.display = "";
        }
    });
    
    var storeItem = Ext.data.Record.create([{name:'myId',type:'string'},{name:'displayText',type:'string'}]);
    var invoicetypecombo = new Ext.form.ComboBox({
        id:'invoicetypecombo',
        triggerAction: 'all',
        lazyRender:true,
        editable:false,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            idIndex: 0,
            fields: [
                'myId',
                'displayText',
                'type',
                'private'
            ]
        }),
        valueField: 'myId',
        width: 220,
        displayField: 'displayText',
        applyTo: 'invoicetype',
        // all of your config options
        listeners:{
             'select': function(cb,record){
                FilterGrid(record.data.myId);
                gridsavedstate.invoicefilter = record.data.myId;
                updateGridSavedState("InvoiceTicketGridState");
             }
        }
    });
    invoicetypecombo.wrap.addClass("x-form-field-float-left");
    
    if(document.getElementById('pricetype') != null){
        var pricetypecombo = new Ext.form.ComboBox({
            triggerAction: 'all',
            lazyRender:true,
            editable:false,
            value: 0,
            mode: 'local',
            store: new Ext.data.ArrayStore({
                idIndex: 0,
                fields: [
                    'myId',
                    'displayText'
                ],
                data: [[0, lang('Real Price')], [1, lang('Customer\'s Price Estimation')]]
            }),
            valueField: 'myId',
            width: 220,
            displayField: 'displayText',
            applyTo: 'pricetype',
            // all of your config options
            listeners:{
                 'select': function(cb,record){
                    SelectPrice(record.data.myId);
                 }
            }
        });
        pricetypecombo.wrap.addClass("x-form-field-float-left")
    }

    function updateButtonsWithContent(data){
        if(data.type == "filter"){
            if(data.private == undefined){
                data.private = 0;
            }
            var comboitem = new storeItem({myId:data.id,displayText:data.name,type:data.type, private:data.private});
            invoicetypecombo.getStore().insert(
                invoicetypecombo.getStore().getCount(),
                comboitem
            );
        }
    }

    function FilterGrid(filter){
        if(filter!=null){
            invoices_store.setBaseParam('invoicefilter', filter);
        }
        invoices_store.load({params:{start:0}});
    }
    
    // trigger the data store load
    FilterGrid(gridsavedstate.invoicefilter);
    //invoices_store.load({params:{start:0}});
    
    function SelectPrice(filter){
        if(filter!=null){
            pricetypecombovalue = filter;
            invoices_store.setBaseParam('pricefilter', filter);
            if(typeof(invoicestore) != 'undefined'){
                invoicestore.setBaseParam('pricefilter', filter);
                invoicestore.load();
            }
        }

        if(from != undefined && from != null){
            invoices_store.load({params:{start:from - 1}});
        }else{
            invoices_store.load({params:{start:0}});
        }
    }

});

function LoadInvoice(invoiceid,id){
    Ext.get(id).load({
        url: 'index.php?fuse=billing&view=Admin_Invoice',
        scripts: true,
        showLoadIndicator: false,
        params: "invoiceid="+invoiceid+"&pricefilter"+pricetypecombovalue,
        text: ""
    });
}
/* TODO 4.6 start migrating to richgrid
$(document).ready(function() { 
	RichHTML.debugLvl = 3;
	richgrid = new RichHTML.grid({
		el:'invoicelist-grid',
        width: "100%",
        url: 'index.php?fuse=billing&action=GetInvoiceList',
		baseParams: {
			sort: 'id',
			dir : 'asc', // or 'desc'
			limit: 10,
			invoicefilter:0,
			moduleview: "billing invoice list"
        },
		root: 'invoices',
		totalProperty : 'totalcount',	
		columns: [{
				text: "",
				xtype: "expander",
				escapeHTML: true,
				renderer:renderExpander,
				renderOnExpand: true				
			},{
                text:     	"",
                dataIndex:  "id",            
                xtype:      "checkbox"            
            },{
                text:     	"Invoice #",
                dataIndex:  "id",
                align:      "center",                
                width:      85,
                sortable: true,
                renderer: function(text,row, el) {
                	return "#"+text;
                }
            },{
                text:     	"Customer Name",
                dataIndex:  "customername",
                align: 		"left"           
            },
            {
            	text:   "Gateway",
            	width:	   85,
            	dataIndex: "paymenttype",
            	sortable: true,
            	align: "center"
            },{
	            text: lang("Amount Due"),
	            width: 85,
	            dataIndex: 'billbalancedue',
	            align:"right"
            },
            {
            	text:	"Status",
            	width: 70,
            	dataIndex: "billstatus",
            	align: "center",
            	escapeHTML: false,
				renderer: renderStatus
            }
        ], 	
    });
    richgrid.render();   
    
    function renderExpander(value,record,el){
    	$.ajax({
		  url: 'index.php?fuse=billing&action=Admin_GetInvoiceTransactions',
		  dataType: 'json',
		  async: false,
		  data: {invoiceid:record.invoiceid},
		  success: function(data) {
			 html = data.invoicetransactions;
		  }
		});			
		return html;			  
    }
    
    function renderStatus(value,record, el){
        if(record.statusenum == -2){
            el.addClass = "invoiceoverdue";
        }else if (record.statusenum == 0){
        }else if(record.statusenum == 1){
            el.addClass = "invoicepaid";
        }else if (record.statusenum == -1){
            el.addClass = "invoicevoidrefund";
        }
        return String.format("{0}",value);
    }
    

	//GLOBAL BINDS FOR OUR INSTALLATION
	$(richgrid).bind({
		"load" : function(event,data) {
		    var paging = lang("Displaying invoices")+" "+(data.paging.start + 1)+" - "+(data.paging.start + data.paging.items)+" of "+data.paging.totalItems;		    
			$('#invoicelist-grid-metadata').html(paging);
	    },
	    "rowselect": function(event,data) {
			console.debug('selected id:'+data.rowid);
	    },
	    "drop": function (event, data) {
	    	console.debug('bound drop function');
	    }
	    
	});
    
    $('#invoicelist-grid-filter').change(function(){
    	richgrid.reload({params:{"start":0,"limit":$(this).val()}});
    });
    $('#invoicelist-grid-filterbystatus').change(function(){
    	richgrid.reload({params:{"start":0,"invoicefilter":$(this).val()}});
    });   
});
*/
