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

var entries_store;

Ext.onReady(function(){
    var from;

    Ext.QuickTips.init();
    entries_store = new Ext.data.JsonStore({
        id: "gridstore",
        root: 'uninvoiced',
        totalProperty: 'totalcount',
        idProperty: 'invoiceentryid',
        remoteSort: true,
        fields: [
            'invoiceentryid','billdate','description','billtype','billbalancedue','taxable','includeinnextpayment','appliestoid'
        ],

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

    entries_store.setBaseParam('moduleview', 'clients uninvoiced');

    entries_store.setDefaultSort('id', 'desc');

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

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

        if(count > 0){
            createinvoicebutton.setDisabled(false);
            deletebutton.setDisabled(false);
            if(mergeintomenu.items != undefined){
                mergeintobutton.setDisabled(false);
            }
        }else{
            createinvoicebutton.setDisabled(true);
            deletebutton.setDisabled(true);
            mergeintobutton.setDisabled(true);
        }
    }

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

    var gridbb = new Ext.PagingToolbar({
        store: entries_store,
        //displayInfo: true,
        //displayMsg: lang('Displaying uninvoiced') +' {0} - {1}' + ' of ' + '{2}',
        //emptyMsg: lang("No users to display"),
        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('uninvoicedlistlabel').innerHTML = String.format(lang('Displaying uninvoiced') +' {0} - {1}' + ' of ' + '{2}',from,to,data.total);
            }
        }
    })

    function renderTaxable(value,p,record){
        if(record.data.taxable == 0){
            taxable = lang('No');
        }else{
            taxable = lang('Yes');
        }
        return taxable;
    }

    function renderIncludeInNextInvoice(value,p,record){
        if(record.data.includeinnextpayment==1){
            text = '<a href="#" qtip="This entry will be included in the next automatically generated invoice for package #'+record.data.appliestoid+'">'+lang('Yes')+'</a>';
        }else{
            text = lang('No');
        }
        return text;
    }

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

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

        // grid columns
        columns:[
            sm,
        {
            id: 'billdate',
            header: lang("Due Date"),
            dataIndex : "billdate",
            width: 60,
            align:"right"
        },{
            id: 'description',
            header: lang("Description"),
            renderer: renderDescription,
            width: 300
        },{
            id: 'billtype',
            header: lang("Billing Type"),
            dataIndex : "billtype",
            width: 160
        },{
            id: 'billbalancedue',
            header: lang("Taxable"),
            width: 50,
            renderer: renderTaxable,
            align:"center"
        },{
            id: 'include',
            header: lang("Include In Next"),
            width: 80,
            renderer: renderIncludeInNextInvoice,
            align:"center"
        }
        ,{
            id: 'billbalancedue',
            header: lang("Amount"),
            width: 80,
            dataIndex : "billbalancedue",
            align:"right"
        }],
        sm: sm
        ,stripeRows: true,
        // customize view config
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no un-invoiced work items available to view at this time"),
            scrollOffset:1
        },
        // paging bar on the bottom
        bbar: gridbb,
        buttonAlign:'left',
        buttons:[ createinvoicebutton = new Ext.Button({
                     id:'createinvoicebutton',
                     autoHeight:true,
                     xtype:'button',
                     text:"&nbsp;"+lang('Create Invoice')+"&nbsp;",
                     disabled: true

                 }),
                 deletebutton = new Ext.Button({
                     id:'deletebutton',
                     autoHeight:true,
                     xtype:'button',
                     text:"&nbsp;"+lang('Delete')+"&nbsp;",
                     disabled: true

                 }),
                 mergeintobutton = new Ext.Button({
                     id:'mergeintobutton',
                     autoHeight:true,
                     xtype:'button',
                     text:"&nbsp;"+lang('Merge Into')+"&nbsp;",
                     disabled: true,
                     menu: mergeintomenu = new Ext.menu.Menu({
                         enableScrolling:false,
                         shadow:false
                     })
                 })
             ]
    });

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

                if (document.getElementById('profile-header-credit-value')) {
                    document.getElementById('profile-header-credit-value').innerHTML = data.balance.credit;
                    document.getElementById('profile-header-totalpaid-value').innerHTML = data.balance.totalpaid;
                    document.getElementById('profile-header-uninvoiced-value').innerHTML = data.balance.uninvoiced;
                    document.getElementById('profile-header-totalunpaid-value').innerHTML = data.balance.totalunpaid;
                }
            },
            failure:    function(){
            }
        });
    }

    var btnButtonActionHandler = function(button, event){
        requesturl = "index.php?fuse=billing&action=Admin_ActOnInvoices";
        var sendReceipt = "";
        if(button.id == "createinvoicebutton"){
        }else if(button.id == "deletebutton"){
            confirmmsg = lang("Click OK if you are sure you want to delete the selected items.");
            var deleteItems = confirm(confirmmsg);
            if(deleteItems == false){
               return false;
            }
        }

        Ext.Ajax.request({
           url: requesturl,
           success: function(xhr) {
               refreshProfileHeaderBalance();
                        //refreshgrid
                        grid.enable();
                        entries_store.load({params:{start:0}});
                        toggleButtons(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("Uninvoiced work have been updated"));
                        }
                    },
           failure: function() {
                grid.enable()
                Ext.Msg.alert("Fail");
           },
           params: { items: getInvoiceItems(),
                     itemstype: 'uninvoiced',
                     actionbutton: button.id
            }
        });
    }
    function addButtonListeners(){
        createinvoicebutton.addListener("click",btnButtonActionHandler);
        deletebutton.addListener("click",btnButtonActionHandler);
        //mergeintobutton.addListener("click",btnButtonActionHandler);
    }
    addButtonListeners();

    grid.render();

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

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

    entries_store.on('load',function(){
        var data = entries_store.reader.jsonData;
        var cm = grid.getColumnModel();
        var multicurrencynotice = "<h2><font color=red>"+lang("Notice")+":</font></h2>"+lang("You are using the Customer's Price Estimation, so all the values below are approximated values depending on the currencies rates.");

        additionalinfo = "";
    });

    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: 1,
        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_Invoices';
             }
        }

    });
    invoicefiltercombo.wrap.addClass("x-form-field-float-left");

    function SelectPrice(filter){
        if(filter!=null) entries_store.setBaseParam('pricefilter', filter);
        if(from != undefined && from != null){
            entries_store.load({params:{start:from - 1}});
        }else{
            entries_store.load({params:{start:0}});
        }
    }

    function MergeToInvoice(button, event){


        var InvoiceItems = getInvoiceItems();
        if(InvoiceItems == ""){
            mergecombo.setValue("");
            strAlertMessage = "You need to select entry(s) to perform this action on";
            alert(strAlertMessage);
            return false;
        }
        if(button.id == null || button.id == ""){
            return;
        }

        requesturl = "index.php?fuse=billing&action=Admin_ActOnInvoices";

        Ext.Ajax.request({
           url: requesturl,
           success: function(xhr) {
                        //refreshgrid
                        grid.enable();
                        entries_store.load({params:{start:0}});
                        toggleButtons(0);
                        mergecombo.setValue("");

                        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("Uninvoiced work have been updated"));
                        }
                    },
           failure: function() {
                grid.enable()
                mergecombo.setValue("");
                Ext.Msg.alert("Fail");
           },
           params: { items: getInvoiceItems(),
                     itemstype: 'uninvoiced',
                     invoiceid: button.id,
                     actionbutton: "mergeintoinvoice"
            }
        });
    }

    function updateMergeDropdown(data){
        //update the button instad of the dropdown list
        if(data.type == "merge"){
            if(data.private == undefined){
                data.private = 0;
            }

            var comboitem = new Ext.menu.Item({type: data.type, id: data.id, text: data.name});
            comboitem.addListener("click",MergeToInvoice);

            mergeintomenu.add(comboitem);
        }
    }

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

                        //go through our options and add to the UI
                        var data = Ext.util.JSON.decode(xhr.responseText);
                        //data.options.forEach(updateMergeDropdown);

                        for ( var i in data.options )
                        {
                            updateMergeDropdown( data.options[i] );
                        }

                    },
           failure: function() {
                Ext.Msg.alert("Fail");
           },
           params: { foo: 'bar' }
        });
    }

    PopulateMergeDropdown();

});