﻿/*
    ConnectionSettings
*/
Veeam.ConnectionSettings = function(config) {
    var data = (config||{}).initData||{ usessl:true, proxy: { mode: 'noproxy' }, port: 9392};
    
    var tf = {  
        allowBlank:false, 
        validationEvent: false,
        msgTarget: 'side',
        maxLength : 200,
        validator : function( value ) { return value.match(/^\s*$/)==null; }
    };

    this.cbCreds = new Ext.form.Checkbox({ boxLabel: 'Use these credentials:', checked : data.creds, handler:this.credsHandler, scope:this });
    this.tfServer = new Ext.form.TextField( Ext.apply({ width: Ext.isIE ? 346 :349 , value : data.servername }, tf ));
    this.tfDescr = new Ext.form.TextArea( Ext.apply({ width: Ext.isIE ? 346 :349 , value : data.description }, {maxLength : 2000, height:40} ));
    this.tfUsername = new Ext.form.TextField( Ext.apply({ fieldLabel:'User name', width: Ext.isIE ? 169 : 180, value : data.username, disabled:!data.creds }, tf ));
    this.tfPassword = new Ext.form.TextField( Ext.apply({ 
        fieldLabel:'Password', 
        inputType: 'password', 
        value : data.password, 
        disabled:!data.creds, 
        width: Ext.isIE ? 169 : 180,
        listeners: { 
            change: { fn: function(){ this.passwordChanged = true; }, scope:this } 
        }
        }, { allowBlank:true}, tf  ));
        
    this.tfPort = new Ext.form.NumberField({ hideLabel:true, minValue: 0, maxValue: 65535, value : data.port, width:50, allowBlank: false, validationEvent: false, msgTarget: 'side', allowDecimals: false, allowNegative: false  });
    this.cbUseSsl = new Ext.form.Checkbox({ boxLabel: 'Use SSL',  checked : data.usessl, hidden:true });

    this.pnVC = config.pnVC || new Ext.Panel ({ 
        border:false,
        width:368,
        html: '<table class="x-settings" style="table-layout:fixed;width:100%;border-collapse:collapse" cellspacing="4" cellpadding="0" ><tr style="width:1px; margin-top:-5px"><td style="width:70px"></td><td style="width:100px"></td><td style="width:110px"></td><td style="width:110px"></td></tr>' +
            '<tr><td colspan=4><label>DNS name or IP address of the Veeam Backup server:</label></td></tr>' + 
            '<tr><td colspan=4 class="x-form-field-wrap" ></td></tr>' +
            '<tr><td colspan=4><label>Server description:</label></td></tr>' + 
            '<tr><td colspan=4 class="x-form-field-wrap" style="padding-bottom:10" ></td></tr>' +
            '<tr><td rowspan="4" valign="middle"><img src="css/images/keys.png" alt="" /></td>' +
            '<td></td><td colspan="2" class="x-form-field-wrap"></td></tr>' +
            '<tr><td><label>User name:</label></td><td colspan="2" class="x-form-field-wrap"></td></tr>' +
            '<tr><td><label>Password:</label></td><td colspan="2" class="x-form-field-wrap"></td></tr>' +
            '<tr><td>Port:</td><td class="x-form-field-wrap"></td><td class="x-form-field-wrap"></td></tr></table>'
    });
    

    // create proxy settings fieldset
    var rb = { hideLabel: true, name:'connection-settings-proxy-radio-group', listeners: { check: this.proxyCheckedHandler.createDelegate(this) }};
    this.rbNoProxy = new Ext.form.Radio( Ext.apply({ boxLabel: 'Do not use proxy' , checked: (data.proxy||{}).mode=='noproxy' }, rb));
    this.rbAutoProxy = new Ext.form.Radio(Ext.apply({ boxLabel: 'Automatically detect proxy settings', checked: (data.proxy||{}).mode=='auto'}, rb));
    
    var isManual = data && data.proxy && data.proxy.mode=='manual';
    this.rbManualProxy = new Ext.form.Radio(Ext.apply({ boxLabel: 'Using the following proxy settings', checked: isManual }, rb));
    

    this.tfProxyServer = new Ext.form.TextField( Ext.apply({ width:100, fieldLabel: 'Server name', value : (data.proxy||{}).servername, disabled: !isManual}, tf ));
    this.nfProxyPort = new Ext.form.NumberField({ 
        minValue: 0, maxValue: 65535, width:50,
        allowDecimals: false,
        allowBlank: false,
        allowNegative: false, 
        value : (data.proxy||{}).port,
        disabled: !isManual
    });
    this.tfProxyUsername = new Ext.form.TextField( Ext.apply({ width:100, fieldLabel: 'User name', value : (data.proxy||{}).username, disabled: !isManual },tf ));
    this.tfProxyPassword = new Ext.form.TextField( Ext.apply({ width:100, fieldLabel: 'Password', inputType: 'password', value : (data.proxy||{}).password, disabled: !isManual }, tf ));

    this.fsProxySettings = new Ext.form.FieldSet ({
        autoHeight:true,
        hidden:true,
        html:'<table><tr><td class="x-form-field-wrap" colspan="4"></td></tr>' + 
            '<tr><td style="width:80px"><label>Server name:</label></td><td class="x-form-field-wrap" style="width:120"></td><td style="width:80px"><label>Port:</label></td><td class="x-form-field-wrap" style="width:120"></td></tr>' + 
            '<tr><td style="width:80px"><label>User name:</label></td><td style="width:120" class="x-form-field-wrap" colspan="3"></td></tr>' + 
            '<tr><td style="width:80px"><label>Password:</label></td><td style="width:120" class="x-form-field-wrap" colspan="3"></td></tr></table>'
    });
    
    // buttons 
    this.btnOk = new Ext.Button({ text : 'OK', handler: this.commitHandler, scope:this });
    this.btnCancel = new Ext.Button({ text : 'Cancel', handler: this.closeHandler, scope:this });
    this.btnAdv = new Ext.Button({ text : 'Advanced&gt;&gt;', handler: this.advHandler, scope:this });
    this.isAdvanced = false;



    var wrapperPn =  new Ext.Panel({
        items:   [ this.pnVC, this.fsProxySettings ],
        id: 'backup-server-settings-panel',
        bodyCssClass: 'backup-server-settings-panel-body'
    });

    // configure dialog itself
    config = Ext.applyIf( config||{}, {
        width: 420,
        autoHeight:true,
        border: false,
        style:'padding:5px',
        bodyStyle:'padding-left:5px; padding-right:5px',
        title: 'Backup Server Settings',
        modal: true,
        shadow:true,
        defaultButton: this.btnOk,
        items: [ wrapperPn ],
        buttons: [ this.btnOk, this.btnCancel/*, this.btnAdv*/ ],
        //listeners: { show:{fn:this.showHandler, scope:this} },
        keys: [{key:13, fn:this.enterHandler, scope:this}]
    });
    
    this.addEvents('commit');
    Veeam.ConnectionSettings.superclass.constructor.apply(this, [config]);
};

 
Ext.extend(Veeam.ConnectionSettings, Veeam.Window, {

    initComponent : function() {
        Veeam.ConnectionSettings.superclass.initComponent.call(this);
    },
    
    destroy: function() {
        this.tfServer.destroy();
        this.tfDescr.destroy();
        this.cbCreds.destroy();
        this.tfUsername.destroy();
        this.tfPassword.destroy();
        this.tfPort.destroy();

      
        this.rbNoProxy.destroy();
        this.rbAutoProxy.destroy();
        this.rbManualProxy.destroy();
        this.tfProxyServer.destroy();
        this.nfProxyPort.destroy();
        this.tfProxyUsername.destroy();
        this.tfProxyPassword.destroy();
  
        Veeam.ConnectionSettings.superclass.destroy.apply( this, arguments );
    },

    render: function() {
        Veeam.ConnectionSettings.superclass.render.apply( this, arguments );
        var tda = this.pnVC.body.select("td.x-form-field-wrap");
        this.tfServer.render(tda.item(0).dom);
        this.tfDescr.render(tda.item(1).dom);
        this.cbCreds.render(tda.item(2).dom);            
        this.tfUsername.render(tda.item(3).dom);
        this.tfPassword.render(tda.item(4).dom);
        this.tfPort.render(tda.item(5).dom);
        //this.cbUseSsl.render(tda.item(5));
        
        var tda = this.fsProxySettings.body.select("td.x-form-field-wrap");
        this.rbNoProxy.render(tda.item(0).dom);
        this.rbAutoProxy.render(tda.item(0).dom);
        this.rbManualProxy.render(tda.item(0).dom);
        this.tfProxyServer.render(tda.item(1).dom);
        this.nfProxyPort.render(tda.item(2).dom);
        this.tfProxyUsername.render(tda.item(3).dom);
        this.tfProxyPassword.render(tda.item(4).dom);
    },
    
    //setFocus : function ()   { this.tfServer.focus.defer(500, this.tfServer);  },
    closeHandler : function() { this.close(); },
    advHandler : function() {
        this.isAdvanced = !this.isAdvanced;            
        this.btnAdv.setText("Advanced&nbsp;" + (this.isAdvanced ? "&lt;&lt;" : "&gt;&gt;") );
        this.fsProxySettings[ this.isAdvanced ? "show" : "hide"]();
        this.doLayout();
    },
    
    credsHandler : function() {
        var has = this.cbCreds.getValue();
        var m = has ? 'enable' : 'disable';
        this.tfUsername[m]();
        this.tfPassword[m]();
        if ( has && !this.tfPassword.getValue() )
            this.passwordChanged = true;
    },
    
    enterHandler:function( key, ev ) {
        if ( ev.target.type=="password")
            this.passwordChanged = true;
        this.commitHandler.defer(100, this);
        ev.stopPropagation();
        ev.preventDefault();
        return false;
    },
    
    focus : function() {
        this.tfServer.focus.defer(100, this.tfServer );
    },
    
    commitHandler: function() {
        if (!this.validate()) return;
        var data = this.captureData();
        this.btnOk.disable();
        this.btnOk.setIconClass('x-request-loading');
        
        if ( this.fireEvent( 'commit', data) !== false )
            this.close();
    },
    showLoading: function(){
        this.btnOk.disable();
        this.btnOk.setIconClass('x-request-loading');
    },
    hideLoading: function(){
        this.btnOk.enable();
        this.btnOk.setIconClass('');
    },
    proxyCheckedHandler : function() {
        var method = this.rbManualProxy.getValue() ? "enable" : "disable";
        this.nfProxyPort[method]();
        this.tfProxyServer[method]();
        this.tfProxyUsername[method]();
        this.tfProxyPassword[method]();
    },
    
    validate : function() {
        
        var v = true;
        v = this.tfServer.validate() && v;
        v = this.tfPort.validate() && v;
        if ( this.cbCreds.getValue() ) {
            v = this.tfUsername.validate() && v;
            v = this.tfPassword.validate() && v;
        }
        if ( this.rbManualProxy.getValue() ) {
            v = this.nfProxyPort.validate() && v;
            v = this.tfProxyServer.validate() && v;
            v = this.tfProxyUsername.validate() && v;
            v = this.tfProxyPassword.validate() && v;
        }

        v = this.tfDescr.validate() && v;
        
        return v;
    },
    
    captureData : function() {
        this.btnOk.focus();

        var data = { 
            servername: this.tfServer.getValue(),
            creds: this.cbCreds.getValue(),
            username: this.tfUsername.getValue(),
            port: this.tfPort.getValue(),
            usessl: this.cbUseSsl.getValue(),
            description: this.tfDescr.getValue()
        };
        
        if ( this.passwordChanged )
            data = Ext.apply(data, {password: this.tfPassword.getValue() } ); 
            
      
        data.proxy = { 
            port: (this.nfProxyPort.getRawValue()=='' ? 0 : this.nfProxyPort.getValue()),
            mode : this.rbNoProxy.getValue() ? 'noproxy' : (this.rbAutoProxy.getValue() ? 'auto' : 'manual'),
            servername : this.tfProxyServer.getValue(),
            username : this.tfProxyUsername.getValue(),
            password : this.tfProxyPassword.getValue()
       }
      
       return data;
    }
});

Ext.reg('vm.ui.connectionsettings', Veeam.ConnectionSettings );

/*
    SchedulerSettings
*/
Veeam.SchedulerSettings = function(config) {

    this.rdManually = new Ext.form.Radio({ boxLabel:'Manually', name: 'scheduler-settings-2-type', 
        handler: this.modeHandler.createDelegate(this), 
        checked: config.data.type=='manually', 
        width:140 });
    this.rdPeriodically = new Ext.form.Radio({ boxLabel:'Periodically every:', name: 'scheduler-settings-2-type', 
        handler: this.modeHandler.createDelegate(this), 
        checked: config.data.type=='periodically', 
        width:140 });

    this.nfPeriod = new Ext.form.NumberField({ value:config.data.period, width:80, minValue:1, allowDecimals:false,  allowNegative:false, allowBlank:false, maxLength:6 });
    this.cbPeriodType = new Ext.form.ComboBox({ 
        store : new Ext.data.SimpleStore({ fields:['value', 'name'],   data:[ ['hours', 'hour(s)'], ['minutes', 'minute(s)'] ] }),
        valueField: 'value', displayField: 'name',                        
        value:config.data.periodtype,
        typeAhead: true,
        triggerAction: 'all',
        shadow:false,
        stateful:false,
        mode: 'local'
    });

    // buttons 
    this.btnOk = new Ext.Button({ text : 'OK', handler: this.commitHandler.createDelegate(this) });
    this.btnCancel = new Ext.Button({ text : 'Cancel', handler: this.closeHandler.createDelegate(this) });

    // configure dialog itself
    config = Ext.applyIf( config, {
        autoHeight:true,
        width:360,
        hideLabels:true,
        border: false,
        title: 'Data Collection Settings',
        buttons: [ this.btnOk, this.btnCancel ],
        shadow:false,
        modal:true,
        layout:'table',
        layoutConfig : { columns: 3 },
        cls: 'scheduler-settings-wnd',
        stateful:false,
        bodyStyle:'padding:10px',
        items: [ 
            {text:'Collect statistics from Veeam Backup servers:', border:false, colspan:3, xtype:'label'},
            this.rdManually, { colspan:2, border: false, hidden:true }, 
            this.rdPeriodically, this.nfPeriod, this.cbPeriodType
		], 
        keys: [{key:13, fn:this.commitHandler, scope:this}]
    });
    
    this.addEvents('commit');
    Veeam.SchedulerSettings.superclass.constructor.apply(this, [config]);
};
 
// extend Wisard behavior 
Ext.extend(Veeam.SchedulerSettings, Veeam.Window, {
    
    modeHandler : function( rb, checked )
    {
        if ( this.rdManually.getValue() )  {
            this.cbPeriodType.disable();
            this.nfPeriod.disable();
        } else {
            this.cbPeriodType.enable();
            this.nfPeriod.enable();
        }
    },
    
    closeHandler : function() {  this.close();  },
    
    commitHandler : function() {
        if (!this.validate()) return;
            
        var data = {
            period:this.nfPeriod.getValue(),
            periodtype:this.cbPeriodType.getValue()
        };
        if (this.rdManually.getValue()) data.type = 'manually' ;
        if (this.rdPeriodically.getValue()) data.type = 'periodically';
        
        this.fireEvent('commit', data );
        this.close();
    },
    
    show: function() {
        Veeam.SchedulerSettings.superclass.show.apply( this, arguments );
        this.cbPeriodType.setWidth(80);
        this.modeHandler();
    },
    
    validate: function() {
		var result = true;
		
		if (!this.nfPeriod.validate())
			result = false;
			
		return result;
    }
});

/*
    BackupServersPanel
*/
Veeam.BackupServersPanel = function(config) {
    Veeam.BackupServersPanel.superclass.constructor.apply(this, [config]);
};

Ext.extend(Veeam.BackupServersPanel, Veeam.AutoGridPanel, {
    addHandler: function () {
        this.wndConn = new Veeam.ConnectionSettings({
            listeners: { commit: this.addBackupServer.createDelegate(this) }
        });
        this.wndConn.show();
    },

    editHandler: function () {
        if (!this.selectedItem) return;

        var cb = function (data) {
            this.wndConn = new Veeam.ConnectionSettings({
                initData: data,
                listeners: { commit: this.editBackupServer.createDelegate(this) }
            });
            this.wndConn.show();
        };

        ext_channel(CommonDataHandler.rpc.getBackupServerInfo(
            this.selectedItem, cb.createDelegate(this)
        ));

    },

    showMsg: function (result) {
        if (!this.wndConn.requestData)
            this.wndConn.requestData = this.wndConn.captureData();

        var cb = function (act) {
            if (act == 'ok') {
                Ext.apply(this.wndConn.requestData, { force: true });
                this.showWait();
                this.wndConn.initialConfig.listeners.commit(this.wndConn.requestData);

            } else {
                this.wndConn.close();
                delete this.wndConn.requestData;
                delete this.wndConn;
            }
        };

        var cb2 = function (act) {
            if (act == 'ok') {
                Ext.apply(this.wndConn.requestData, { overrideOldEM: true });
                this.showWait();
                this.wndConn.initialConfig.listeners.commit(this.wndConn.requestData);
            } else {
                this.wndConn.close();
                delete this.wndConn.requestData;
                delete this.wndConn;
            }
        };


        if (!result.prompt && !result.prompt2) {
            Ext.MessageBox.show({ title: 'Status',
                msg: result.message || 'Success.', width: 400, buttons: Ext.MessageBox.OK,
                icon: Ext.MessageBox[result.success ? "INFO" : "ERROR"]
            });

            this.wndConn.close();
            delete this.wndConn.requestData;
            delete this.wndConn;

        } else if (result.prompt) {
            Ext.MessageBox.show({ title: 'Status', msg: result.prompt,
                buttons: Ext.MessageBox.OKCANCEL,
                fn: cb.createDelegate(this),
                icon: Ext.MessageBox.QUESTION
            });
        } else if (result.prompt2) {
            Ext.MessageBox.show({ title: 'Status', msg: result.prompt2,
                buttons: Ext.MessageBox.OKCANCEL,
                fn: cb2.createDelegate(this),
                icon: Ext.MessageBox.QUESTION
            });
        }

    },

    removeHandler: function () {
        if (!this.selectedItem) return;

        var fn = function (btn) {
            if (btn == "yes") {
                this.showWait();
                CommonDataHandler.rpc.removeBackupServer(this.selectedItem,
                    this.updatedHandler.createDelegate(this, [], true)
                ).call(ext_channel);
            }
        };

        var dialog = Ext.MessageBox.confirm(
            'Backup Servers',
            "Backup Server will be removed. Are you sure?",
            fn.createDelegate(this)
        ).getDialog();
        dialog.defaultButton = 2;
        dialog.focus();
    },

    addBackupServer: function (data) {
        if (!data.force) this.showWait();
        ext_channel(CommonDataHandler.rpc.addBackupServer(data, this.updatedHandler.createDelegate(this)));
        return false;
    },

    editBackupServer: function (data) {
        ext_channel(CommonDataHandler.rpc.editBackupServer(this.selectedItem, data, this.updatedHandler.createDelegate(this)));
        return false;
    },

    updatedHandler: function (result) {
        if (result.success === true) {
            if (this.wndConn) { this.wndConn.close(); }
            try { Ext.MessageBox.hide(); } catch (e) { }
        } if (!result.success) {
            this.showMsg(result);
        }

        Ext.apply(this.store.baseParams, { clearCache: true });
        this.store.load();
    },

    onCommitSch: function (data) {
        this.selectedVc.schedule = data;
        CommonDataHandler.rpc.updateVc(
            this.selectedVc, this.dataUpdated.createDelegate(this)).call(ext_channel);
    },

    scheduleHandler: function (x) {
        var commitfn = function (data) {
            ext_channel(CommonDataHandler.rpc.updateScheduleSettings(data,
                this.updatedHandler.createDelegate(this)));
        };

        var fn = function (r) {
            var f = new Veeam.SchedulerSettings({ data: r, listeners: { commit: commitfn.createDelegate(this)} });
            f.show();
        };
        ext_channel(CommonDataHandler.rpc.getScheduleSettings(fn.createDelegate(this)));
    },

    activate: function (params) {
        Veeam.BackupServersPanel.superclass.activate.apply(this, [params]);
    },

    deactivate: function (params) {
        Veeam.BackupServersPanel.superclass.deactivate.apply(this, [params]);
    }

});

Ext.reg('vm.ui.backupservers', Veeam.BackupServersPanel );


/*
    AccountWindow
*/
Veeam.AccountWindow = function (config) {
    var editMode = typeof (config.data.account.name) != 'undefined';

    this.storeAccounts = new Ext.data.JsonStore({
        root: 'items', totalProperty: 'totalCount',
        fields: ['accountguid', 'name', 'isgroup'],
        data: config.data.accounts
    });

    this.storeRoles = new Ext.data.JsonStore({
        root: 'items', totalProperty: 'totalCount',
        fields: ['roleguid', 'name'],
        data: config.data.roles
    });

    var cb = {
        allowBlank: false,
        msgTarget: 'side',
        validationEvent: false,
        mode: 'local',
        typeAhead: true,
        triggerAction: 'all',
        shadow: true
    };

    var filtUsers = function () {
        this.storeAccounts.filterBy((
            function (r) {
                return r.data.isgroup === this.cbType.getValue();
            }).createDelegate(this)
        );
    };

    this.cbType = new Ext.form.ComboBox(Ext.applyIf({
        fieldLabel: 'Account type',
        store: new Ext.data.SimpleStore({ fields: ['value', 'name'], data: [[false, 'User'], [true, 'Group']] }),
        disabled: editMode,
        editable: false,
        //hideTrigger: editMode,
        valueField: 'value', displayField: 'name',
        value: config.data.account.isgroup,
        width: 80
    }, cb));


    if (editMode)
        this.cbType.onTriggerClick = Ext.emptyFn;


    this.cbRoles = new Ext.form.ComboBox(Ext.applyIf({
        fieldLabel: 'Role',
        store: this.storeRoles,
        valueField: 'roleguid', displayField: 'name',
        value: config.data.role.roleguid,
        anchor: '95%',
        editable: false
    }, cb));

    this.cbAccounts = new Ext.form.TextField(Ext.applyIf({
        fieldLabel: 'Account',
        disabled: editMode,
        anchor: '95%',
        listeners: { expand: filtUsers.createDelegate(this) }
    }, cb));



    this.permissions = {
        'check1': new Ext.form.Checkbox({
            fieldLabel: 'Allow restore of',
            boxLabel: 'Entire virtual machines',
            name: 'vm_restore'
        }),
        'check2': new Ext.form.Checkbox({
            boxLabel: 'Guest files',
            name: 'file_restore',
            listeners: {
                'check' : this._toggleFlrSettings,
                'scope' : this
            }
        }),
        validate: function () {
            var restoreOpRole = !!(this.cbRoles.getValue() == '00000000-0000-0000-0000-000000000000'),
                anyChecked = !!(this.permissions.check1.checked || this.permissions.check2.checked);

            if (restoreOpRole && !anyChecked) {
                Veeam.Msg.warning({ msg: 'Select at least one restore permission.' });
                return false;
            }
            return true;
        }
    }


    this.restoreScope = {
        'radio1': new Ext.form.Radio({
            fieldLabel: 'Restore scope',
            boxLabel: 'All virtual machines',
            name: 'restore_scope_on'
        }),
        'radio2': new Ext.form.Radio({
            boxLabel: 'Selected virtual machines only',
            width: 185,
            name: 'restore_scope_on'
        }),
        'button': new Ext.Button({
            //iconCls: 'x-button-gear',
            text: 'Choose',
            handler: this.configureScopeHandler,
            scope: this
        }),

        'toggle': function (radio, checked) {
            this.button[checked == true ? 'enable' : 'disable']();
        }
    };

    this.restoreScope.radio2.on('check', this.restoreScope.toggle, this.restoreScope);

    var rCfg = {
        anchor: '95%',
        layout: 'form',
        xtype: 'container',
        id: 'restore-scope-form',
        cls: 'account-form',
        items: [
            this.restoreScope.radio1,
            {
                layout: 'hbox',
                xtype: 'container',
                cls:'x-form-item x-chb-wrap' ,  
                layoutConfig: { pack: 'start', align: 'top' },
                items: [
                  //  { xtype: 'displayfield', width: 105 },
                    this.restoreScope.radio2,
                    { xtype: 'displayfield', flex: 1 },
                    { xtype: 'container', items : this.restoreScope.button }
                ]
            }
        ]
    };





    /* Flr settings */
     this.cbDisableDownloads = new Ext.form.Checkbox({
        boxLabel : 'Allow in-place file restores only',
        id: 'cb-disable-downloads'
    });

    this.cbRestrictedExt = new Ext.form.Checkbox({

        boxLabel: 'Allow restore of files with these extensions only:',
        id: 'cb-restricted-ext',
        listeners: {
            'check' : function(f, checked){
                this.tfRestrictedExt.setDisabled( !checked );
            },
            scope: this
        }
    });

    this.tfRestrictedExt = new Ext.form.TextField({
        anchor: '95%',
        fieldLabel: false,
        allowBlank: true,
        hideLabel: true,
        id:'tf-restricted-ext',
        validator: function(value) {
            if (/[^A-z0-9,]+?/.test(value) || !/\S/.test(value))
                return false;
            return true;
        },
        invalidText: 'Invalid entry. Specify one or more file extensions separated by commas.'
    });

    var fileRestoreSettingsCnf = {
        id: 'file-restore-settings',
        xtype: 'container',
        autoHeight:true,
        layout:'form',
        baseCls: 'config-box box-panel',
        hideLabels: true,
        items: [
            this.cbDisableDownloads,
//            {   autoEl: 'div',
//                xtype: 'box',
//                id: 'disable-downloads-help',
//                html: ''
//            },
            this.cbRestrictedExt,
            this.tfRestrictedExt
        ]

    };

    var permCfg = {
           layout: 'form',
           xtype: 'container',
           id: 'permissions-form',
           cls: 'account-form',
           items: [
               this.permissions.check1,
               this.permissions.check2,
               fileRestoreSettingsCnf
           ]
       }


    // buttons 
    this.btnOk = new Ext.Button({ text: 'OK', handler: this.commitHandler, scope: this });
    this.btnCancel = new Ext.Button({ text: 'Cancel', handler: this.close, scope: this });

    this.scopeObjectCtrl = new Veeam.SecurityScope.ObjectsSelectorCtrl({ roleAccountInfo: config.data });
    var scopeObjects = [].concat(config.data.scopeObjects ? config.data.scopeObjects.items : []);
    this.scopeObjectCtrl.loadObjects(scopeObjects);
    
    config = Ext.apply({
        title: 'Account',
        cls: 'veeam-account-window',
        autoHeight: true,
        width: 450,
        resizable: false,
        modal: true,
        layout: 'form',
        bodyStyle: 'padding:10 10 10 10',
        items: [this.cbType, this.cbAccounts, this.cbRoles, rCfg, permCfg ],
        buttons: [this.btnOk, this.btnCancel],
        keys: [{ key: 13, fn: this.commitHandler, scope: this}]
    }, config || {});

    this.addEvents('commit');
    Veeam.AccountWindow.superclass.constructor.apply(this, [config]);
};


Ext.extend(Veeam.AccountWindow, Veeam.Window, {
    ADMINISTRATOR_GUID: '5f37a46b-9ce2-40f4-8a62-b45b079257fc',
    initComponent: function () {
        this.cbRoles.on('select', this._toggleOptions, this);

        Veeam.AccountWindow.superclass.initComponent.apply(this, arguments);
    },


    render: function () {
        Veeam.AccountWindow.superclass.render.apply(this, arguments);
        var data = this.initialConfig.data,
            scopeEnabled = !!data.scopeEnabled;

        this.cbAccounts.setRawValue(data.account.name);
        if (App.isEnterprisePlusLicense() == false)
        {
            this.restoreScope.radio1.setValue(true);
            this.restoreScope.radio2.disable();
            this.restoreScope.button.disable();

        } else {
            this.restoreScope.radio1.setValue(!scopeEnabled);
            this.restoreScope.radio2.setValue(scopeEnabled);
            this.restoreScope.toggle.call(this.restoreScope, this.restoreScope.radio2, scopeEnabled);
        }


        if (data && data.role.roleguid) {
            var ind = this.storeRoles.findExact('roleguid', data.role.roleguid),
                r = this.storeRoles.getAt(ind);
            this._toggleOptions.apply(this, [this.cbRoles, r, ind]);
        } else {
            this._toggleOptions.apply(this, [this.cbRoles, this.storeRoles.getAt(0), 0]);
        }

        this.permissions.check1.setValue(!!data.canRestoreVms);
        this.permissions.check2.setValue(!!data.canRestoreFiles);
        this._toggleFlrSettings(this.permissions.check2, !!data.canRestoreFiles);

        var flrData = data.flrSettings || {};
        this.cbDisableDownloads.setValue(flrData.noDownloads);
        this.cbRestrictedExt.setValue(flrData.flrRestrictedByExt);
        this.tfRestrictedExt.setValue(flrData.flrExtRestrictions);
        if (!data.canRestoreFiles || flrData.flrRestrictedByExt == false)
            this.tfRestrictedExt.disable();


        Ext.QuickTips.register({
            target: this.cbDisableDownloads.wrap ? this.cbDisableDownloads.wrap : this.cbDisableDownloads.getEl(),
            text: 'Disables ability to download guest files locally'
        });
    },

    captureData: function () {
        if (!this.spec)
            this._getUpdateSpec();
        var flrSettings = {
                noDownloads: this.cbDisableDownloads.getValue(),
                flrRestrictedByExt: this.cbRestrictedExt.getValue(),
                flrExtRestrictions: this.tfRestrictedExt.getValue()
        };
        return {
            roleAccount: {
                roleaccountguid: this.initialConfig.data.roleaccountguid,
                accountguid: this.cbAccounts.getValue(),
                accountname: this.cbAccounts.getRawValue(),
                roleguid: this.cbRoles.getValue(),
                isgroup: this.cbType.getValue(),
                canRestoreVms: this.permissions.check1.getValue(),
                canRestoreFiles: this.permissions.check2.getValue(),
                flrSettings: flrSettings
            },
            scopeUpdateSpec: {
                objects: this.spec.getObjects(),
                securityScopeEnabled: this.spec.getEnabled()
            }

        };
    },

    validate: function () {
        var spec = this._getUpdateSpec(),
            v = this.cbAccounts.validate();

        v = this.cbRoles.validate() && v;
        if (this.cbRoles.getValue() != this.ADMINISTRATOR_GUID) {
            if (spec.getEnabled() == true)
                v = this.scopeObjectCtrl.validate() && v;
            if (this.cbRestrictedExt.getValue())
                v = this.tfRestrictedExt.validate() && v;
        }
        return this.permissions.validate.call(this) && v;
    },

    commitHandler: function () {
        if (!this.validate()) return;
        this.showLoading();
        if (this.fireEvent('commit') === true)
            this.close();
    },

    showLoading: function(){
        this.btnOk.disable();
        this.btnOk.setIconClass( 'x-request-loading');
    },
    
    hideLoading: function(){
        if (this.btnOk && this.btnOk.el) {
            this.btnOk.enable();
            this.btnOk.setIconClass('');
        }
    },

    configureScopeHandler: function () {
        if (this.restoreScope.button.disabled)
            return;

        if (!this.scopeSettingsWin) {

            this.scopeSettingsWin = new Ext.Window({
                width: 510,
                height: 370,
                resizable: false,
                title: 'Manage scope objects',
                items: this.scopeObjectCtrl,
                layout: 'fit',
                closeAction: 'hide',
                buttons: [
                {

                    text: 'OK', handler: this.collectScopeObjects, scope: this, itemId: 'ok-button'
                },
                {
                    text: 'Cancel', handler: this.collectScopeObjects, scope: this, itemId: 'cancel-button'
                }]
            });

        }

        this.scopeSettingsWin.show();
    },

    destroy: function () {
        Ext.QuickTips.unregister( this.cbDisableDownloads.getEl() );
        if (this.scopeObjectCtrl) {
            this.scopeObjectCtrl.destroy();
            this.scopeObjectCtrl = null;
        }

        if (this.scopeSettingsWin) {
            this.scopeSettingsWin.destroy();
            this.scopeSettingsWin = null;
        }

        if (this.btnOk) {
            this.btnOk.destroy();
            this.btnOk = null;
        }


        Veeam.AccountWindow.superclass.destroy.apply(this, arguments);

    },

    _getUpdateSpec: function () {

        var objs = this.scopeObjectCtrl.getData();
        if (App.isEnterprisePlusLicense() == true){
            this.spec = Veeam.SecurityScope.UpdateSpec.create(this.restoreScope.radio2.getValue(), objs);
        } else {
            this.spec = Veeam.SecurityScope.UpdateSpec.create(false, []);
        }
        return this.spec;
    },
    collectScopeObjects: function (b, e) {
        var ok_btn = b.itemId == 'ok-button' ? true : false;


        if (!ok_btn)
            this.scopeObjectCtrl.discardChanges(); // TODO:make this work
        else
            if (!this.scopeObjectCtrl.validate())
                return;


        this._getUpdateSpec();

        if (this.scopeSettingsWin)
            this.scopeSettingsWin.hide();

    },

    _toggleOptions: function (combo, rec, index) {

        var guid = rec.get('roleguid'),
            permForm = Ext.get('permissions-form'),
            restScopeForm = Ext.get('restore-scope-form');

        if (guid == this.ADMINISTRATOR_GUID) {
            permForm.addClass('hidden');
            restScopeForm.addClass('hidden');

        } else {
            permForm.removeClass('hidden');
            restScopeForm.removeClass('hidden');
        }

        this.syncSize();
    },

    _toggleFlrSettings: function(f, checked){
        this.cbDisableDownloads[ checked ? 'enable' : 'disable']();
        this.cbRestrictedExt[checked ? 'enable' : 'disable']();
        this.tfRestrictedExt[checked && this.cbRestrictedExt.checked ? 'enable' : 'disable']();
       // Ext.fly('disable-downloads-help')[checked ? 'removeClass' : 'addClass']('x-item-disabled');

    }




});

Ext.reg('vm.ui.accountwindow', Veeam.AccountWindow );



/*
    AccountsPanel
*/
Veeam.AccountsPanel = function (config) {
    
    Veeam.AccountsPanel.superclass.constructor.apply(this, [config]);
};



Ext.extend(Veeam.AccountsPanel, Veeam.AutoGridPanel, {
    initComponent: function () {

        Veeam.AccountsPanel.superclass.initComponent.call(this);

        var gridpn = this,
            toolbar = this.gridToolBar,
            tasksCfg = this.initialConfig.serverTasks;


        var taskButton = new Veeam.TaskButton({
            handler: this.rebuildScopeHandler,
            scope: gridpn,
            disabled: false,
            requireRow: false,
            id: 'task-btn-rebuild',
            xtype: 'menuitem',
            text: 'Rebuild roles',
            xtype: 'vm.ui.taskbutton',
            iconCls: 'x-icon-tasks icon-tasks-rebuild-roles'
        });



        toolbar.insertButton(6, taskButton);
        toolbar.doLayout();
        if (App.isEnterprisePlusLicense() == false)
            taskButton.hide();
    },

    addHandler: function () {
        var fn = function (data) {
            this.wndAccount = new Veeam.AccountWindow({
                data: data,
                listeners: { commit: this.addAccount.createDelegate(this) }
            });
            this.wndAccount.show();
        };
        ext_channel(CommonDataHandler.rpc.getAccount(null, fn.createDelegate(this)));
    },

    editHandler: function () {
        if (!this.selectedItem) return;

        var fn = function (data) {
            this.wndAccount = new Veeam.AccountWindow({
                data: data,
                listeners: { commit: this.editAccount.createDelegate(this) }
            });
            this.wndAccount.show();
        };
        ext_channel(CommonDataHandler.rpc.getAccount(this.selectedItem, fn.createDelegate(this)));
    },

    removeHandler: function () {
        if (!this.selectedItem) return;

        var fn = function (btn) {
            if (btn == "yes") {
                this.showWait();
                CommonDataHandler.rpc.removeAccount(this.selectedItem,
                    this.updatedHandler.createDelegate(this, [], true)
                ).call(ext_channel);
            }
        };

        var dialog = Ext.MessageBox.confirm(
            'Account',
            "Account will be removed. Are you sure?",
            fn.createDelegate(this)
        ).getDialog();
        dialog.defaultButton = 2;
        dialog.focus();
    },

    addAccount: function () {
        var data = this.wndAccount.captureData();
        ext_channel(CommonDataHandler.rpc.addAccount(
            data.roleAccount, data.scopeUpdateSpec, this.updatedHandler.createDelegate(this)));
        return false;
    },

    editAccount: function (data) {
        var data = this.wndAccount.captureData();
        ext_channel(CommonDataHandler.rpc.editAccount(
            data.roleAccount, data.scopeUpdateSpec, this.updatedHandler.createDelegate(this)));
        return false;
    },

    updatedHandler: function (result) {
        try { Ext.MessageBox.hide() } catch (e) { };
        this.wndAccount.hideLoading();
        if (result.success && this.wndAccount)
            this.wndAccount.close();
        if (!result.success) {
            this.showMsg(result);
        }

        Ext.apply(this.store.baseParams, { clearCache: true });
        this.store.load();
    },

    activate: function (params) {

        Veeam.AccountsPanel.superclass.activate.apply(this, [params]);
    },

    deactivate: function (params) {
        Veeam.AccountsPanel.superclass.deactivate.apply(this, [params]);
    },

    rebuildScopeHandler: function (caller, e, confirm) {
        if (typeof confirm == "undefined") {

            return Ext.MessageBox.confirm("", "Rebuild scope for all users?", function (btn) {
                if (btn == 'yes') {
                    this.rebuildScopeHandler(caller, e, true);
                }

            }, this)
        }

        if (confirm !== true)
            return;

        var callback = function (result) {
            if (result.success === false)
                return Veeam.Msg.error({ msg: result.message });
            else
                return Veeam.Msg.success({ msg: result.message });
        }

        // TODO
        CommonDataHandler.rpc["scope.rebuildAll"](callback).call(ext_channel);
    }
});

Ext.reg('vm.ui.accountspanel', Veeam.AccountsPanel );


/*
    Search Servers panel
*/
Veeam.SearchServersPanel = function(config) {
    Veeam.SearchServersPanel.superclass.constructor.apply(this, [config]);
};
 
Ext.extend(Veeam.SearchServersPanel, Veeam.AutoGridPanel, {
    addHandler : function() {
        this.wndConn = new Veeam.SearchConnectionSettings({ 
            listeners: { commit: this.addSearchServer.createDelegate(this) }
        });

        this.wndConn.show();
        this.wndConn.toFront();
    },
    
    editHandler : function() {
        if ( !this.selectedItem )  return;
        
        // get selected data from grid store
        var i = this.store.findBy( (function(r) { 
                return this.selectedItem.typeId == r.get("objectId").typeId; }
        ), this );
        
        var status;
        if (i >= 0){
            status = this.store.getAt(i).json["cfg_search_srv_state"].value;
        }   
        
        if (status == 'Removing'){
            return this.removeHandler.apply(this, [status]);
        
        }
        
        
        var cb = function( data ) {        
            this.wndConn = new Veeam.SearchConnectionSettings({ 
                initData : data,
                listeners: { commit: this.editSearchServer.createDelegate(this) }
            });
            this.wndConn.show();
            this.wndConn.toFront();
        };
        
        ext_channel(CommonDataHandler.rpc.getSearchServerInfo( 
            this.selectedItem, cb.createDelegate(this)
        ));
        
    },

    showMsg : function( result ) {
        var cb = function( act ) {
            if ( act=='yes') {
                this.wndConn.initialConfig.listeners.commit( Ext.apply( 
                    { force:true }, this.wndConn.captureData()
                ));
                
                this.wndConn.close();
                delete this.wndConn;
            }
            if ( act=='cancel') {
                this.wndConn.close();
                delete this.wndConn;
            }

        };


        if ( !result.prompt ) {
            Ext.MessageBox.show({
                title: 'Status',
                msg: result.message||'Success.', width:400, buttons: Ext.MessageBox.OK, 
                icon: Ext.MessageBox[ result.success ? "INFO" : "ERROR"]
            });
        } else {
            Ext.MessageBox.show({ title:'Status', msg: result.prompt,
               buttons: Ext.MessageBox.YESNOCANCEL,
               fn: cb.createDelegate(this),
               icon: Ext.MessageBox.QUESTION });
        }
    },

    removeHandler : function(status) {
        if ( !this.selectedItem ) return;
        
        var fn = function( btn) {
            if ( btn=="yes" ) {
            
                // get checkbox value
                var body = Ext.Msg.getDialog().body;
                var chkbx = body.select('input[id=search-cleanup]').elements[0];
                var cleanup = chkbx.checked
                this.showWait();
                CommonDataHandler.rpc.removeSearchServer( this.selectedItem,  cleanup, 
                    this.updatedHandler.createDelegate(this, [], true) 
                ).call(ext_channel);
            }
        };
        
        
        var callback = function(result, status){
           Ext.MessageBox.hide();
           if ( !result.success  ) {
                this.showMsg( result );            
           }
            
            var chbval = result.cleanSrc;
            var msg_text = (status == 'Removing') ? "Search Server is in delete pending state" :  "Search Server will be removed. Are you sure?"
            
            var dialog = Ext.MessageBox.confirm( 
                'Search Servers', 
                msg_text + "<br /><br />" +
                "<span><input type='checkbox' id='search-cleanup' " +
                ( chbval ? ' checked ' : ' ') + 
                "style='vertical-align: middle;'/>&nbsp;<label for='search-cleanup'>Cleanup search sources</label></span>",
                fn.createDelegate(this)
            ).getDialog(); 
            dialog.defaultButton = 2;
            dialog.focus();
        }
        
        this.showWait();
        ext_channel(CommonDataHandler.rpc.getSearchServerInfo( 
            this.selectedItem, callback.createDelegate(this, [status], true)
        ));    
    },
    
    addSearchServer : function(data) {
        if ( !data.force )  this.showWait();
        ext_channel(CommonDataHandler.rpc.addSearchServer( data, this.updatedHandler.createDelegate(this) ));
        return false;
    },
    
    editSearchServer : function(data) {
        ext_channel(CommonDataHandler.rpc.editSearchServer( this.selectedItem, data, this.updatedHandler.createDelegate(this) ));
        return false;
    },
    
    updatedHandler : function(result) {
        try { Ext.MessageBox.hide(); } catch(e){}
        if ( result.success ) {
            if ( this.wndConn ) { this.wndConn.close(); }

        } if ( !result.success ) {
            this.showMsg( result );            
        }
        
        Ext.apply( this.store.baseParams, { clearCache : true });
        this.store.load();
    },

    onCommitSch : function( data ) {
        this.selectedVc.schedule = data;
        CommonDataHandler.rpc.updateVc( 
            this.selectedVc, this.dataUpdated.createDelegate(this) ).call(ext_channel);
    },

    scheduleHandler : function(x) {
        var commitfn = function(data) {
            ext_channel(CommonDataHandler.rpc.updateCatalogScheduleSettings( data, 
                this.updatedHandler.createDelegate(this) ));
        };
    
        var fn = function(r) {
            var f = new Veeam.CatalogSchedulerSettings({ data: r, listeners:{commit: commitfn.createDelegate(this) } });
            f.show();
        };
        ext_channel(CommonDataHandler.rpc.getCatalogScheduleSettings( fn.createDelegate(this) ));
    },
    
    activate :function(params) {
        Veeam.SearchServersPanel.superclass.activate.apply(this, [params] );
    },
    
    deactivate :function(params) {
        Veeam.SearchServersPanel.superclass.deactivate.apply(this, [params] );
    }
   
});

Ext.reg('vm.ui.searchservers', Veeam.SearchServersPanel );


/*
    ConnectionSettings for Search server
*/
Veeam.SearchConnectionSettings = function(config) {
   var config = config || {};
   // override port
   config.initData = Ext.applyIf(config.initData || {} , { port: 9395 } );
   var data = config.initData||{ usessl:true, proxy: { mode: 'noproxy' }, port: 9395};
  
   this.tfIndexLimit= new Ext.form.NumberField({ hideLabel:true, minValue: 1000, maxValue: 999999, value : data.index_limit, width:50, allowBlank: false, validationEvent: false, msgTarget: 'side', allowDecimals: false, allowNegative: false }); 
    
    this.cbServer = new Veeam.SimpleComboBox({
        id: 'cb_serverType',
        data: [
            ['300000','Microsoft Search Server'],
            ['30000','Microsoft Search Server Express (SQL)'],
            ['3000','Microsoft Search Server Express (SQL Express)'],
            ['', "Custom"]
        ]
    });
    
    this.cbServer.on('select', this.onComboSelect, this);
    
    this.pnVC = new Ext.Panel ({ 
            border:false,
            width: 368,
            html: '<table class="x-settings" style="border-collapse:collapse" cellspacing="4" cellpadding="0" ><tr style="width:1px; margin-top:-5px"><td style="width:70px"></td><td style="width:100px"></td><td style="width:110px"></td><td style="width:110px"></td></tr>' +
                '<tr><td colspan=4><label>DNS name or IP address of the Search server:</label></td></tr>' + 
                '<tr><td colspan=4 class="x-form-field-wrap" ></td></tr>' +
                '<tr><td colspan=4><label>Server description:</label></td></tr>' + 
                '<tr><td colspan=4 class="x-form-field-wrap" ></td></tr>' +
                
                '<tr><td rowspan="4" valign="middle"><img src="css/images/keys.png" alt="" /></td>' +
                '<td colspan="3" class="x-form-field-wrap"></td></tr>' +
                '<tr><td><label>User name:</label></td><td colspan="2" class="x-form-field-wrap"></td></tr>' +
                '<tr><td><label>Password:</label></td><td colspan="2" class="x-form-field-wrap"></td></tr>' +
                '<tr><td>Port:</td><td class="x-form-field-wrap"></td><td class="x-form-field-wrap"></td></tr></table>' +
                '<table class="x-settings x-settigs-capacity" style="padding-top: 3px;" cellspacing="0" cellpadding="0" >' +
                '<tr><td colspan="2" style="border-bottom: 1px solid #CCCCCC;"><b>Capacity</b></td></tr>' +
                '<tr><td colspan="2" style="padding-top: 3px; padding-bottom: 3px; ">' +
                'Specify backend database server type to set recommended capacity values for this indexing server.'+ 
                '</td></tr>' + 
                '<tr><td width="25%"><label>Server type:</label></td><td class="x-form-capacity"></tr>' +
                '<tr><td width="25%"><label>Index limit:</label></td><td class="x-form-capacity"></tr></table>'
        });
        
    
    
    // configure dialog itself
    config = Ext.applyIf( config||{}, {
        title: 'Search Server Settings',
        pnVC : this.pnVC,
        resizable: false
    });
    
    this.addEvents('commit');
    Veeam.SearchConnectionSettings.superclass.constructor.apply(this, [config]);
};

 
Ext.extend(Veeam.SearchConnectionSettings, Veeam.ConnectionSettings, {

    initComponent : function() {
        Veeam.SearchConnectionSettings.superclass.initComponent.call(this);
        this.on('show', this.fixListZIndex, this);
     },

    fixListZIndex: function(){
        var zIndex = parseInt(this.getEl().getStyle("z-index"));
        var listEl = this.cbServer.getListParent();
        if(listEl){
            listEl.style.zIndex = zIndex + 10; // make sure the combo's list will display.
        }
    },
    
    destroy: function() {
        this.tfIndexLimit.destroy();
        this.cbServer.destroy();
        Veeam.SearchConnectionSettings.superclass.destroy.apply( this, arguments );
    },

    render: function() {
       Veeam.SearchConnectionSettings.superclass.render.apply( this, arguments );
       var tda = this.pnVC.body.select("td.x-form-capacity");
       // Render combobox
       this.cbServer.render(tda.item(0).dom);
       this.cbServer.setWidth(264);

       this.tfIndexLimit.render(tda.item(1).dom);
       
       var currIndexLimit = this.tfIndexLimit.getValue();
       if ((currIndexLimit != 3000) && (currIndexLimit != 30000) && (currIndexLimit != 300000)){
            // Custom value
            this.cbServer.setValue("");
       } else { 
            this.cbServer.setValue(currIndexLimit);
       }


       
    },
    captureData : function() {
        this.btnOk.focus();

        var data = { 
            servername: this.tfServer.getValue(),
            creds: this.cbCreds.getValue(),
            username: this.tfUsername.getValue(),
            port: this.tfPort.getValue(),
            usessl: this.cbUseSsl.getValue(),
            description: this.tfDescr.getValue(),
            index_limit: this.tfIndexLimit.getValue()
        };
        
        if ( this.passwordChanged )
            data = Ext.apply(data, {password: this.tfPassword.getValue() } ); 
            
        data.proxy = { 
            port: (this.nfProxyPort.getRawValue()=='' ? 0 : this.nfProxyPort.getValue()),
            mode : this.rbNoProxy.getValue() ? 'noproxy' : (this.rbAutoProxy.getValue() ? 'auto' : 'manual'),
            servername : this.tfProxyServer.getValue(),
            username : this.tfProxyUsername.getValue(),
            password : this.tfProxyPassword.getValue()
       }
       return data;
    },
    onComboSelect: function(combo, record, index){
        if (index ==  3) return 
        var val = record.get('value');
        this.tfIndexLimit.setValue(val);
    },
    validate: function(){
        var v = Veeam.SearchConnectionSettings.superclass.validate.apply( this, arguments );
        
        v = this.tfIndexLimit.validate() && v;
        return v;
    }
});

Ext.reg('vm.ui.searchconnectionsettings', Veeam.SearchConnectionSettings );


/*
    SchedulerSettings
*/
Veeam.CatalogSchedulerSettings = function(config) {
    config = config || {};
    
    this.data = config.data;
    
    this.rdManually = new Ext.form.Radio({ 
        boxLabel:'Manually', 
        name: 'scheduler-settings-2-type', 
        handler: this.modeHandler.createDelegate(this), 
        checked: config.data.type=='manually', 
        width:140,
        colspan: 2 
    });
     
    this.rdPeriodically = new Ext.form.Radio({ 
        boxLabel:'Automatically after any backup job finishes', 
        name: 'scheduler-settings-2-type', 
        handler: this.modeHandler.createDelegate(this), 
        checked: config.data.type=='periodically', 
        colspan: 2
     });
    
    this.nfPeriodMin = new Ext.form.NumberField({ 
        value:config.data.min.period, 
        width:50, 
        minValue:1, 
        allowDecimals:false,  
        allowNegative:false, 
        allowBlank:false, 
        maxLength:6 
     });
     
    this.nfPeriodMax = new Ext.form.NumberField({ 
        value:config.data.max.period, 
        width:50, 
        minValue:1, 
        allowDecimals:false,  
        allowNegative:false, 
        allowBlank:false, 
        maxLength:6 
     });
     
    this.ckbPeriodMin = new Ext.form.Checkbox({
        id: "cb_period_min",
        boxLabel:'Wait for other running jobs for up to',
        handler: this.cboxHandler.createDelegate(this),
        checked: config.data.min.is_checked 
    });
    
    this.ckbPeriodMax = new Ext.form.Checkbox({
        id: "cb_period_max",
        boxLabel:'Update index no more often than once every',
        handler: this.cboxHandler.createDelegate(this), 
        checked: config.data.max.is_checked  
    });
    
    

    
    this.cbPeriodTypeMin = new Ext.form.ComboBox({ 
        store : new Ext.data.SimpleStore({ fields:['value', 'name'],   data:[ ['hours', 'hour(s)'], ['minutes', 'minute(s)'] ] }),
        valueField: 'value', displayField: 'name',                        
        value:config.data.min.type,
        typeAhead: true,
        triggerAction: 'all',
        shadow:false,
        stateful:false,
        mode: 'local'
    });
    
    this.cbPeriodTypeMax = new Ext.form.ComboBox({ 
        store : new Ext.data.SimpleStore({ fields:['value', 'name'],   data:[ ['hours', 'hour(s)'], ['minutes', 'minute(s)'] ] }),
        valueField: 'value', displayField: 'name',                        
        value:config.data.max.type,
        typeAhead: true,
        triggerAction: 'all',
        shadow:false,
        stateful:false,
        mode: 'local'
    });

    // buttons 
    this.btnOk = new Ext.Button({ text : 'OK', handler: this.commitHandler.createDelegate(this) });
    this.btnCancel = new Ext.Button({ text : 'Cancel', handler: this.closeHandler.createDelegate(this) });
    
    
    this.tblPeriod = new Ext.Container({
        layout: 'table',
        layoutConfig: { columns: 3 },
        border: false,
        items: [
          this.ckbPeriodMin, this.nfPeriodMin, this.cbPeriodTypeMin,
          this.ckbPeriodMax, this.nfPeriodMax, this.cbPeriodTypeMax    
        ] 
    });
    
    // configure dialog itself
    config = Ext.applyIf( config, {
        autoHeight:true,
        width:460,
        hideLabels:true,
        border: false,
        title: 'Replicate catalogs',
        buttons: [ this.btnOk, this.btnCancel ],
        shadow:false,
        modal:true,
        layout:'table',
        layoutConfig : { columns: 2 },
        cls: 'scheduler-settings-wnd',
        stateful:false,
        bodyStyle:'padding:10px',
        items: [ 
            {text:'Update index:', border:false, colspan:2, xtype:'label'},
            this.rdManually,  
            this.rdPeriodically, 
            {colspan:2, items: this.tblPeriod, border: false } 
        ],   
        keys: [{key:13, fn:this.commitHandler, scope:this}]
    });
    
    this.addEvents('commit');
    Veeam.CatalogSchedulerSettings.superclass.constructor.apply(this, [config]);
};
 
// extend Wisard behavior 
Ext.extend(Veeam.CatalogSchedulerSettings, Veeam.Window, {
    cboxHandler : function (cb, checked){
        // Enable/disable fields on cbox click
       
        if (cb.id == 'cb_period_max'){
            this.cbPeriodTypeMax.setDisabled(!checked);
            this.nfPeriodMax.setDisabled(!checked);
            return
        }
        if (cb.id == 'cb_period_min'){
            this.cbPeriodTypeMin.setDisabled(!checked);
            this.nfPeriodMin.setDisabled(!checked);
            return
        }
        
    },
    modeHandler : function( rb, checked )
    {
        if ( this.rdManually.getValue() )  {
            this.cbPeriodTypeMin.disable();
            this.ckbPeriodMin.disable();
            this.nfPeriodMin.disable();
            this.cbPeriodTypeMax.disable();
            this.ckbPeriodMax.disable();
            this.nfPeriodMax.disable();
        } else {
            this.ckbPeriodMin.enable();
            this.cbPeriodTypeMin.setDisabled(!this.ckbPeriodMin.checked);
            this.nfPeriodMin.setDisabled(!this.ckbPeriodMin.checked);
            
            this.ckbPeriodMax.enable();
            this.cbPeriodTypeMax.setDisabled(!this.ckbPeriodMax.checked);
            this.nfPeriodMax.setDisabled(!this.ckbPeriodMax.checked);
        }
    },
    
    closeHandler : function() {  this.close();  },
    
    commitHandler : function() {
        if (!this.validate()) return;
            
        var data = {
            min: {
                period : this.nfPeriodMin.getValue(),
                type: this.cbPeriodTypeMin.getValue(),
                is_checked: this.ckbPeriodMin.getValue()
            },
            max: {
                period : this.nfPeriodMax.getValue(),
                type: this.cbPeriodTypeMax.getValue(),
                is_checked: this.ckbPeriodMax.getValue()
            },
            id: this.data.id,
            periodN : this.data.periodN
        };
        
        if (this.rdManually.getValue()) data.type = 'manually' ;
        if (this.rdPeriodically.getValue()) data.type = 'periodically';
        
        this.fireEvent('commit', data );
        this.close();
    },
    
    show: function() {
        Veeam.CatalogSchedulerSettings.superclass.show.apply( this, arguments );
        this.cbPeriodTypeMin.setWidth(80);
        this.cbPeriodTypeMax.setWidth(80);
        this.modeHandler();
    },
    
    validate: function() {
		var result = true;
		
		if (!this.nfPeriodMin.validate())
			result = false;
		if (!this.nfPeriodMax.validate())
			result = false;	
		return result;
    }
});

/* Licensing */

Veeam.LicenseGrid = function(config) {
    config = Ext.applyIf(config ||{} , {
        border: false
    });
    Veeam.LicenseGrid.superclass.constructor.apply(this, [config]);
};
 
Ext.extend(Veeam.LicenseGrid, Veeam.AutoGridPanel, {
    revokeLicense : function() {
        if ( !this.selectedItem ) return;
        var fn = function( btn) {
            if ( btn=="yes" ) {
                //  Get multiple selected rows  
                var selModel = this.grid.getSelectionModel();
                var selectedItems = [];
                if (selModel) {
                    // get selected Data;
                    var records = selModel.getSelections();
                    for (var i=0, len = records.length; i < len; i++){
                        selectedItems.push(records[i].get('objectId'));
                    }
                
                }
               
                this.showWait();
                var licensePanel = Ext.getCmp('license-panel');
                CommonDataHandler.rpc.revokeLicenses( selectedItems , 
                    licensePanel.revokeCallback.createDelegate(licensePanel, [], true) 
                ).call(ext_channel);
            }
        };

        Ext.MessageBox.confirm( 
            'Veeam Backup Enterprise Manager', 
            "Revoke selected licenses?",
            fn.createDelegate(this)
        ); 
    },
    
    activate :function(params) {
        Veeam.LicenseGrid.superclass.activate.apply(this, [params] );
    },
    
    deactivate :function(params) {
        Veeam.LicenseGrid.superclass.deactivate.apply(this, [params] );
    }
   
});

Ext.reg('vm.ui.licensegrid', Veeam.LicenseGrid );
