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

var ShowingInvoiceDetails = '';

var invoicestore = null;
var grid2 = null;
var sm2 = null;
var deletebutton2 = null;
var move2uninvoiced = null;
var btnButtonActionHandler2 = null;

Ext.onReady(function(){
    //pricefilter 0 for real price 1 for estimated price
    ShowingInvoiceDetails = function(invoice,pricefilter){
        invoicestore.setBaseParam('invoiceid', invoice);
        invoicestore.setBaseParam('pricefilter', pricefilter);
        invoicestore.load();
        grid2.show();
    }

    invoicestore = new Ext.data.JsonStore({
        id: "invoicestore",
        root: 'invoiceentries',
        totalProperty: 'totalcount',
        idProperty: 'invoiceentryid',
        remoteSort: true,
        fields: [
            'invoiceentryid','billdate','description','billtype','billbalancedue','billtaxprice','billtax2price'
        ],

        // 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=GetInvoiceEntries'
        })
    });

    // ORDER BY isdiscount ASC, date, appliestoid, billingtypeid DESC
    //invoicestore.setDefaultSort('isdiscount', 'asc');
    invoicestore.setBaseParam('sort', 'isdiscount,date,appliestoid,billingtypeid');
    invoicestore.setBaseParam('dir', 'ASC,ASC,ASC,DESC');

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

    function toggleButtons2(count){
        if(count == undefined){
            count = sm2.getCount();
        }
        if(count > 0){
            deletebutton2.setDisabled(false);
            move2uninvoiced.setDisabled(false);
        }else{
            deletebutton2.setDisabled(true);
            move2uninvoiced.setDisabled(true);
        }
    }

    function getInvoiceItems2(){
        var invoiceItems = "";
        var rows = sm2.getSelections();
        for(var x = 0; x < rows.length; x++){
            var spacevar = " ";
            if(x !=0){
               invoiceItems += spacevar;
            }
            invoiceItems += rows[x].data.invoiceentryid;
        }
        return invoiceItems;
    }

    function renderEntryDescription(value,p,record){
        var name = '<a href="javascript:ShowEditInvoiceEntryWindow('+record.data.invoiceentryid+',false);" id="'+record.data.invoiceentryid+'" qtip="Edit this entry">'+record.data.description+'</a>';
        return name;
    }

    grid2 = new Ext.grid.GridPanel({
        el:               'invoiceentries-grid',
        autoHeight:       true,
        store:            invoicestore,
        trackMouseOver:   false,
        disableSelection: true,
        loadMask:         true,
        columns:          [
            sm2,
            {
                id:         'billdate',
                header:     lang("Due Date"),
                dataIndex:  "billdate",
                width:      60,
                align:      "left"
            },
            {
                id:         'description',
                header:     lang("Description"),
                renderer:   renderEntryDescription,
                width:      300
            },
            {
                id:         'billtype',
                header:     lang("Billing Type"),
                dataIndex:  "billtype",
                width:      120,
                align:      "right"
            },
            {
                id:         'billbalancedue',
                header:     lang("Amount"),
                width:      80,
                dataIndex:  "billbalancedue",
                align:      "right"
            },
            {
                id:         'billtaxprice',
                header:     lang("TAX 1"),
                width:      100,
                dataIndex:  "billtaxprice",
                align:      "center",
                hidden:     true
            },
            {
                id:         'billtax2price',
                header:     lang("TAX 2"),
                width:      100,
                dataIndex:  "billtax2price",
                align:      "center",
                hidden:     true
            }
        ],
        sm:               sm2,
        stripeRows:       false,
        // customize view config
        viewConfig:       {
            forceFit:       true,
            enableRowBody:  true,
            emptyText:      lang("WARNING!: This invoice has no entries"),
            scrollOffset:   1
        },
        // paging bar on the bottom
        buttonAlign:      'left',
        buttons:          [
            deletebutton2 = new Ext.Button({
                id:         'deletebutton2',
                autoHeight: true,
                xtype:      'button',
                text:       lang('Delete Selected Entry'),
                disabled:   true,
                hidden:     true
            }),
            move2uninvoiced = new Ext.Button({
                id:         'move2uninvoiced',
                autoHeight: true,
                xtype:      'button',
                text:       lang('Move to Un-Invoiced'),
                disabled:   true,
                hidden:     true
            })
        ]
    });

    btnButtonActionHandler2 = function(button, event){
        grid2.disable();
        var applyToAll = false;
        var data = invoicestore.reader.jsonData;
        var requesturl = "index.php?fuse=billing&action=Admin_ActOnInvoices";
        
        if(button.id == "deletebutton2"){
            var confirmmsg = lang("Click OK if you are sure you want to delete the selected items.");
            
            if(data.totalcount == sm2.getCount()){
                applyToAll = true;
                confirmmsg += "\n\n"+lang("Warning: By deleting all of the remaining entries, this invoice will be deleted as well.");
            }
            
            Ext.Msg.confirm(lang('Delete Entries?'), confirmmsg, function(btn, text){
                if(btn == 'yes'){
                    //delete entries
                    Ext.Ajax.request({
                        url:      requesturl,
                        success:  function(xhr){
                            //refreshgrid2
                            if(applyToAll){
                                hideInvoiceDetails();
                                
                                if(typeof(invoices_store) != 'undefined'){
                                    invoices_store.load();
                                }
                            }else{
                                // Refresh the invoice grid
                                grid2.enable();
                                invoicestore.load();
                            }
                            
                            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 entries have been updated"));
                            }
                        },
                        failure:  function(){
                            grid2.enable();
                            Ext.Msg.alert("Fail");
                        },
                        params:   {
                            items:        getInvoiceItems2(),
                            itemstype:    'invoiceentries',
                            actionbutton: button.id,
                            invoiceid:    data.invoiceid
                        }
                    });
                }
            });
        }else if(button.id == "move2uninvoiced"){
            var confirmmsg = lang("Click OK if you are sure you want to move the selected items to un-invoiced work.");
            
            if(data.totalcount == sm2.getCount()){
                applyToAll = true;
                confirmmsg += "\n\n"+lang("Warning: By moving all of the remaining entries to un-invoiced work, this invoice will be deleted.");
            }
            
            Ext.Msg.confirm(lang('Move Entries To Un-Invoiced Work?'), confirmmsg, function(btn, text){
                if(btn == 'yes'){
                    //move entries
                    Ext.Ajax.request({
                        url:      requesturl,
                        success:  function(xhr){
                            //refreshgrid2
                            if(applyToAll){
                                hideInvoiceDetails();
                                
                                if(typeof(invoices_store) != 'undefined'){
                                    invoices_store.load();
                                }
                            }else{
                                // Refresh the invoice grid
                                grid2.enable();
                                invoicestore.load();
                            }
                            
                            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 entries have been updated"));
                            }
                        },
                        failure:  function(){
                            grid2.enable();
                            Ext.Msg.alert("Fail");
                        },
                        params:   {
                            items:        getInvoiceItems2(),
                            itemstype:    'invoiceentries',
                            actionbutton: button.id,
                            invoiceid:    data.invoiceid
                        }
                    });
                }
            });
        }
        
        return false;
    }
    
    function addButtonListeners2(){
        deletebutton2.addListener("click",btnButtonActionHandler2);
        move2uninvoiced.addListener("click",btnButtonActionHandler2);
    }
    
    addButtonListeners2();
    
    grid2.hide();
    grid2.render();
    
    invoicestore.on('load',function(){
        toggleButtons2(0);
        
        var data = invoicestore.reader.jsonData;
        
        //create content to put in the invoice summary header
        var invoiceDetails = '';
        invoiceDetails += "<span style='float:left;'><h2>" + lang("Invoice") + " #" + data.invoiceid + "</h2></span>";
        invoiceDetails += "<span style='float:right;'><b>" + lang("Sent") + ":</b> " + data.invoicedatesent + "&nbsp;&nbsp;&nbsp;&nbsp;<b>" + lang("Paid") + ":</b> " + data.invoicedatepaid + "</span>";
        invoiceDetails += "<div style='clear:both;'></div>";
        document.getElementById('divinvoicedetails').innerHTML = invoiceDetails;
        document.getElementById('divinvoicedetails').style.display = "";
        
        //create content to put in the total below
        var invoiceDetailsTotals = '';
        
        if(data.taxed){
            invoiceDetailsTotals += lang("Subtotal") + ": " + data.outstandingamount + "<br/>";
            
            if(data.invoicetax > 0){
                invoiceDetailsTotals += data.invoicetaxname + ' (' + data.invoicetax + '%)' + ": " + data.totaltaxed + "<br/>";
            }
            
            if(data.invoicetax2 > 0){
                invoiceDetailsTotals += data.invoicetax2name + ' (' + data.invoicetax2 + '%)' + ": " + data.totaltaxed2 + "<br/>";
            }
        }
        
        invoiceDetailsTotals += lang("Total") + " " + data.invoicetotal + "<br/>";
        
        if(data.invoicepartiallypaid){
            invoiceDetailsTotals += lang("Paid") + ": (" + data.invoiceamountpaid + ")<br/>";
            invoiceDetailsTotals += lang("Due") + ": " + data.invoicebalancedue;
        }
        
        document.getElementById('divinvoicedetails-totals').innerHTML = invoiceDetailsTotals;
        document.getElementById('divinvoicedetails-totals').style.display = "";
        
        var cm = grid2.getColumnModel();
        
        if(data.caneditdetails){
            cm.setHidden(0, false);
            deletebutton2.show();
            move2uninvoiced.show();
        }else{
            cm.setHidden(0, true);
            deletebutton2.setDisabled(true);
            deletebutton2.hide();
            
            move2uninvoiced.setDisabled(true);
            move2uninvoiced.hide();
        }
        
        if(data.invoicetax > 0){
            cm.setColumnHeader(cm.findColumnIndex("billtaxprice"), data.invoicetaxname + ' (' + data.invoicetax + '%)');
            cm.setHidden(cm.findColumnIndex("billtaxprice"), false);
        }else{
            cm.setHidden(cm.findColumnIndex("billtaxprice"), true);
        }

        if(data.invoicetax2 > 0){
            cm.setColumnHeader(cm.findColumnIndex("billtax2price"), data.invoicetax2name + ' (' + data.invoicetax2 + '%)');
            cm.setHidden(cm.findColumnIndex("billtax2price"), false);
        }else{
            cm.setHidden(cm.findColumnIndex("billtax2price"), true);
        }
    });
    
    function hideInvoiceDetails(){
        grid2.hide();
        document.getElementById('divinvoicedetails').innerHTML = "";
        document.getElementById('divinvoicedetails').style.display = "none";
        document.getElementById('divinvoicedetails-totals').innerHTML = "";
        document.getElementById('divinvoicedetails-totals').style.display = "none";
    }
});