﻿Veeam.Search.MainPanel = Ext.extend(Ext.TabPanel, {
    initComponent: function () {

        this.currentSearchTask = {};
        this.updateResultsTimer = null;
        this.prevTask = this.initialConfig.prevTask || {};
        this.initialBrowseParams = this.initialConfig.initialBrowseParams || {};
        this.initialSearchParams = this.initialConfig.initialSearchParams || {};
        this.noDownloadsAllowed = this.initialConfig.noDownloadsAllowed || false;
        this.resUpdateInterval = this.initialConfig.resUpdateInterval || 1;

        Ext.apply(this, {
            border: false,
            activeTab: 0,
            id: 'search-type-tab',
            deferredRender: false,  // important!
            cls: 'x-veeam-tabpanel-new',
            stateful: true,
            forceLayout: true,
            stateEvents: ['tabchange'],
            getState: this.getStateHandler,
            applyState: this.setStateHandler,
            listeners: {
                tabchange: { fn: this.typeChangeHandler, scope: this }
            },
            items: this.buildItems()
        });

        Veeam.Search.MainPanel.superclass.initComponent.call(this);

        this.attachEvents();

        this.initNotifier();
        this.initIndicators();
    },

    attachEvents: function () {
        // Monitor quick search

        this.addEvents('search.started', 'search.error', 'search.complete', 'search.update', 'change.vmname');

        //this.items.addListener('submit', this.searchHandler, this);
        this.pnSearch.addListener('submit', this.searchHandler, this);
        this.pnBrowse.addListener('submit', this.searchHandler, this);

        this.pnSearch.addListener('showhistory', this.showHistoryHandler, this);
        this.pnBrowse.addListener('showhistory', this.showHistoryHandler, this);
        this.pnRestoreList.addListener('showhistory', this.showHistoryHandler, this);

        this.pnRestoreList.on('removeitem', this.pnSearch.updateActionTrigger, this.pnSearch);
        this.pnRestoreList.on('removeitem', this.pnBrowse.updateActionTrigger, this.pnBrowse);

        //this.pnBrowse.addListener('show', this.bindInitialBrowseParams, this, { single: true });
        this.pnSearch.addListener('showerrors', this.showErrorsWind, this);


        this.addListener('change.vmname', this.pnBrowse.reloadOibs, this.pnBrowse, { delay: 100 });

        this.on('afterrender', this.renderHandler, this);
        this.on({
            'search.started': this.pnSearch.setSearchStarted,
            'search.error': this.pnSearch.setSearchErrors,
            'search.update': this.pnSearch.loadSearchResults,
            'search.complete': this.pnSearch.setSearchComplete,
            scope: this.pnSearch
        });
        this.on('update.restorestate', function (updtr, files) {
            this.pnBrowse.setFilesRestoreState(updtr, files);
            this.pnSearch.setFilesRestoreState(updtr, files);
            this.pnRestoreList.setFilesRestoreState(updtr, files);
        }, this);
    },

    buildItems: function () {

        //this.tabPanel = this.buildTabs();
        return this.buildTabs();
    },

    buildTabs: function () {

        this.pnBrowse = new Veeam.Search.BrowsePanel({
            layout: 'border',
            title: "Browse",
            id: "browse-panel",
            bodyCssClass: "x-browse-panel-body",
            border: true,
            anchor: '100%'
        });

        this.pnRestore = new Veeam.RestorePanel();
        this.pnRestoreList = new Veeam.RestoreList();

        this.pnSearch = new Veeam.Search.SearchTab();


        return [this.pnBrowse, this.pnSearch, this.pnRestore, this.pnRestoreList];
    },

    getStateHandler: function () {
        var activeTab = this.getActiveTab() || 0;
        if (!Ext.isNumber(activeTab)) {
            activeTab = this.items.findIndex('id', activeTab.getId());
        }
        return { 'activeTab': activeTab };
    },

    setStateHandler: function (state) {
        this.setActiveTab(Ext.isNumber(state.activeTab) ? state.activeTab : 0);
    },


    initNotifier: function () {
        // Restore started callback
        this.restoreObservers = [];
        this.pnRestore.on('restorestarted', function (options) {

            var restoreObserver = Veeam.RestoreSessionUpdaterManager.createUpdater(options.sessionId, options.files);
            restoreObserver.on('updateend', function (updtr, files) {
                //log("Calling setFilesRestoreState");
                this.fireEvent('update.restorestate', updtr, files);
            }, this);

            this.restoreObservers.push(restoreObserver);


            this.setActiveTab(this.pnRestore.getId());
            this.pnRestore.goToLastSession();

        }, this);


        var notifier = new Veeam.RestoreNotifier({ targetPn: this.pnRestore });

        this.items.addListener({
            'beforerestore': notifier.prepare,
            'restorefailed': notifier.fail,
            scope: notifier
        });
    },

    initIndicators: function () {
        // preload search indicator
        var img = new Image();
        img.src = Ext.LOADING_ANIM_IMG_URL;
        var imgBig = new Image();
        imgBig.src = Veeam.Search.SEARCHRESULTS_LOADER_SRC;
    },

    initData: function () {

        this.pnBrowse.initData(this.initialBrowseParams);
        this.pnSearch.initData(this.initialSearchParams);
        this.pnBrowse.initialVmName = Veeam.Search.SearchPanel.lastVmName = this.initialBrowseParams["vm_name"];
        this.fireEvent('change.vmname', this.pnBrowse.initialVmName);
    },

    prepareUI: function () {
        var licEdition = App.getLicenseType() || 0;
        if (App.isEnterpriseLicense() == false) {
            this.pnRestoreList.disableButtons();
            this.pnBrowse.disableButtons();
        }

        if (App.user && App.user.canRestore() == false) {
            this.pnRestoreList.disableButtons(true);
            this.pnBrowse.disableButtons(true);
        }

        if (this.noDownloadsAllowed == true && !App.user.canDownload()) {
            this.pnRestoreList.disableDownloads();
            this.pnBrowse.disableDownloads();
        }
        //Misc
        this.pnSearch.fireEvent('update.pagesize');
    },

    renderHandler: function () {
        this.initData();
        this.prepareUI();
    },

    searchHandler: function (field, value) {
        // Check search keyword is not empty
        var q = value;

        if (Ext.isEmpty(q)) {
            return this.pnSearch.showMsg({
                success: true,
                message: "Please enter one or more search words"
            });
        }

        var vmsearch = {},
            vmbrowse = {},
            requestType, oldTaskId;


        // If panel in "Browse" mode, than collect some data and set search params
        if (this.getActiveTab() instanceof Veeam.Search.BrowsePanel) {
            var requestModel = this.pnBrowse.getSearchData();
            this.pnSearch.updateSearchData(requestModel);
            requestType = 1;
            vmbrowse = requestModel.data;
            //TODO: need better way to handle vm name
            var vmObj = Ext.getCmp('vmname').getValueObject();
            vmbrowse["vmName"] = vmObj ? vmObj.vmDisplayName : "";
            vmbrowse["q"] = q;
            vmsearch["vm"] = Ext.getCmp('vmname').getValueObject();
            this.setActiveTab('advanced-search-form');
        } else {

            // validate Advanced params
            if (this.pnSearch.validateAdvancedValues() === false) {
                return this.pnSearch.showMsg({
                    success: false,
                    message: "One or more advanced search parameters are invalid."
                });
            }

            //TODO: vmsearch.vm = Ext.getCmp('vmname').getValueObject();

            var request = this.pnSearch.getSearchData();
            vmsearch = Ext.apply({}, request.data);
            vmsearch["vm"] = Ext.getCmp('vmname').getValueObject();
            vmsearch["q"] = q;
        }


        if (this.currentSearchTask && this.currentSearchTask.task_id) {
            old_task_id = this.currentSearchTask.task_id;
        }

        //Construct search request
        var request = {
            vmFileSearchRequest: vmsearch,
            rpFileSearchRequest: vmbrowse,
            requestType: requestType,
            old_task_id: oldTaskId
        };

        // Clear previous search values
        this.currentSearchTask = null;
        clearInterval(this.updateResultsTimer);

        var cbFn = function (result) {

            if (result.success == false) {
                this.pnSearch.fireEvent('unmask');
                this.fireEvent('search.complete');
                return this.pnSearch.showMsg(result);
            }
            // show load status
            this.fireEvent('search.started');
            this.getSearchTask(result);
        };

        this.pnSearch.fireEvent('mask');
        this.pnSearch.fireEvent('update.pagesize');
        ext_channel(CommonDataHandler.rpc.getSearchResult(request, cbFn.createDelegate(this)));
    },

    updateResults: function () {

        var cbFn = function (cnf) {
            // Check if server returned error
            this.pnSearch.fireEvent('unmask');
            this.pnSearch.fireEvent('update.pagesize');
            if (cnf.success === false) {
                this.onSearchEnd();
                return this.pnSearch.showMsg(cnf);
            }

            var oldSearchTask = this.currentSearchTask || {};
            this.currentSearchTask = cnf;

            // Load data in panel when we got results
            this.fireEvent('search.update', cnf.task_id, cnf.results_count, oldSearchTask.results_count);


            // Show error button if errors
            if (cnf.errors_count > 0) {
                this.fireEvent('search.error', !!(cnf.errors_count == cnf.warnings_count));
            }

            if (cnf.isComplete == true) {
                // Hide status panel
                this.onSearchEnd(cnf);
            }

        }

        ext_channel(CommonDataHandler.rpc.updateTaskState(this.currentSearchTask, cbFn.createDelegate(this)));

    },
    onSearchEnd: function (cnf) {
        this.pnSearch.fireEvent('unmask');
        clearInterval(this.updateResultsTimer);
        this.fireEvent('search.complete');
        //if (this.pnResult.store.getCount() == 0) { this.pnResult.pn.update('<p class="mt5 ml5">No matches found</p>'); }
    },

    preloadSearchResults: function () {
        if (this.prevTask.task_id) {
            this.currentSearchTask = this.prevTask;
            this.updateResults();

            delete this.prevTask;
        }
    },

    getSearchTask: function (cnf) {
        //Ext.Msg.hide();
        this.currentSearchTask = cnf;
        this.updateResultsTimer = setInterval(this.updateResults.createDelegate(this), parseInt(this.resUpdateInterval * 1000));
    },

    showErrorsWind: function () {
        // Show window with errors in search result
        var cnf = this.currentSearchTask;

        // Get search errors
        var clb = function (res) {
            if (res.success == false) {
                this.pnSearch.showMsg(res);
            } else {
                // Display errors
                var errWin = new Veeam.Search.ErrorsWindow({ data: res.items });
                errWin.show();
            }
        }
        ext_channel(CommonDataHandler.rpc.getSearchErrors(this.currentSearchTask, clb.createDelegate(this)));
    },

    typeChangeHandler: function (pn, tab) {
        this.searchType = tab.id == 'browse-panel' ? 'browse' : 'search';
    },

    showHistoryHandler: function (session_id) {
        this.activate(this.pnRestore);
        if (session_id && typeof (session_id).toLowerCase() == 'string') {
            this.pnRestore.selectRecord.defer(100, this.pnRestore, [session_id]);
        }

    }

});


Veeam.Search.SearchTab = Ext.extend(Veeam.Search.CommonPanel, {
    initComponent: function() {
        Ext.apply(this, {
            layout: "border",
            border: true,
            frame: false,
            id: "advanced-search-form",
            bodyCssClass: 'advanced-search-form-body',
            anchor: '100%',
            title: "Search",
            cls: 'x-panel-collapsed',
            forceLayout: true,
            defaults: { split: false },
            items: this.buildItems()
        });
        Veeam.Search.SearchTab.superclass.initComponent.call(this);


        if (this.noSearchServerFlag) {
            this.tabAdvancedCriteria.insert(0, {
                xtype: 'box', width: 500,
                html: '<div class="x-notice">To enable advanced search functionality, add at least one search server.<br />To add search server, go to Configuration -> Search servers</div>'
            });
        }
    },

    buildItems: function() {

        this.queryField = new Veeam.Search.QuickSearchField({
            fieldLabel: 'Search',
            width: 230,
            id: 'q',
            name: 'q'
        });

        // Results panel
        this.pnResult = new Veeam.Search.ResultPanel({ region: "center", border: false });

        this.collapseTool = new Ext.BoxComponent({
            cls: 'x-collapse-tool',
            width: 150,
            html: '<div class="inner"><div class="tool"></div><span class="text">Advanced search</span></div>',
            id: 'advanced-options-collapse-tool',
            hidden: this.noSearchServerFlag
        });


           this.cbDateType = new Veeam.SimpleComboBox({
            hiddenName: 'lmt_datetype',
            id: 'cb_lmt_datetype',
            hiddenValue: 0,
            data: [
                ['1', 'A long time ago'],
                ['2', 'Earlier this year'],
                ['3', 'Earlier this month'],
                ['4', 'Last week'],
                ['5', 'Yesterday']
            ],
            width: 238,
            colspan: 3, // for table layout
            disabled: true
        });

        this.cbDocType = new Veeam.SimpleComboBox({
            hiddenName: 'doctype',
            id: 'cb_doctype',
            width: 250,
            data: [
                ['txt', 'TXT'],
                ['rtf', 'RTF'],
                ['doc', 'Microsoft Word (doc)'],
                ['xls', 'Microsoft Excel (xls)'],
                ['ppt', 'Microsoft PowerPoint (ppt)'],
                ['pdf', 'Adobe PDF'],
                ['jpg', 'JPG'],
                ['gif', 'GIF'],
                ['png', 'PNG'],
                ['avi', 'AVI'],
                ['mpg', 'MPG'],
                ['flv', 'Flash Video (flv)']
            ],
            disabled: true
        });

        this.cbSizeType = new Veeam.SimpleComboBox({
            hiddenName: 'sizetype',
            hiddenValue: 0,
            id: 'cb_sizetype',
            width: 250,
            labelSeparator: '',
            colspan: 5,
            data: [
                ['1', 'Tiny (0-10KB)'],
                ['2', 'Small (10-100KB)'],
                ['3', 'Medium (100KB-1MB)'],
                ['4', 'Large (> 1MB)']
            ],
            disabled: true
        });

        this.cbSizeOptFrom = new Veeam.SimpleComboBox({
            hiddenName: 'size_opt_from',
            width: 60,
            id: 'cb_size_opt_from',
            data: [
                [1000, 'KB'],
                [1000000, 'MB'],
                [1000000000, 'GB']
            ],
            disabled: true
        });

        this.cbSizeOptTo = new Veeam.SimpleComboBox({
            hiddenName: 'size_opt_to',
            width: 60,
            id: 'cb_size_opt_to',
            data: [
                [1000, 'KB'],
                [1000000, 'MB'],
                [1000000000, 'GB']
            ],
            disabled: true
        });

        // Search button
        this.btnSearch = new Ext.Button({
            text: 'Search',
            scope: this,
            handler: this.searchHandler
        });

        // FIELDSETS
        // Type fieldset
        this.fsType = new Veeam.Search.SearchFieldset({
            layoutConfig: { columns: 2 },
            title: "Type",
            layout: "table",
            items: [
                {
                    xtype: 'radio',
                    name: 'rb_doctype',
                    boxLabel: 'Any document',
                    cellCls: 'td-first',
                    id: 'rb_doctype_0',
                    inputValue: 0,
                    checked: true,
                    colspan: 2,
                    labelSeparator: '',
                    listeners: {
                        check: this.toggleFields
                    }
                },
                {
                    xtype: 'radio',
                    name: 'rb_doctype',
                    boxLabel: 'Known type:',
                    cellCls: 'td-first',
                    id: 'rb_doctype_1',
                    inputValue: 1,
                    labelSeparator: '',
                    listeners: {
                        check: this.toggleFields
                    }
                },
                this.cbDocType,
                {
                    xtype: 'radio',
                    name: 'rb_doctype',
                    boxLabel: 'Extension:',
                    cellCls: 'td-first',
                    id: 'rb_doctype_2',
                    inputValue: 2,
                    labelSeparator: '',
                    listeners: {
                        check: this.toggleFields
                    }
                },
                {
                    xtype: 'textfield',
                    name: 'doctype_ext',
                    id: "doctype_ext",
                    cls: "w100",
                    labelSeparator: '',
                    disabled: true
                }
            ]
        });

        // Author fieldset
        this.fsAuthor = new Veeam.Search.SearchFieldset({
            layoutConfig: { columns: 2 },
            title: "Owner",
            layout: "table",
            items: [
                {
                    xtype: 'radio',
                    name: 'rb_owner',
                    checked: true,
                    cellCls: 'td-first',
                    boxLabel: 'Any owner',
                    id: 'rb_owner_0',
                    inputValue: 0,
                    colspan: 2,
                    labelSeparator: '',
                    listeners: {
                        check: this.toggleFields
                    }
                },
                {
                    xtype: "radio",
                    name: "rb_owner",
                    id: "rb_owner_1",
                    cellCls: 'td-first',
                    boxLabel: "This owner:",
                    inputValue: 1,
                    listeners: {
                        check: this.toggleFields
                    }
                },
                {
                    xtype: "textfield",
                    style: "margin: 5 0 5 0;",
                    name: "author",
                    id: "author",
                    width: 250,
                    disabled: true
                }
            ]
        });

        // Location fieldset
        this.fsLocation = new Veeam.Search.SearchFieldset({
            layoutConfig: { columns: 3 },
            title: "Location",
            layout: "table",
            items: [
                {
                    xtype: 'radio',
                    name: 'rb_location',
                    checked: true,
                    cellCls: 'td-first',
                    boxLabel: 'Anywhere on VM',
                    id: 'rb_location_0',
                    inputValue: 0,
                    labelSeparator: '',
                    listeners: {
                        check: this.toggleFields
                    }
                },
                {
                    xtype: 'box', colspan: 2
                },
                {
                    xtype: 'radio',
                    name: 'rb_location',
                    boxLabel: "Folder:",
                    cellCls: 'td-first',
                    id: 'rb_location_1',
                    inputValue: 1,
                    labelSeparator: '',
                    listeners: {
                        check: this.toggleFields
                    }
                },
                {
                    xtype: "textfield",
                    style: "margin: 5 5 5 0;",
                    width: 180,
                    tabIndex: 1,
                    name: "vmfolder",
                    id: "vmfolder",
                    disabled: true,
                    itemId: 'vmfolderField'
                },
                {
                    xtype: "button",
                    id: "vmfolder_button",
                    text: "Browse",
                    disabled: true,
                    cls: 'x-btn-gray',
                    handler: this.selectFolderHandler.createDelegate(this)
                }
            ]
        });

        // Last modification time fieldset
        this.fsLMT = new Veeam.Search.SearchFieldset({
            layoutConfig: { columns: 4 },
            title: "Last modification time",
            layout: "table",
            hideLabels: true,
            items: [
                {
                    xtype: 'radio',
                    labelSeparator: '',
                    inputValue: 0,
                    id: 'rb_lmt_0',
                    checked: true,
                    name: 'rb_lmt',
                    cellCls: 'td-first',
                    boxLabel: 'Not sure',
                    colspan: 4,
                    listeners: {
                        check: this.toggleFields
                    }
                },
                {
                    xtype: 'radio',
                    labelSeparator: '',
                    inputValue: 1,
                    id: 'rb_lmt_1',
                    cellCls: 'td-first',
                    name: 'rb_lmt',
                    boxLabel: 'Approximate time:',
                    listeners: {
                        check: this.toggleFields
                    }
                },
                this.cbDateType,
                {
                    xtype: 'radio',
                    labelSeparator: '',
                    inputValue: 2,
                    id: 'rb_lmt_2',
                    name: 'rb_lmt',
                    cellCls: 'td-first',
                    boxLabel: 'Time between:',
                    listeners: {
                        check: this.toggleFields
                    }
                },
                {
                    xtype: 'vm.ui.datefield',
                    name: 'lmt_from',
                    vtype: 'daterange',
                    id: "lmt_from",
                    emptyText: 'Start date',
                    maxValue: new Date().add(Date.DAY, 1),
                    width: 100,
                    endDateField: 'lmt_to',
                    disabled: true
                },
                {
                    xtype: "label",
                    text: "and",
                    autoWidth: false,
                    forId: "lmt_to",
                    cls: 'ml5 mr5'
                },
                {
                    xtype: 'vm.ui.datefield',
                    name: 'lmt_to',
                    vtype: 'daterange',
                    id: "lmt_to",
                    emptyText: 'End date',
                    maxValue: new Date().add(Date.DAY, 1),
                    width: 100,
                    startDateField: 'lmt_from',
                    disabled: true
                }
            ]
        });

        // Size fieldset
        this.fsSize = new Veeam.Search.SearchFieldset({
            layoutConfig: { columns: 6 },
            title: "Size",
            layout: "table",
            items: [
                {
                    xtype: 'radio',
                    labelSeparator: '',
                    inputValue: 0,
                    checked: true,
                    cellCls: 'td-first',
                    name: 'rb_size',
                    id: 'rb_size_0',
                    boxLabel: 'Not sure',
                    colspan: 6,
                    listeners: {
                        check: this.toggleFields
                    }
                },
                {
                    xtype: 'radio',
                    labelSeparator: '',
                    inputValue: 1,
                    name: 'rb_size',
                    id: 'rb_size_1',
                    cellCls: 'td-first',
                    boxLabel: 'Approximate size:',
                    listeners: {
                        check: this.toggleFields
                    }
                },
                this.cbSizeType,
                {
                    xtype: 'radio',
                    labelSeparator: '',
                    inputValue: 2,
                    cellCls: 'td-first',
                    name: 'rb_size',
                    id: 'rb_size_2',
                    boxLabel: 'Size between:',
                    listeners: {
                        check: this.toggleFields
                    }
                },
                {
                    xtype: 'vm.ui.spinnerfield',
                    fieldLabel: '',
                    name: 'size_from',
                    id: 'size_from',
                    minValue: 0,
                    maxValue: 999999,
                    allowNegative: false,
                    value: 0,
                    allowDecimals: false,
                    incrementValue: 1,
                    allowBlank: false,
                    alternateIncrementValue: 5,
                    accelerate: true,
                    width: 44,
                    hideLabel: true,
                    disabled: true
                },
                this.cbSizeOptFrom,
                {
                    xtype: "label",
                    text: "and",
                    autoWidth: false,
                    forId: "size_to",
                    cls: 'ml5 mr5 mt5'
                },
                {
                    xtype: 'vm.ui.spinnerfield',
                    name: 'size_to',
                    id: 'size_to',
                    minValue: 0,
                    maxValue: 999999,
                    allowNegative: false,
                    allowBlank: false,
                    value: 0,
                    allowDecimals: false,
                    incrementValue: 1,
                    alternateIncrementValue: 5,
                    accelerate: true,
                    width: 44,
                    hideLabel: true,
                    disabled: true
                },
                this.cbSizeOptTo
            ]
        });


        // Backuptime fieldset
        this.fsBackuptime = new Veeam.Search.SearchFieldset({
            layoutConfig: { columns: 4 },
            title: "Backup time",
            layout: "table",
            items: [
                {
                    xtype: 'radio',
                    labelSeparator: '',
                    inputValue: 0,
                    cellCls: 'td-first',
                    checked: true,
                    name: 'rb_btime',
                    id: 'rb_btime_0',
                    boxLabel: 'Latest backup',
                    colspan: 4,
                    listeners: {
                        check: this.toggleFields
                    }
                },
                {
                    xtype: 'radio',
                    labelSeparator: '',
                    inputValue: 1,
                    id: 'rb_btime_1',
                    cellCls: 'td-first',
                    name: 'rb_btime',
                    boxLabel: 'Backups between:',
                    listeners: {
                        check: this.toggleFields
                    }
                },
                {
                    xtype: 'vm.ui.datefield',
                    name: 'btime_from',
                    id: 'btime_from',
                    maxValue: new Date().add(Date.DAY, 1),
                    emptyText: 'Start date',
                    width: 100,
                    vtype: 'daterange',
                    endDateField: 'btime_to',
                    disabled: true
                },
                {
                    xtype: "label",
                    text: "and",
                    autoWidth: false,
                    forId: "backup_to",
                    cls: 'ml5 mr5'
                },
                {
                    xtype: 'vm.ui.datefield',
                    name: 'btime_to',
                    id: 'btime_to',
                    maxValue: new Date().add(Date.DAY, 1),
                    emptyText: 'End date',
                    width: 100,
                    vtype: 'daterange',
                    startDateField: 'btime_from',
                    disabled: true
                },
                {
                    xtype: 'checkbox',
                    name: 'bimported',
                    id: 'bimported',
                    boxLabel: 'Search imported backups only',
                    colspan: 4
                }
            ]
        });


        // Search severs presence
        this.noSearchServerFlag = /*(config.meta.SearchServersCount < 1) ? true :*/false;




        this.tabAdvancedCriteria = new Ext.FormPanel({
            layout: "table",
            region: "north",
            titleCollapse: false,
            collapsible: false,
            collapsed: true,
            animCollapse: true,
            stateful: false, // Do not store panel state (expanded, etc..)
            border: false,
            id: "search-advanced-options-boxes",
            height: 400,
            autoScroll: true,
            //cls: 'pt5',
            bodyStyle: 'padding: 10px',
            forceLayout: true,
            layoutConfig: { columns: 2 },
            defaults: { border: false, cellCls: "pr10" },
            items: [this.fsLocation, this.fsAuthor,
                this.fsLMT, this.fsType,
                this.fsBackuptime, this.fsSize
            ]
        });

        return [
            {
                xtype: 'container',
                layout: 'hbox',
                region: 'north',
                style: "padding: 10px;",
                layoutConfig: { pack: 'start', align: 'middle' },
                height: 50,
                id: 'advanced-search-wrapper',
                items: [
                    {
                        id: 'search-wraper',
                        xtype: 'container',
                        layout: 'form',
                        width: 300,
                        labelWidth: 50,
                        items: this.queryField,
                        hidden: this.noSearchServerFlag
                    },
                    { xtype: 'box', flex: 2 },
                    this.collapseTool
                ]
            },
            {
                xtype: 'panel',
                //tbar: this.tbStatus,
                region: 'center',
                layout: 'border',
                border: false,
                items: [
                    this.tabAdvancedCriteria,
                    this.pnResult
                ]

            }
        ]
    },

    validateAdvancedValues: function () {
        var checkFields = ["size_from", "size_to", "lmt_from", "lmt_to", "btime_from", "btime_to"],
            i = checkFields.length,
            valid = true;

        while (i--) {
            var f = Ext.getCmp(checkFields[i]);
            if (f && f.disabled === false) {
                if (f.validate() === false) {
                    f.markInvalid();
                    valid = false;
                }
            }
        }

        return valid;
    },

    initEvents: function() {
        Veeam.Search.SearchTab.superclass.initEvents.call(this);
        this.addEvents(
            'expand.form', 'collapse.form',
            'submit', 'update.pagesize', 'mask', 'unmask'
        );

        this.relayEvents(this.queryField, ['submit']);
        this.relayEvents(this.pnResult, ['showhistory', 'showerrors']);

        // Collapse/expand search options
        this.collapseTool.on('afterrender', function () {
            this.mon(this.collapseTool.el, 'click',
                this.collapseHandler.createDelegate(this, [this.collapseTool])
            );

        }, this, { single: true });


        this.pnResult.addListener('bodyresize', this.pnResult.updatePageSize, this.pnResult);
        // Monitor user click a warnings/errors button in results toolbar
       // this.pnResult.addListener('showerrors', this.showErrorsWind, this);
        this.pnResult.addListener('beforeupdate.pagesize', this.beforeUpdateResultsSize, this);
        this.pnResult.addListener('show.backupinfo', this.showBackupInfo, this);
        this.pnResult.addListener('mask',  this.pnResult.doLoadMask, this.pnResult);
        this.pnResult.addListener('unmask',  this.pnResult.hideLoadMask, this.pnResult);
                
        this.addListener('update.pagesize', this.pnResult.updatePageSize, this.pnResult);

    },

    collapseHandler: function (tool, flag) {
        // Expand/collapse panel
        var is_collapsed = flag ? !flag : this.tabAdvancedCriteria.collapsed;
        if (is_collapsed) {
            tool.el.addClass('x-collapsed');
            this.removeClass('x-panel-collapsed');
            this.tabAdvancedCriteria.expand();
            this.fireEvent('expand.form');
        } else {
            this.addClass('x-panel-collapsed');
            tool.el.removeClass('x-collapsed');
            this.tabAdvancedCriteria.collapse();
            this.fireEvent('collapse.form');
        }
        this.doLayout();
    },

    initData: function (params) {
        // defaults
        this.cbSizeOptTo.setValue(1000);
        this.cbSizeOptFrom.setValue(1000);

        d = params && params.vmFileSearchRequest;
        if (Ext.isEmpty(d))
            return;

        if (params.requestType == 1) {
            // bind quicksearch params
            var rp = params.rpFileSearchRequest;
            d = Ext.applyIf({
                rb_location: 1,
                rb_btime: 1,
                btime_to: rp.restorePoint.m_backupDate,
                btime_from: rp.restorePoint.m_backupDate,
                vmfolder: rp.folderPath,
                q: rp.fileNamePattern,
                quicksearch: rp.fileNamePattern // quicksearch field
            }, d);

        }
        // vm display name fix
        delete d.vmname;
        d.vmname = d.vm;


        var dateFields = { "btime_to": true, "btime_from": true, "lmt_from": true, "lmt_to": true };
        var radio = { "rb_btime": 1, "rb_doctype": 1, "rb_lmt": 1, "rb_size": 1, 'rb_location': 1, 'rb_owner': 1 };
        var combo = { "size_opt_from": 1, "size_opt_to": 1, 'lmt_datetype': 1, 'doctype': 1, 'sizetype': 1 };
        // create a callback function and simulate radio click
        // some components may not be renedered because of ExtJS table layout bug, so use deffered call

        var rbSetFn = function (rb) {
            rb.el.dom.checked = true;
            rb.onClick.defer(300, rb);
        };
        for (var key in d) {
            if (!d.hasOwnProperty(key))
                continue;
            var val = d[key];
            // Radiobuttons
            if (key in radio) {
                var c = Ext.getCmp(key + "_" + d[key]);
                if (c.rendered == true) {
                    if (c) rbSetFn(c);
                } else {
                    c.on('render', rbSetFn.createDelegate(this, [c]));
                }
                continue;
            }
            // Comboboxes
            if (key in combo) {
                if (val == 0) continue;
                var cmp = Ext.getCmp('cb_' + key);
                cmp.on('afterrender', (function (c, v) {
                    c.setValue(v)
                }).createDelegate(this, [cmp, val]));
                continue
            }
            // Other
            var cmp = Ext.getCmp(key);
            if (cmp) {

                if (key in dateFields) {
                    if (val == 0) continue;
                    var date = new Date(parseInt(val) * 1000);
                    cmp.setValue(date);
                } else {
                    cmp.setValue(val);
                    if (cmp.id == 'vmname') {
                        cmp.fireEvent('change', cmp, val);
                        //  this.pnBrowse.initialVmName = Veeam.Search.SearchPanel.lastVmName = val;
                    }
                }
            }
        }
    },

    updateSearchData: function(dataModel) {
        if (!dataModel)
            throw new Error("Argument is null or empty");
        if (!(dataModel instanceof Veeam.Search.Model.VmBrowseRequest))
            throw new Error("Argument type is not Veeam.Search.Model.VmBrowseRequest");

        Ext.getCmp('vmfolder').setValue(dataModel.get('folderPath'));
        var rb = Ext.getCmp('rb_location_1');
        rb.el.dom.checked = true;
        rb.onClick.call(rb);


        var backupTimestampObj = dataModel.get('restorePoint'),
            backupTimestamp = backupTimestampObj["m_backupDate"],
            date = new Date(parseInt(backupTimestamp) * 1000);
        if (backupTimestamp){
            Ext.getCmp('btime_from').setValue(date);
            Ext.getCmp('btime_to').setValue(date);
            var rb = Ext.getCmp('rb_btime_1');
            rb.el.dom.checked = true;
            rb.onClick.call(rb);
        }
        this.queryField.setValue(dataModel.get('fileNamePattern'));

    },

    getSearchData: function() {
        var data = this.tabAdvancedCriteria.form.getValues();


        // Force date fields values to be unix timestamp
        var dateFields = ["btime_to", "btime_from", "lmt_from", "lmt_to"];
        for (var i = 0, len = dateFields.length; i < len; i++) {
            var field = dateFields[i];
            if (data[field]) {
                var dt = Ext.getCmp(field).getValue();
                if (!Ext.isDate(dt)) {
                    // Set to current day's midnight
                    dt = (new Date()).clearTime();
                }
                data[field] = dt.valueOf() / 1000;
            }
        }

        // force checkbox value  true/false
        data.bimported = Ext.getCmp('bimported').getValue();

        return new Veeam.Search.Model.VmFileSearchRequest( data );
    },

    clearResults: function(){
        this.pnResult.clearStore();
        this.pnResult.initialResultLoad = false;
    },

    setSearchStarted: function(){

        var progressbarText = Ext.getCmp('progress-bar-text');
        var progressbarBtn = Ext.getCmp('search-errors-button');
        var progressbarInd = Ext.getCmp('search-progress-ind');

        progressbarText.setText('Searching');
        progressbarBtn.hide();

        this.clearResults();


        // Collapse extended search form
        this.collapseHandler.apply(this, [this.collapseTool, true]);
        progressbarText.show();
        progressbarInd.show();
    },

    setSearchErrors: function(onlyWarn){
        var btn = Ext.getCmp('search-errors-button');
        // TODO: use css class
        btn.setIcon('img/icon_' + (onlyWarn ? 'alert' : 'error') + '.gif');
        btn.setText(onlyWarn ? 'Warnings' : 'Errors');
        btn.show();
        btn.enable();

    },

    loadSearchResults: function(taskId, resultsCount, oldResultsCount){

        this.pnResult.updateTotalCount(resultsCount);
        
        if (!this.pnResult.initialResultLoad && (resultsCount > 0)) {
            this.pnResult.loadResults(taskId, resultsCount);
            this.pnResult.initialResultLoad = true;
            //this.hideLoadMask();
        }

        // Refresh grid if we got new results
        if (this.pnResult.initialResultLoad && (resultsCount > oldResultsCount)) {
            var store = this.pnResult.store;
            var limit = resultsCount;
            var lastOptions = store.lastOptions;
            var length = (limit < this.pnResult.paging.pageSize) ? limit : this.pnResult.paging.pageSize;
            Ext.apply(lastOptions.params, {
                limit: length
            });

            this.pnResult.store.reload(lastOptions);
        }
    },
    setSearchComplete: function(){
        var barText = Ext.getCmp('progress-bar-text');
        barText.setText('Complete');
        (function () { barText.hide(); }).defer(600);
        Ext.getCmp('search-progress-ind').hide();
    },
    
    selectFolderHandler: function () {
        // Open folder selection dialog
        var vmName = Ext.getCmp('vmname').getValueObject();
        // If no Vm provided, show notice
        if (!vmName || !vmName.vmDisplayName) {
            return this.showMsg({ message: "Please, enter a VM name first" });
        }

        //  Get restore points list
        var callback = function (response) {
            if (response.success == false) {
                this.showMsg(response);
            } else {
                var winFolder = new Veeam.Search.FolderWindow({
                    vmName: vmName,
                    initialPath: Ext.get('vmfolder').getValue(),
                    storeData: response
                });
                winFolder.on('select.folder', this.onFolderSelected, this);
                winFolder.show();
            }
        };

        ext_channel(CommonDataHandler.rpc.getVmRestPoints({ vm_name: vmName }, callback.createDelegate(this)));
    },
    onFolderSelected: function(folderVal){
        if (!folderVal)
            throw new Error("Empty folder value");
        this.fsLocation.items.get('vmfolderField').setValue(folderVal);
    },
    beforeUpdateResultsSize: function(){
        return this.tabAdvancedCriteria.collapsed;
    },
    showBackupInfo:  function (record, json) {
        this.pnResult.hideLoadMask();
        var winExt = new Veeam.Search.ExtendedInfoWindow({ data: { record: record, info: json} });
        winExt.show();
    },
    toggleFields: function (radio, checked) {
        if (!checked) return
        // enable fields in current row
        // Disable all fields except radio in fieldset
        var fs = radio.findParentByType('vm.ui.searchfieldset');
        fs.items.each(function (field, idx, total) {
            if (field.id == radio.id) return;
            if (!field.xtype || !field.xtype.match('radio|checkbox|label')) {
                field.disable();
                if (field.clearInvalid) field.clearInvalid();
            }
        });

        var row = radio.el.findParentNode('tr', 10, true);
        var elems = row.query('input,table.x-btn');

        for (var i = 0, len = elems.length; i < len; i++) {
            var cmp = Ext.getCmp(elems[i].id);
            if (cmp) {
                if (cmp.id == radio.id) continue;
                cmp.enable(true)
            }
        }

    },
    
    updateActionTrigger: function(list, id, off){
        return this.pnResult.updateActionTrigger.apply(this.pnResult, [list, id, off]);
    },
    setFilesRestoreState: function(updtr, files){
        return this.pnResult.setFilesRestoreState(updtr, files);
    }

});