licensedefender = {};

Ext.onReady(function(){

    licensedefender.loggedinas = "";
    licensedefender.searchkey = "";

    new Ext.Button({
        id:"gridadddomainbtn",
        renderTo:"gridadddomainbtn",
        text: lang('Add License(s)'),
        handler: function() {
            LazyLoad.js(['../plugins/snapins/licensedefender/license_edit.js'], function () {
                licensedefender.addLicense($('#gridadddomainbtn').offset().left,($('#gridadddomainbtn').offset().top+5));
            });
        }
    });

    licensedefender.editLicense = function(license,recordid,resellerid,is_owned,limit_users) {
        LazyLoad.js(['../plugins/snapins/licensedefender/license_edit.js'], function () {
            id = "#license_"+recordid;
            if (limit_users != null) {
                type = 1; //25 user licenses
            } else {
                type = 0; //unlimited
            }
            licensedefender.viewEditLicense(license,type,resellerid,$(id).offset().left,($(id).offset().top+5));
        });
    }

    licensedefender.searchlicense = function() {
        //clientexec
        var searchkey = $('#searchlicense').val();
        licensedefender.searchkey = trim(searchkey);
        licensedefender.gridstore.setBaseParam('searchkey', licensedefender.searchkey);
        licensedefender.gridstore.load({params:{start:0,limit:10}});
        if (licensedefender.searchkey =="") {
             $('#searchkey').text("");
             document.getElementById('usedlicenses').style.display = '';
             //we are showing resellers
             if(licensedefender.loggedinas !="") {
                document.getElementById('totallicenses').style.display = '';
                document.getElementById('remaininglicenses').style.display = '';
             } else {
                document.getElementById('totallicenses').style.display = 'none';
                document.getElementById('remaininglicenses').style.display = 'none';
             }

        } else {
             $('#searchkey').html("searching <span style='color:orange;'>"+licensedefender.searchkey+"</span>");
             document.getElementById('usedlicenses').style.display = 'none';
             document.getElementById('totallicenses').style.display = 'none';
             document.getElementById('remaininglicenses').style.display = 'none';
        }

    }

    licensedefender.removeAllFilters = function() {
        licensedefender.loggedinas = '';
        licensedefender.searchkey = '';
        licensedefender.gridstore.setBaseParam('searchkey', licensedefender.searchkey);
        licensedefender.gridstore.setBaseParam('loginas', licensedefender.loggedinas);
        $('#searchkey').text("");
        $('#searchlicense').val("");
        $('#loggedinas').text("");
        licensedefender.gridstore.load({params:{start:0,limit:10}});
        if (Ext.getCmp('resellerfilter')) {
            Ext.getCmp('resellerfilter').setValue('All');
        }
        Ext.getCmp('gridadddomainbtn').setText(lang('Add License(s)'));
        document.getElementById('usedlicenses').style.display = '';
    }

    licensedefender.loadResellerLicenses = function(reseller) {
        licensedefender.loggedinas = reseller;
        $('#loggedinas').text("("+licensedefender.loggedinas+")");
        licensedefender.gridstore.setBaseParam('loginas', licensedefender.loggedinas);
        licensedefender.gridstore.load({params:{start:0,limit:10}});
        if (Ext.getCmp('resellerfilter')) {
            Ext.getCmp('resellerfilter').setValue(reseller);
        }
        var btnText = (licensedefender.loggedinas !="") ? lang('Add License(s) to')+" "+licensedefender.loggedinas : lang('Add License(s)');
        Ext.getCmp('gridadddomainbtn').setText(btnText);
    }
    
    licensedefender.filterstore = new Ext.data.JsonStore({
        id:             "filterstore",
        root:           'data',
        idProperty:     'username',
        remoteSort:     true,
        fields:         ['username'],
        proxy:          new Ext.data.HttpProxy({
            url:  'index.php?fuse=home&action=DoSnapinPluginAction&plugin=licensedefender&pluginAction=getResellerNames'
        })
    });

    licensedefender.showResellerFilter = function(){
        $('#resellerfilterdiv').css("display","");
        // Create the dropdown of Registrar plugins
        if (!licensedefender.resellerfilter) {
            licensedefender.resellerfilter = new Ext.form.ComboBox({
                id: 'resellerfilter',
                triggerAction: 'all',
                lazyRender:true,
                editable:false,
                value:'All',
                width: 200,
                store:licensedefender.filterstore,
                displayField:'username',
                hiddenName: 'reseller',
                valueField:'username',
                mode:'local',
                beforeBlur : Ext.emptyFn,
                applyTo: 'resellerfilter',
                listeners:{
                    'select': function(cb,record){
                        licensedefender.loadResellerLicenses(cb.getValue());
                    }
                }
            });
        }
        licensedefender.filterstore.load();
    }


    licensedefender.gridstore = new Ext.data.JsonStore({
        root: 'data.licenses',
        idProperty: 'domain',
        totalProperty: 'totalcount',
        remoteSort : true,
        sortInfo: {
            field: 'domain',
            direction: 'ASC'
        },
        baseParams: {
            loginas: "",
            searchkey: ""
        },
        fields: ['domain','reseller','resellerid','licensekey','is_owned','limit_users'],
        proxy: new Ext.data.HttpProxy({
                url: 'index.php?fuse=home&action=DoSnapinPluginAction&plugin=licensedefender&pluginAction=getDomains'
        }),
        listeners: {
            'load' : function(s,r,o) {
                //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.permissions = s.reader.jsonData.data.permissions;
                if($.inArray("showresellers",licensedefender.permissions) > -1) {
                    licensedefender.showResellerFilter();
                }


                isViewingAsAdmin = false;
                if($.inArray("isGroup0",licensedefender.permissions) > -1) {
                    //reseller add check for distributor as well
                    isViewingAsAdmin = false;
                } else if($.inArray("isGroup1",licensedefender.permissions) > -1) {
                    isViewingAsAdmin = true;
                }

                //enable reseller tab
                if ((isViewingAsAdmin) || (licensedefender.loggedinas!=""))
                {
                    ce.showSnapinHiddenTab("Resellers");
                }

                cm = licensedefender.grid.getColumnModel();
                //totallicenses usedlicenses remaininglicenses
                if (((!isViewingAsAdmin) && (licensedefender.searchkey=="")) ) {
                    //we are showing a reseller
                    document.getElementById('totallicenses').style.display = '';
                    document.getElementById('remaininglicenses').style.display = '';
                    $('#totallicenses_count').text(s.reader.jsonData.data.licensetotals.allotted);
                    $('#remaininglicenses_count').text(parseInt(s.reader.jsonData.data.licensetotals.allotted) - parseInt(s.reader.jsonData.data.licensetotals.used));
                    //hide reseller column
                    cm.setHidden(cm.getIndexById('colReseller'), true);
                } else {
                    //we are showing an admin
                    $('#totallicenses').hide();
                    $('#remaininglicenses').hide();
                    //show reseller column
                    cm.setHidden(cm.getIndexById('colReseller'), false);
                }
                $('#usedlicenses_count').text(s.reader.jsonData.data.licensetotals.used);
                licensedefender.toggleButtons();
            }
        }
    });

    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('deletelicenses').setDisabled(false);
        }else{
            Ext.getCmp('deletelicenses').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.renderUserLimit = function (value,p,record)
    {
        if (record.data.limit_users == null) {
            return "no limit";
        } else {
            return "<span style='color:red'>"+record.data.limit_users + "</span> user limit";
        }
    }

    licensedefender.renderType = function(value,p,record) {
        if(record.data.is_owned == 1)
        {
            return "Owned";
        } else {
            return "Leased";
        }
    }

    licensedefender.renderReseller = function(value,p,record) {
        if (record.data.reseller == null) {
            return "<span style='color:gray;'>Not applicable</span>";
        } else {
            return "<a style='cursor:pointer' qtip='Filter based on reseller: "+record.data.reseller+"' onclick='licensedefender.loadResellerLicenses(\""+record.data.reseller+"\");'>"+record.data.reseller+"</a>";
        }
    }

    licensedefender.countofrecords = 0;
    licensedefender.renderName = function(value,p,record) {
            licensedefender.countofrecords++;
            return "<a style='cursor:pointer' id='license_"+licensedefender.countofrecords+"' qtip='Edit license for domain: "+record.data.domain+"' onclick='licensedefender.editLicense(\""+record.data.domain+"\","+licensedefender.countofrecords+","+record.data.resellerid+","+record.data.is_owned+","+record.data.limit_users+");'>"+record.data.domain+"</a>";
    }

    licensedefender.expander = new Ext.ux.grid.RowExpander({
        enableCaching: false,
        lazyRender:true,
        listeners:{
           'expand': function(re,response,body,index){
               licensedefender.grid.disable();
               //get specifics about domain
               //last 5 queries
               //dir installed on and activated maybe
               Ext.Ajax.request({

                    url: 'index.php?fuse=home&action=DoSnapinPluginAction',
                    success: function(xhr){
                            licensedefender.grid.enable();
                            var json = ce.parseAjaxResponse(xhr);

                            var html = "<div class='licensedetails'>";

                            if (json.data.domain){
                                html += " <label>Expires</label>: "+json.data.domain[1];
                                if (json.data.domain[3]!=0) {
                                    html += " <label>Installed Version</label>: "+json.data.domain[2];
                                    html += " <label>Last Checked</label>: "+json.data.domain[4];
                                    html += " <br/><label>Installed In</label>: "+json.data.domain[0];
                                }
                            }
                            if (json.data.lastx) {
                                if (json.data.lastx.length>0) html += " <br/></br><div class='detailheader'>Last "+json.data.lastx.length+" License Checks</div>";
                                for (var x=0;x<json.data.lastx.length;x++){
                                    html+= "<br/> <label>Date</label>: "+json.data.lastx[x][1];
                                    html+= "<label>ip</label>: "+json.data.lastx[x][0];

                                    passedtext = "<span style='color:red'>Failed Check</span>";
                                    if (json.data.lastx[x][2] == 1) {
                                        passedtext = "<span>Verified</span>";
                                    }
                                    html+= "<label>Status</label>: "+passedtext;
                                }
                            }
                            html += "</div>";
                            body.innerHTML = html;

                            $('.licensedetails label').css('color','green');
                            $('.licensedetails label').css('font-weight','bold');
                            $('.licensedetails label').css('padding-left','15px');
                            $('.licensedetails').css('padding-left','21px');
                            $('.licensedetails').css('padding-bottom','10px');
                            $('.detailheader').css('padding-top','10px');
                            $('.detailheader').css('font-weight','bold');
                            $('.detailheader').css('padding-left','15px');
                            $('.detailheader').css('margin-bottom','-10px');

                    },
                    params: {
                        plugin: 'licensedefender',
                        pluginAction : 'getLicenseDetails',
                        domain: response.data.domain,
                        resellerid: response.data.resellerid,
                        loginas : licensedefender.loggedinas
                    }
                });

            }
        }
    });

    licensedefender.grid = new Ext.grid.GridPanel({
        store:licensedefender.gridstore,
        columns: [
        licensedefender.expander,
        licensedefender.sm,
        {
            header: lang("Domain"),
            sortable: true,
            dataIndex: 'domain',
            renderer: licensedefender.renderName
        },
        {
            header: lang("License Key"),
            hidden:true,
            sortable: false,
            dataIndex: 'licensekey'
        },
        {
            header: lang("Type"),
            width: 25,
            hidden: false,
            sortable: false,
            align:'center',
            dataIndex: 'is_owned',
            renderer: licensedefender.renderType
        },
        {
            header: lang("# Users"),
            width: 20,
            hidden: false,
            sortable: true,
            align:'center',
            dataIndex: 'limit_users',
            renderer: licensedefender.renderUserLimit
        },
        {
            id: 'colReseller',
            header: lang("Reseller"),
            width: 30,
            hidden: false,
            sortable: false,
            align:'center',
            dataIndex: 'reseller',
            renderer: licensedefender.renderReseller
        }
        ],
        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,
        plugins :licensedefender.expander,
        collapsible: false,
        buttonAlign:'left',
        iconCls: 'icon-grid',
        id:       'domains-grid',
        el:       'domains-grid',
        buttons:[
            {
                id:'deletelicenses',
                text: lang('Delete License'),
                disabled: true,
                onClick:  function(record){
                    if(!Ext.getCmp('deletelicenses').disabled) {
                        licensedefender.deleteProduct();
                    }
                }
            }
        ]
    });

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



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

    licensedefender.deleteProduct = function()
    {
        var rows = licensedefender.getSelectedRows();
        Ext.MessageBox.confirm('Confirm License Deletion:', "Are you sure you want to remove a license for domain: "+rows[0].data.domain, function(btn){
            if (btn == "yes") {
                for (var x=0;x< rows.length; x++) {
                    //ce.log(1,rows[x].data.resellerid);
                    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 : 'deleteDomains',
                            loginas : licensedefender.loggedinas,
                            resellerid: rows[x].data.resellerid,
                            domain: rows[x].data.domain
                        }
                    });
                }
            }
        }, this);
        
    }

    licensedefender.grid.render();


});