/*
 * 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','customername','description','billdate','billbalancedue','clientid','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', 'billing uninvoiced list');

    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){
            deletebutton.setDisabled(false);
        }else{
            deletebutton.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 invoices') +' {0} - {1}' + ' of ' + '{2}',
        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;

				$('uninvoicedlistlabel').innerHTML = String.format(lang('Displaying Un-Invoiced Work') +' {0} - {1}' + ' of ' + '{2}',from,to,data.total);
            }
        }
    })

    function renderName(value,p,record){
        name = "<a href='index.php?fuse=clients&view=Admin_Profile_Contact&frmClientID="+record.data.clientid+"'  qtip='Go to customer profile'>"+record.data.customername+"</a>&nbsp;&nbsp;";
        return name;
    }

    function renderDate(value,p,record){
        date = record.data.billdate+"&nbsp;&nbsp;";
        return date;
    }

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

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

    }

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

    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: 'linkid',
            header: lang("#"),
            width: 45,
            renderer: renderId,
            dataIndex : "invoiceentryid",
            align:"center"
        },{
            id: 'description',
            header: lang("Subject"),
            align:"left",
            dataIndex : "description",
            width: 300
        },{
            id: 'customername',
            header: lang("Customer Name"),
            width: 100,
            align:"right",
            renderer: renderName,
            dataIndex : "customername"
        },{
            id: 'include',
            header: lang("Include In Next"),
            width: 80,
            renderer: renderIncludeInNextInvoice,
            align:"center"
        },{
            id: 'billdate',
            header: lang("Due Date"),
            renderer: renderDate,
            dataIndex : "billdate",
            width: 80,
            align:"right"
        },{
            id: 'billbalancedue', 
            header: lang("Amount Due"),
            width: 80,
            renderer: renderDue,
            dataIndex : "billbalancedue",
            align:"right"
        }],
        sm: sm
        ,stripeRows: true,
        // customize view config
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no Un-Invoiced work available to view at this time"),
            scrollOffset:1
        },
        // paging bar on the bottom
        bbar: gridbb,
        buttonAlign: "left",
        buttons:[ deletebutton = new Ext.Button({
                     id:'deletebutton',
                     autoHeight:true,
                     arrowAlign:'right',
                     xtype:'splitbutton',
                     text:lang('Delete'),
                     disabled: true
                 })
             ]
    });
    
    var btnButtonActionHandler = function(button, event){
        requesturl = "index.php?fuse=billing&action=Admin_ActOnInvoices";
        var sendReceipt = "";
        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) {
                        //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: Ext.util.JSON.encode(getInvoiceItems()),
                     itemstype: Ext.util.JSON.encode('uninvoiced'),
                     actionbutton: Ext.util.JSON.encode(button.id)
            }
        });
    }
    function addButtonListeners(){
        deletebutton.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({
        tpl: '<tpl for="."><div ext: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'], [50, '50'], [150,'150'],[300,'300']]
        }),
        valueField: 'myId',
        width: 50,
        displayField: 'displayText',
        applyTo: 'numlistfilter',
        // 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 detailstittle = "<h2>"+lang("Details")+":</h2>";
        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.");
        
        var invoicetypeinfo = "";
        
        invoicetypeinfo = lang(" 	Uninvoiced Work");
        
        additionalinfo = detailstittle + invoicetypeinfo + ": " + data.totalcount + "<br>"+lang("Total")+": " + data.outstandingamount;
        if (pricetypecombo){
            if(pricetypecombo.getValue() == 1){
                additionalinfo += "<br><br>" + multicurrencynotice;
            }
        }
        //$('divdetails').innerHTML = additionalinfo;
        //$('divdetails').style.display = "";
    });
    
    if($('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")

    }

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