licensedefender = {};

Ext.onReady(function(){

    licensedefender.searchkey = "";

    new Ext.Button({
        id:"gridaddresellerbtn",
        renderTo:"gridaddresellerbtn",
        text: lang('Add Reseller'),
        handler: function() {
            LazyLoad.js(['../plugins/snapins/licensedefender/reseller_edit.js'], function () {
                licensedefender.addeditReseller($('#gridaddresellerbtn').offset().left,($('#gridaddresellerbtn').offset().top+5));
            });
        }
    });

    licensedefender.gridstore = new Ext.data.JsonStore({
        root: 'data.resellers',
        idProperty: 'domain',
        totalProperty: 'totalcount',
        remoteSort : true,
        sortInfo: {
            field: 'license',
            direction: 'DESC' // or 'DESC' (case sensitive for local sorting)
        },
        baseParams: {
            searchkey: ""
        },
        fields: ['id','email','username','userurl','license','used','group','check_ip','ip_range'],
        proxy: new Ext.data.HttpProxy({
                url: 'index.php?fuse=home&action=DoSnapinPluginAction&plugin=licensedefender&pluginAction=getResellerList'
        }),
        listeners: {
            'load' : function(s,r,o) {

                if (s.reader.jsonData.data.resellertotals) {
                    $('#totalresellers_count').text(s.reader.jsonData.data.resellertotals.totalresellers);
                    $('#totallicenses_count').text(s.reader.jsonData.data.resellertotals.allotted);
                    $('#usedlicenses_count').text(s.reader.jsonData.data.resellertotals.used);
                }

                /*
                //need to set all expanded to collapsed since our rowexpander has lazy render:true (needs true since we are calling for content their via ajax)
                $('.x-grid3-row-expanded').removeClass('x-grid3-row-expanded').addClass('x-grid3-row-collapsed');
                */
                licensedefender.toggleButtons();
            }
        }
    });


    licensedefender.searchreseller = function() {
        //clientexec
        var searchkey = $('#searchreseller').val();
        licensedefender.searchkey = trim(searchkey);
        licensedefender.gridstore.setBaseParam('searchkey', licensedefender.searchkey);
        licensedefender.gridstore.load({params:{start:0,limit:10}});
        if (licensedefender.searchkey =="") {
             $('#searchkey').text("");
        } else {
             $('#searchkey').html("searching <span style='color:orange;'>"+licensedefender.searchkey+"</span>");
        }

    }

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


    licensedefender.toggleButtons = function(count){
        if(count == undefined){
            count = licensedefender.sm.getCount();
        }
        if(count == 1){
            Ext.getCmp('deletereseller').setDisabled(false);
        }else{
            Ext.getCmp('deletereseller').setDisabled(true);
        }
    }

    licensedefender.gridbb = new Ext.PagingToolbar({
        id:'licensegridpagingbar',
        store: licensedefender.gridstore,
        pageSize: 10,
        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('licensegridpagingbar').style.display = ( data.pages > 1 ) ? '' : 'none';
				document.getElementById('domainlistlabel').innerHTML = String.format(lang('Displaying licenses') +' {0} - {1}' + ' of ' + '{2}',from,to,data.total);
          }
        }
    });

    licensedefender.renderUserLink = function (value,p,record)
    {
        if (record.data.userurl == "") {
            return "<span style='color:red;'>No record</font>";
        } else {
            return "<a href='index.php?fuse=clients&view=Admin_Profile_Products&"+record.data.userurl+"'>View User Record</a>";
        }
    }

    licensedefender.editReseller = function(resellerid) {
        LazyLoad.js(['../plugins/snapins/licensedefender/reseller_edit.js'], function () {
            id = "#reseller_"+resellerid;
            licensedefender.addeditReseller($(id).offset().left,($(id).offset().top+5),resellerid);
        });
    }

    licensedefender.renderUserName = function (value,p,record)
    {
        return "<a style='cursor:pointer' id='reseller_"+record.data.id+"' qtip='Edit reseller: "+record.data.username+"' onclick='licensedefender.editReseller("+record.data.id+")'>"+record.data.username+"</a>";
    }

    licensedefender.grid = new Ext.grid.GridPanel({
        store:licensedefender.gridstore,
        columns: [
        licensedefender.sm,
        {
            header: lang("Reseller"),
            sortable: true,
            dataIndex: 'username',
            renderer: licensedefender.renderUserName
        },
        {
            header : lang('Profile'),
            sortable: false,
            dataIndex: 'userurl',
            width: 30,
            align: 'center',
            renderer: licensedefender.renderUserLink
        },
        {
            header: lang("Total"),
            hidden:false,
            sortable: true,
            dataIndex: 'license',
            align: 'center',
            width: 20
        },
        {
            header: lang("Used"),
            hidden:false,
            sortable: true,
            dataIndex: 'used',
            align: 'center',
            width: 20
        }
        ],
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are currently no licenses to view"),
            scrollOffset:1
        },
        loadMask: true,
        columnLines: true,
        autoHeight:true,
        sm:               licensedefender.sm,
        // paging bar on the bottom
        bbar: licensedefender.gridbb,
        stripeRows: true,
        collapsible: false,
        buttonAlign:'left',
        iconCls: 'icon-grid',
        id:       'domains-grid',
        el:       'domains-grid',
        buttons:[
            {
                id:'deletereseller',
                text: lang('Delete Reseller'),
                disabled: true,
                onClick:  function(record){
                    if(!Ext.getCmp('deletereseller').disabled) {
                        licensedefender.deleteReseller();
                    }
                }
            }
        ]
    });


    licensedefender.getSelectedRows = function(){
        var domainrecords = [];
        rows = licensedefender.sm.getSelections();
        for(x=0;x<rows.length;x++){
            domainrecords.push(rows[x]);
        }
        return domainrecords;
    }

    licensedefender.deleteReseller = function()
    {
        var rows = licensedefender.getSelectedRows();
        Ext.MessageBox.confirm('Confirm Reseller Deletion:', "Are you sure you want to remove reseller: "+rows[0].data.username, function(btn){
            if (btn == "yes") {
                for (var x=0;x< rows.length; x++) {
                    Ext.Ajax.request({
                        url: 'index.php?fuse=home&action=DoSnapinPluginAction',
                        success: function(xhr) {
                            var json = ce.parseAjaxResponse(xhr);
                            licensedefender.gridstore.load({params:{start:0,limit:10}});
                        },
                        params: {
                            plugin: 'licensedefender',
                            pluginAction : 'deleteReseller',
                            resellerid: rows[x].data.id
                        }
                    });
                }
            }
        }, this);

    }

    licensedefender.gridstore.load({params:{start:0,limit:10}});
    licensedefender.grid.render();

});