/* show settings window */
TP.settingsWindow = function() {

    /* stop rotation */
    TP.stopRotatingTabs();

    /* the settings form */
    var settings_form = new Ext.form.Panel({
        bodyPadding: 5,
        border:      0,
        defaults: {
            labelWidth:  100,
            anchor: '99%'
        },
        items: [{
            /* global refresh rate */
            xtype:      'tp_slider',
            formConf: {
                fieldLabel: 'Global Refresh Rate',
                value:      60,
                minValue:   0,
                nameS:      'refresh',
                nameL:      'refresh_txt'
            }
        }, new Ext.form.CheckboxGroup({
            /* global backends */
            id:         'global_backends',
            fieldLabel: 'Backends / Sites',
            xtype:      'checkboxgroup',
            vertical:   true,
            columns:    1,
            items:      []
        }), {
            /* rotating tabs */
            xtype:      'tp_slider',
            formConf: {
                fieldLabel: 'Rotate Tabs',
                value:      0,
                minValue:   0,
                nameS:      'rotate_tabs',
                nameL:      'rotate_tabs_txt'
            }
        }, {
            /* show server time */
            xtype:      'checkbox',
            fieldLabel: 'Show Server Time',
            name:       'server_time'
        }, {
            /* auto hide panlet header */
            xtype:      'checkbox',
            fieldLabel: 'Autohide Panlet Header',
            name:       'autohideheader'
        }, {
            /* Import / Export */
            xtype: 'panel',
            layout: {
                type: 'hbox',
                align: 'stretch'
            },
            items: [{
                xtype: 'button',
                text: 'Export All Tabs',
                handler: function() {
                    Ext.MessageBox.show({
                        title:      'All Tabs Export',
                        multiline:  true,
                        width:      500,
                        msg:        'Save this string',
                        value:      encode64(cp.encodeValue(cp.readValues())),
                        buttons:    Ext.MessageBox.OK,
                        icon:       Ext.MessageBox.INFO
                    });
                }
            }, {
                xtype: 'button',
                text: 'Import All Tabs',
                handler: function() {
                    Ext.MessageBox.prompt({
                        title:      'Import Tabs Export',
                        id:         'importdialog',
                        multiline:  true,
                        value:      '',
                        width:      500,
                        msg:        'Enter Saved String.<br>This will replace all currently existing Tabs and windows!',
                        buttons:    Ext.MessageBox.OKCANCEL,
                        icon:       Ext.MessageBox.INFO,
                        fn:         function(btn, text, window){
                            if(btn == 'ok') {
                                TP.importAllTabs(text);
                                win_settings.close();
                                Ext.MessageBox.alert('Success', 'Import Successful!');
                            }
                        }
                    });
                }
            }, {
                xtype: 'button',
                text: 'Reset to Default View',
                handler: function() {
                    Ext.Msg.confirm('Reset to default view?', 'Do you really want to reset all tabs and windows?', function(button) {
                        if (button === 'yes') {
                            TP.importAllTabs(default_view);
                            win_settings.close();
                            Ext.MessageBox.alert('Success', 'Reset Successful!<br>Please wait while page reloads...');
                        }
                    });
                }
            }]
        }]
    });

    /* save global settings */
    var settingsSave = function() {
        var win = this.up('window');
        var tab = Ext.getCmp('tabpan');
        var form = win.down('form').getForm();
        if(form.isValid()) {
            tab.xdata = TP.storeFormToData(form, tab.xdata);
            TP.setRefreshText(tab.xdata, 'rotate_tabs', 'rotate_tabs_txt');
            TP.applyFormValues(form, tab.xdata);
            TP.setBackends(tab.xdata.backends);
            delete tab.xdata['rotate_tabs_txt'];
            tab.saveState();
            win.destroy();
            TP.startRotatingTabs();
            TP.startServerTime();
            /* start refresh for all panlets with global refresh rate */
            var panels = TP.getAllPanel();
            for(var nr in panels) {
                var p = panels[nr];
                if(p.xdata.refresh == -1) {
                    p.startInterval();
                }
                if(tab.xdata.autohideheader) { p.header.hide() } else { p.header.show() }
            }
            return true;
        }
        return false;
    }

    /* the panel containing the form panel */
    var settings_panel = new Ext.panel.Panel({
        layout:     'fit',
        border:     0,
        items:      [settings_form],
        buttonAlign: 'center',
        fbar: [{ xtype:  'button', text: 'cancel', handler: function() { this.up('window').destroy() } },
               { xtype:  'button',
                 text:    'save',
                 handler: settingsSave
               }
        ],
        listeners: {
            afterrender: function(This, eOpts) {
                var tab = Ext.getCmp('tabpan');
                var form = This.down('form').getForm();
                // reset backends to global ones
                tab.xdata.backends = [];
                for(var nr in initial_backends) {
                    if(initial_backends[nr].state != 2) {
                        tab.xdata.backends.push(nr);
                    }
                }
                TP.setRefreshText(tab.xdata, 'rotate_tabs', 'rotate_tabs_txt');
                TP.applyFormValues(form, tab.xdata);
                delete tab.xdata['rotate_tabs_txt'];
            }
        }
    });

    /* the actual settings window containing the panel */
    var win_settings = new Ext.window.Window({
        autoShow:    true,
        modal:       true,
        width:       400,
        title:       'Global Settings',
        html:        '',
        buttonAlign: 'center',
        items:       [settings_panel]
    });
    // checkboxes are wrong otherwise
    Ext.getCmp('global_backends').reset();
};


/* set backends from list */
TP.setBackends = function(backends) {
    for(var nr in initial_backend_states) {
        initial_backend_states[nr] = 2;
        initial_backends[nr].state = 2;
    }
    for(var nr in backends) {
        var b = backends[nr];
        initial_backend_states[b] = 0;
        initial_backends[b].state = 0;
    }
    TP.setBackendsCookieAndRefresh(0);
}

/* set cookie and reload panels */
var backendSelTimer;
TP.setBackendsCookieAndRefresh = function(wait) {
    /* save current selected backends in session cookie */
    document.cookie = "thruk_backends="+Ext.Object.toQueryString(initial_backend_states)+ "; path="+cookie_path+";";

    /* reload panel */
    window.clearTimeout(backendSelTimer);
    backendSelTimer = window.setTimeout(TP.refreshAllSitePanel, wait);
}
