/*
 * Ext JS Library 3.0 RC1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 *
 * http://extjs.com/license
 */

var AcceptCCNumber = false;
var EditingPaymentReference = '';
var ShowingInvoiceDetails = '';
var PaymentReferenceInvoiceId = 0;

var invoices_store;
var pricetypecombovalue = 0;

var refreshProfileHeaderBalance;

Ext.onReady(function(){
    //Ext.Ajax.timeout = 120000; //2 minutes
    
    var from;

    invoices_store = new Ext.data.JsonStore({
        id: "gridstore",
        root: 'invoices',
        totalProperty: 'totalcount',
        idProperty: 'invoiceid',
        remoteSort: true,
        fields: [
            'invoiceid',
            'billdate',
            'description',
            'billappliesto',
            'billpmtref',
            'billrawpmtref',
            'billamount',
            'billbalancedue',
            'simplebalancedue',
            'billstatus',
            'statusenum'
        ],
        // 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', 'clients invoices');
    invoices_store.setDefaultSort('id', 'desc');

    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"));
                            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{
                            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 gridbb = new Ext.PagingToolbar({
        id:'invoicegridpagingbar',
        store: invoices_store,
        emptyMsg : "",
        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('invoicegridpagingbar').style.display = ( data.pages > 1 ) ? '' : 'none';
				document.getElementById('invoicelistlabel').innerHTML = String.format(lang('Displaying invoices') +' {0} - {1}' + ' of ' + '{2}',from,to,data.total);
            }
        }
    })

    function renderTotal(value,p,record){
        //make description part of the popup
        total = record.data.billamount + " / " + record.data.billbalancedue;
        return total+ "&nbsp;&nbsp;&nbsp;";
    }

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

    function renderDescription(value,p,record){
        var invoice = "<span class='invoicelink'><a href='javascript:LoadInvoice("+record.data.invoiceid+",\"invoice\");' qtip='"+ lang('View Invoice Summary') +"'>" + record.data.description + "</a></span>"
        //invoice = "<span class='invoicelink'><a href='index.php?fuse=billing&view=Admin_Invoice&invoiceid=" + record.data.invoiceid + "' qtip='"+ lang('View Invoice Summary') +"'>" + record.data.description + "</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>";
        description = invoice + pdf;
        return description;
    }

    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);
    }

    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);
                            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:   false,
        disableSelection: true,
        loadMask:         true,
        columns:          [
            expander,
            sm,
            {
                id:         'billdate',
                header:     lang("Due Date"),
                dataIndex:  "billdate",
                width:      70,
                sortable:   true,
                align:      "left"
            },
            {
                id:         'description',
                header:     lang("Invoice"),
                dataIndex:  "description",
                renderer:   renderDescription,
                width:      300
            },
            {
                id:         'billappliesto',
                header:     lang("Applies To"),
                dataIndex:  "billappliesto",
                renderer:   renderAppliesTo,
                align:      "center",
                hidden:     true,
                width:      90
            },
            {
                id:         'billpmtref',
                header:     lang("Pmt Reference"),
                dataIndex:  "billpmtref",
                align:      "center",
                width:      100
            },
            {
                id:         'billamount',
                header:     lang("Total") + " / " + lang("Amount Due"),
                width:      160,
                renderer:   renderTotal,
                align:      "right"
            },
            {
                id:         'billstatus',
                header:     lang("Status"),
                width:      50,
                renderer:   renderStatus,
                align:      "center"
            }
        ],
        sm:               sm,
        stripeRows:       true,
        plugins:          expander,
        viewConfig:       {
            forceFit:       true,
            enableRowBody:  true,
            emptyText:      lang("There are no invoices available to view at this time"),
            scrollOffset:   1
        },
        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);
                }
            }
        ]
    });

    function updatePaymentReference(btn,text){
        if(btn=="ok"){
            var checknum = text;
            if (checknum.length > 50){
                checknum
                Ext.Msg.alert('Payment Reference Too Long', 'Payment Reference must have at most 50 characters length, and this one has '+checknum.length+' characters length:<br>'+checknum);
                PaymentReferenceInvoiceId = 0;
            }

            if(PaymentReferenceInvoiceId == 0){
                grid.enable();
                return false;
            }

            var requesturl = "index.php?fuse=billing&action=Admin_ActOnInvoices";
            Ext.Ajax.request({
                url: requesturl,
                success: function(xhr) {
                    //refreshgrid
                    PaymentReferenceInvoiceId = 0;
                    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(xhr) {
                    PaymentReferenceInvoiceId = 0;
                    
                    //alert(dump(xhr));
                    refreshProfileHeaderBalance();
                    
                    grid.enable();
                    invoices_store.load({params:{start:0}});
                    
                    var timeoutText = '';
                    if(xhr.isTimeout){
                        timeoutText = '<br>timeout';
                    }
                },
                params: {items: Ext.util.JSON.encode(PaymentReferenceInvoiceId),
                          itemstype: 'invoices',
                          actionbutton: "addchecktoinvoicebutton",
                          checknum: checknum
                }
            });
        }else{
            grid.enable();
        }
    }

    EditingPaymentReference = function(invoiceId){
        grid.disable();
        PaymentReferenceInvoiceId = invoiceId;
        
        var elementIndex = invoices_store.find('invoiceid', invoiceId);
        var billrawpmtref = '';
        if(elementIndex > -1){
            var elementObject = invoices_store.getAt(elementIndex);
            billrawpmtref =  elementObject.data['billrawpmtref'];
        }
        Ext.MessageBox.prompt('Payment Reference', 'Enter your payment reference:', updatePaymentReference, this, false, billrawpmtref);
    }

    function processInvoices(btn, text){
        //The line inside does not work in Internet Explorer
        if(/*@cc_on!@*/true){
            Ext.MessageBox.getDialog().body.child('input').dom.type='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){
                    refreshProfileHeaderBalance();
                    
                    //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(xhr){
                    //alert(dump(xhr));
                    refreshProfileHeaderBalance();
                    
                    grid.enable();
                    invoices_store.load({params:{start:0}});
                    
                    var timeoutText = '';
                    if(xhr.isTimeout){
                        timeoutText = '<br>timeout';
                    }
                }
            });
        }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){
                //The line inside does not work in Internet Explorer
                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){
                refreshProfileHeaderBalance();
                
                //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(xhr){
                //alert(dump(xhr));
                refreshProfileHeaderBalance();
                
                grid.enable();
                invoices_store.load({params:{start:0}});
                
                var timeoutText = '';
                if(xhr.isTimeout){
                    timeoutText = '<br>timeout';
                }
           }
        });
    }

    refreshProfileHeaderBalance = function(){
        Ext.Ajax.request({
            url:        "index.php?fuse=billing&action=GetProfileHeaderBalance",
            params:     {
            },
            autoAbort:  true,
            success:    function(xhr) {
                var data = Ext.util.JSON.decode(xhr.responseText);
                
                document.getElementById('profile-header-credit-value').innerHTML = data.balance.credit;
                document.getElementById('profile-header-totalpaid-value').innerHTML = data.balance.totalpaid;
                document.getElementById('profile-header-totalunpaid-value').innerHTML = data.balance.totalunpaid;
            },
            failure:    function(){
            }
        });
    }

    grid.render();

    // trigger the data store load
    gridbb.pageSize = 10;
    invoices_store.setBaseParam('limit', 10);
    invoices_store.load({params:{start:0}});

    // create the combo instance
    var combo = new Ext.form.ComboBox({
        tpl: '<tpl for="."><div qtip="Display {displayText} items" class="x-combo-list-item">{displayText}</div></tpl>',
        triggerAction: 'all',
        lazyRender:true,
        editable:false,
        value:'10',
        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}});
             }
        }
    });

    invoices_store.on('load',function(){
        toggleButtons(0);
        ////TODO I need to update param to send to invoice load
        //if(document.getElementById('divinvoicedetails').style.display != 'none'){
            //gridstore2.load();
        //}
    });

    var storeItem = Ext.data.Record.create([{name:'myId',type:'string'},{name:'displayText',type:'string'}]);
    var invoicetypecombo = new Ext.form.ComboBox({
        triggerAction: 'all',
        lazyRender:true,
        editable:false,
        value:lang('All Types'),
        mode: 'local',
        store: new Ext.data.ArrayStore({
            idIndex: 0,
            fields: [
                'myId',
                'displayText',
                'type',
                'private'
            ]
        }),
        valueField: 'myId',
        width: 120,
        itemCls:'someclass',
        displayField: 'displayText',
        applyTo: 'invoicetype',
        // all of your config options
        listeners:{
             'select': function(cb,record){
                FilterGrid(record.data.myId);
             }
        }
    });
    invoicetypecombo.wrap.addClass("x-form-field-float-left");

    if(document.getElementById('pricetype') != undefined){
        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");
    }

    var invoicefiltercombo = 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('Invoices')], [1, lang('Un-invoiced Work')]]
        }),
        valueField: 'myId',
        width: 220,
        displayField: 'displayText',
        applyTo: 'invoicefilter',
        // all of your config options
        listeners:{
             'select': function(cb,record){
                window.location = 'index.php?fuse=clients&view=Admin_Profile_UnInvoiced';
             }
        }

    });
    invoicefiltercombo.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}});
    }

    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 PopulateInvoiceFilters(){
        Ext.Ajax.request({
           url: 'index.php?fuse=billing&action=GetInvoiceStatusFilters',
           success: function(xhr) {
                //clear the items from our combobox
                invoicetypecombo.getStore().removeAll();
                //go through our options and add to the UI
                var data = ce.parseAjaxResponse(xhr);
                //var data = Ext.util.JSON.decode(xhr.responseText);
                //data.options.forEach(updateButtonsWithContent);
                for ( var i in data.options )
                {
                    updateButtonsWithContent( data.options[i] );
                }
           },
           failure: function() { },
           params: {foo: 'bar'}
        });
    }

    PopulateInvoiceFilters();
});

function editPaymentReference(invoiceId){
    EditingPaymentReference(invoiceId);
}

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: ""
    });
}
