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

//making global so it can be refreshed from external add invoice buttons
var entries_store;

Ext.onReady(function(){    
    Ext.QuickTips.init();

    var RecurringCharge = Ext.data.Record.create([
       {name: 'id'},
       {name: 'nextdate'},
       {name: 'amount'},
       {name: 'name'},
       {name: 'paymentterm_mashup'},
       {name: 'paymentterm_word'},
       {name: 'package'},
       {name: 'desc'},
       {name: 'taxable'},
       {name: 'disablegenerate'},
       {name: 'realdisablegenerate'},
       {name: 'billingtype'},
       {name: 'readonly'},
       {name: 'subscriptionid'}
    ]);

   var myReader = new Ext.data.JsonReader(
    {                             // The metadata property, with configuration options:
        totalProperty: "totalcount", //   the property which contains the total dataset size (optional)
        root: "data",             //   the property which contains an Array of record data objects
        id: "id"          //   the property within each row object that provides an ID for the record (optional)
    },
    RecurringCharge  // Ext.data.Record constructor that provides mapping for JSON object
    );

    entries_store = new Ext.data.GroupingStore({
      id: "entries_store",
      url: 'index.php?fuse=billing&action=Admin_GetRecurringCharges',
      reader: myReader,
      remoteSort: true,
      groupField: 'package',
      fields: [
                'id','billingtype','nextdate','amount','paymentterm_word','paymentterm_mashup','package','desc','name','taxable','disablegenerate', 'realdisablegenerate', 'readonly', 'subscriptionid'
      ],
      sortInfo: { field: "nextdate", direction: "ASC" }
    });

    function renderName(value,p,record){
        tSubscriptionId = '';
        if(record.data.subscriptionid != null && record.data.subscriptionid != ""){
            tSubscriptionId = '  (Subscr. ' + record.data.subscriptionid + ')';
        }
        
        if(record.data.billingtype == lang("Product")){
            //name = record.data.name + record.data.disablegenerate + tSubscriptionId;
            name = '<a href="javascript:ShowEditInvoiceEntryWindow('+record.data.id+',true,true);" id="'+record.data.id+'" qtip="<b>Description</b>: '+record.data.desc+'">'+record.data.name+'</a> '+record.data.disablegenerate + tSubscriptionId;
        }else{
            name = '<a href="javascript:ShowEditInvoiceEntryWindow('+record.data.id+',true);" id="'+record.data.id+'" qtip="<b>Description</b>: '+record.data.desc+'">'+record.data.name+'</a> '+record.data.disablegenerate + tSubscriptionId;
        }
        return name;
    }

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

    var recurringgrid_sm = new Ext.grid.CheckboxSelectionModel({
        renderer: function(value, metaData, record){
            // Hide checkbox for certain records
            if(record.get('billingtype') == lang("Product") || record.get('readonly')){
                return;
            }
            return Ext.grid.CheckboxSelectionModel.prototype.renderer.apply(this, arguments);
        },
        listeners:{
             'rowdeselect': function(model, rowIndex, record){
                    toggleButtons();
              },
              'rowselect': function(model, rowIndex, record){
                    toggleButtons();
              },
              'beforerowselect': function(selModel, rowIndex, keepExisting, record){
                    // Don't allow selection for certain records
                    if(record.get('billingtype') == lang('Product') || record.get('readonly')){
                        return false;
                    }
                }
        }
    });

    function renderAmount(value,p,record){
        return record.data.amount;
    }
    function renderPaymentCycle(value,p,record){
        return record.data.paymentterm_word + record.data.paymentterm_mashup;
    }
    var recurringgrid = new Ext.grid.GridPanel({
       store:entries_store,
        columns: [
            recurringgrid_sm,
            {header: lang("Next Date"), width: 20, sortable: true, align:'center', dataIndex: 'nextdate'},
            {header: lang("Billing Type"), width: 20, sortable: true, align:'center', dataIndex: 'billingtype'},
            {id:'name',header: lang("Name"), sortable: true, renderer: renderName, dataIndex: 'name'},
            {header: lang("Amount"), width: 20, sortable: true,  align:'center',renderer: renderAmount},
            {header: lang("Taxable"), width: 20, sortable: true,  align:'center',renderer: renderTaxable},
            {header: lang("Cycle"), width: 20, sortable: false,  align:'center',renderer: renderPaymentCycle},
            {header: lang("Associated To Package"), width: 20, sortable: true, hidden:true, dataIndex: 'package'}
        ],
        view: new Ext.grid.GroupingView({
            forceFit:true,
            groupFit:true,
            scrollOffset:1,
            emptyText: lang("There are no recurring charges available"),
            groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
        }),
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no products available"),
            scrollOffset:1
        },
        sm:recurringgrid_sm,
        frame:false,
        loadMask: true,
        columnLines: true,
        autoHeight:true,
        collapsible: false,
        // inline buttons
        buttons: [deletebutton = new Ext.Button({
                     id:'deletebutton',
                     text:lang('Delete'),
                     disabled: true,
                     handler: function(){
                         PerformActionOnRecurringCharges("index.php?fuse=billing&action=Admin_DeleteRecurringCharge");
                     }
                 })
             ],
        buttonAlign:'left',
        animCollapse: false,
        title: '',
        iconCls: 'icon-grid',
        renderTo: 'recurringcharges-grid'
    });
    entries_store.load({params:{start:0}});

    // option button code
    function toggleButtons(count){
        if((recurringgrid_sm.getCount()>0) && (count!=0)){
            deletebutton.setDisabled(false);
        }else{
            deletebutton.setDisabled(true);
        }
    }

    function GetSelectedRowIds(){
        var arrayofids = new Array();
        rows = recurringgrid_sm.getSelections();
        for(x=0;x<rows.length;x++){
           arrayofids[x] = rows[x].data.id;
        }
        return arrayofids;
    }

    function PerformActionOnRecurringCharges(requesturl){
        recurringgrid.disable();
        Ext.Ajax.request({
           url: requesturl,
           success: function(xhr) {
                //refreshgrid
                recurringgrid.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("Action on Recurring Charge(s) have been performed"));
                }
           },
           failure: function() {
                recurringgrid.enable();
                Ext.Msg.alert("Fail");
           },
           params: {ids: Ext.util.JSON.encode(GetSelectedRowIds())

            }
        });
    }

    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");
    }
    function SelectPrice(filter){
        if(filter!=null) entries_store.setBaseParam('pricefilter', filter);
        entries_store.load({params:{start:0}});
    }

});