Ext.onReady(function(){

    var gridstore = new Ext.data.JsonStore({
            id: "gridstore",
            root: 'billingtypes',
            totalProperty: 'totalcount',
            idProperty: 'id',
            remoteSort: true,
            baseParams: {
            filter: "",
            customerid: "0"
        },
        fields: [
                'id','name','detail','count','description','price'
        ],
        // 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=admin&action=GetBillingTypes'
        })
    });
    gridstore.setDefaultSort('id', 'asc');
    gridstore.setBaseParam('active',$("billingTypeFilter").value);

    if($("billingTypeFilter").value == -1){
       viewingArchived = true;
    }else{
       viewingArchived=false;
    }

    function renderName(value,p,record){
        //make description part of the popup
        name = '<a href="javascript:ShowEditBillingTypeWindow('+record.data.id+');" id="'+record.data.id+'" class="editbillingtype" qtip="'+lang('Click to edit this billing type')+'">'+record.data.name+'</a>';
        return name;
    }

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

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

        // grid columns
        columns:[
        sm,{
            id: 'id', 
            header: lang("Id"),
            width: 15,	
    		dataIndex : "id",
            sortable: false,
            hidden:true
        },{
            id: 'name', 
            header: lang("Name"),
            width: 65,	
    		dataIndex : "name",
    		renderer: renderName,
            sortable: false
        },{
            id: 'description',
            header: lang("Invoice Description"),
            width: 85,	
    		dataIndex : "description",
            sortable: false
        },{
            id: 'price',
            header: lang("Price"),
            width: 30,
            align:"center",	
    		dataIndex : "price",
            sortable: false
        },{
            id: 'count',
            header: lang("Count"),
            width: 30,
            align:"center",	
    		dataIndex : "count",
            sortable: false
        }

        ],
		stripeRows: true,
        // customize view config
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no billing types available to view at this time"),
	    scrollOffset:1
        },
        sm: sm,
        // inline buttons
        buttons:[
            deletebutton = new Ext.Button({
                 id:'actionbuttons',
                 autoHeight:true,
                 xtype:'button',
                 text:'Delete',
                 disabled: true,
                 onClick: function(record){
                        if(!deletebutton.disabled){
                            requesturl = "index.php?fuse=billing&action=DeleteBillingType";
                            ProcessAction(requesturl);
                        }
                    }
                 }),
             archivebutton = new Ext.Button({
                 id:'statusbuttons',
                 autoHeight:true,
                 xtype:'button',
                 text:(viewingArchived)? lang('Un-Archive'): lang('Archive'),
                 disabled: true,
                 onClick: function(record){
                        if(!archivebutton.disabled){
                            if(viewingArchived){
                                requesturl = "index.php?fuse=admin&action=UnArchiveBillingTypes";
                            }else{
                                requesturl = "index.php?fuse=admin&action=ArchiveBillingTypes";
                            }
                            ProcessAction(requesturl);
                        }
                    }
             })
        ],
        buttonAlign:'left'

    });


    // option button code
    function toggleButtons(count){
        if(count == undefined){
            count = sm.getCount();
        }
        if(count>0){
            deletebutton.setDisabled(false);
            archivebutton.setDisabled(false);
        }else{
            deletebutton.setDisabled(true);
            archivebutton.setDisabled(true);
        }
    }
      
    function GetSelectedRowIds(){
        var arrayofids = new Array();
        rows = sm.getSelections();
	    for(x=0;x<rows.length;x++){
	       arrayofids[x] = rows[x].data.id;
	    }
	    return arrayofids;
    }
        
    function ProcessAction(requesturl){
	    grid.disable();
	    	    
	    Ext.Ajax.request({
           url: requesturl,
           success: function(xhr) {
                //refreshgrid
                grid.enable()
                gridstore.load({params:{start:0}});   
                toggleButtons(0);
                
                var data = Ext.util.JSON.decode(xhr.responseText);
                if(data.message){
                    msg(data.message,"");
                }else{
                    msg(lang("Billing Type(s) have been updated"),"");
                } 
           },
           failure: function() {
                grid.enable()
                msg(lang("There was an error performing this action"),"");
           },
           params: { 
            ids: Ext.util.JSON.encode(GetSelectedRowIds())
            }
        });   
    }

    // render it
    grid.render();
    
	//check to see if I'm looking at archived or active coupons.
    gridstore.setBaseParam('limit', 50);
    gridstore.load({params:{start:0}});  

});