Welcome to mirror list, hosted at ThFree Co, Russian Federation.

config.js « src « js - github.com/phpmyadmin/phpmyadmin.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c1d343d4f253b3de88483cf20368227edb9566e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
/**
 * Functions used in configuration forms and on user preferences pages
 */
window.Config = {};

window.configInlineParams;
window.configScriptLoaded;

/**
 * checks whether browser supports web storage
 *
 * @param {'localStorage' | 'sessionStorage'} type the type of storage i.e. localStorage or sessionStorage
 * @param {boolean} warn Wether to show a warning on error
 *
 * @return {boolean}
 */
window.Config.isStorageSupported = (type, warn = false) => {
    try {
        window[type].setItem('PMATest', 'test');
        // Check whether key-value pair was set successfully
        if (window[type].getItem('PMATest') === 'test') {
            // Supported, remove test variable from storage
            window[type].removeItem('PMATest');
            return true;
        }
    } catch (error) {
        // Not supported
        if (warn) {
            Functions.ajaxShowMessage(Messages.strNoLocalStorage, false);
        }
    }
    return false;
};

// default values for fields
window.defaultValues = {};

/**
 * Returns field type
 *
 * @param {Element} field
 *
 * @return {string}
 */
function getFieldType (field) {
    var $field = $(field);
    var tagName = $field.prop('tagName');
    if (tagName === 'INPUT') {
        return $field.attr('type');
    } else if (tagName === 'SELECT') {
        return 'select';
    } else if (tagName === 'TEXTAREA') {
        return 'text';
    }
    return '';
}

/**
 * Enables or disables the "restore default value" button
 *
 * @param {Element} field
 * @param {boolean} display
 *
 * @return {void}
 */
function setRestoreDefaultBtn (field, display) {
    var $el = $(field).closest('td').find('.restore-default img');
    $el[display ? 'show' : 'hide']();
}

/**
 * Marks field depending on its value (system default or custom)
 *
 * @param {Element | JQuery<Element>} field
 *
 * @return {void}
 */
function markField (field) {
    var $field = $(field);
    var type = getFieldType($field);
    var isDefault = checkFieldDefault($field, type);

    // checkboxes uses parent <span> for marking
    var $fieldMarker = (type === 'checkbox') ? $field.parent() : $field;
    setRestoreDefaultBtn($field, ! isDefault);
    $fieldMarker[isDefault ? 'removeClass' : 'addClass']('custom');
}

/**
 * Sets field value
 *
 * value must be of type:
 * o undefined (omitted) - restore default value (form default, not PMA default)
 * o String - if field_type is 'text'
 * o boolean - if field_type is 'checkbox'
 * o Array of values - if field_type is 'select'
 *
 * @param {Element} field
 * @param {string}  fieldType see {@link #getFieldType}
 * @param {string | boolean}  value
 */
function setFieldValue (field, fieldType, value) {
    var $field = $(field);
    switch (fieldType) {
    case 'text':
    case 'number':
        $field.val(value);
        break;
    case 'checkbox':
        $field.prop('checked', value);
        break;
    case 'select':
        var options = $field.prop('options');
        var i;
        var imax = options.length;
        for (i = 0; i < imax; i++) {
            options[i].selected = (value.indexOf(options[i].value) !== -1);
        }
        break;
    }
    markField($field);
}

/**
 * Gets field value
 *
 * Will return one of:
 * o String - if type is 'text'
 * o boolean - if type is 'checkbox'
 * o Array of values - if type is 'select'
 *
 * @param {Element} field
 * @param {string}  fieldType returned by {@link #getFieldType}
 *
 * @return {boolean | string | string[] | null}
 */
function getFieldValue (field, fieldType) {
    var $field = $(field);
    switch (fieldType) {
    case 'text':
    case 'number':
        return $field.prop('value');
    case 'checkbox':
        return $field.prop('checked');
    case 'select':
        var options = $field.prop('options');
        var i;
        var imax = options.length;
        var items = [];
        for (i = 0; i < imax; i++) {
            if (options[i].selected) {
                items.push(options[i].value);
            }
        }
        return items;
    }
    return null;
}

/**
 * Returns values for all fields in fieldsets
 *
 * @return {object}
 */
window.Config.getAllValues = () => {
    var $elements = $('fieldset input, fieldset select, fieldset textarea');
    var values = {};
    var type;
    var value;
    for (var i = 0; i < $elements.length; i++) {
        type = getFieldType($elements[i]);
        value = getFieldValue($elements[i], type);
        if (typeof value !== 'undefined') {
            // we only have single selects, fatten array
            if (type === 'select') {
                value = value[0];
            }
            values[$elements[i].name] = value;
        }
    }
    return values;
};

/**
 * Checks whether field has its default value
 *
 * @param {Element} field
 * @param {string}  type
 *
 * @return {boolean}
 */
function checkFieldDefault (field, type) {
    var $field = $(field);
    var fieldId = $field.attr('id');
    if (typeof window.defaultValues[fieldId] === 'undefined') {
        return true;
    }
    var isDefault = true;
    var currentValue = getFieldValue($field, type);
    if (type !== 'select') {
        isDefault = currentValue === window.defaultValues[fieldId];
    } else {
        // compare arrays, will work for our representation of select values
        if (currentValue.length !== window.defaultValues[fieldId].length) {
            isDefault = false;
        } else {
            for (var i = 0; i < currentValue.length; i++) {
                if (currentValue[i] !== window.defaultValues[fieldId][i]) {
                    isDefault = false;
                    break;
                }
            }
        }
    }
    return isDefault;
}

/**
 * Returns element's id prefix
 * @param {Element} element
 *
 * @return {string}
 */
window.Config.getIdPrefix = function (element) {
    return $(element).attr('id').replace(/[^-]+$/, '');
};

// ------------------------------------------------------------------
// Form validation and field operations
//

// form validator assignments
let validate = {};

// form validator list
window.validators = {
    // regexp: numeric value
    regExpNumeric: /^[0-9]+$/,
    // regexp: extract parts from PCRE expression
    regExpPcreExtract: /(.)(.*)\1(.*)?/,
    /**
     * Validates positive number
     *
     * @param {boolean} isKeyUp
     *
     * @return {boolean}
     */
    validatePositiveNumber: function (isKeyUp) {
        if (isKeyUp && this.value === '') {
            return true;
        }
        var result = this.value !== '0' && window.validators.regExpNumeric.test(this.value);
        return result ? true : Messages.error_nan_p;
    },
    /**
     * Validates non-negative number
     *
     * @param {boolean} isKeyUp
     *
     * @return {boolean}
     */
    validateNonNegativeNumber: function (isKeyUp) {
        if (isKeyUp && this.value === '') {
            return true;
        }
        var result = window.validators.regExpNumeric.test(this.value);
        return result ? true : Messages.error_nan_nneg;
    },
    /**
     * Validates port number
     *
     * @return {true|string}
     */
    validatePortNumber: function () {
        if (this.value === '') {
            return true;
        }
        var result = window.validators.regExpNumeric.test(this.value) && this.value !== '0';
        return result && this.value <= 65535 ? true : Messages.error_incorrect_port;
    },
    /**
     * Validates value according to given regular expression
     *
     * @param {boolean} isKeyUp
     * @param {string}  regexp
     *
     * @return {true|string}
     */
    validateByRegex: function (isKeyUp, regexp) {
        if (isKeyUp && this.value === '') {
            return true;
        }
        // convert PCRE regexp
        var parts = regexp.match(window.validators.regExpPcreExtract);
        var valid = this.value.match(new RegExp(parts[2], parts[3])) !== null;
        return valid ? true : Messages.error_invalid_value;
    },
    /**
     * Validates upper bound for numeric inputs
     *
     * @param {boolean} isKeyUp
     * @param {number} maxValue
     *
     * @return {true|string}
     */
    validateUpperBound: function (isKeyUp, maxValue) {
        var val = parseInt(this.value, 10);
        if (isNaN(val)) {
            return true;
        }
        return val <= maxValue ? true : Functions.sprintf(Messages.error_value_lte, maxValue);
    },
    // field validators
    field: {},
    // fieldset validators
    fieldset: {}
};

/**
 * Registers validator for given field
 *
 * @param {string}  id       field id
 * @param {string}  type     validator (key in validators object)
 * @param {boolean} onKeyUp  whether fire on key up
 * @param {Array}   params   validation function parameters
 */
window.Config.registerFieldValidator = (id, type, onKeyUp, params) => {
    if (typeof window.validators[type] === 'undefined') {
        return;
    }
    if (typeof validate[id] === 'undefined') {
        validate[id] = [];
    }
    if (validate[id].length === 0) {
        validate[id].push([type, params, onKeyUp]);
    }
};

/**
 * Returns validation functions associated with form field
 *
 * @param {String}  fieldId     form field id
 * @param {boolean} onKeyUpOnly see registerFieldValidator
 *
 * @return {any[]} of [function, parameters to be passed to function]
 */
function getFieldValidators (fieldId, onKeyUpOnly) {
    // look for field bound validator
    var name = fieldId && fieldId.match(/[^-]+$/)[0];
    if (typeof window.validators.field[name] !== 'undefined') {
        return [[window.validators.field[name], null]];
    }

    // look for registered validators
    var functions = [];
    if (typeof validate[fieldId] !== 'undefined') {
        // validate[field_id]: array of [type, params, onKeyUp]
        for (var i = 0, imax = validate[fieldId].length; i < imax; i++) {
            if (onKeyUpOnly && ! validate[fieldId][i][2]) {
                continue;
            }
            functions.push([window.validators[validate[fieldId][i][0]], validate[fieldId][i][1]]);
        }
    }

    return functions;
}

/**
 * Displays errors for given form fields
 *
 * WARNING: created DOM elements must be identical with the ones made by
 * PhpMyAdmin\Config\FormDisplayTemplate::displayInput()!
 *
 * @param {object} errorList list of errors in the form {field id: error array}
 */
window.Config.displayErrors = function (errorList) {
    var tempIsEmpty = function (item) {
        return item !== '';
    };

    for (var fieldId in errorList) {
        var errors = errorList[fieldId];
        var $field = $('#' + fieldId);
        var isFieldset = $field.attr('tagName') === 'FIELDSET';
        var $errorCnt;
        if (isFieldset) {
            $errorCnt = $field.find('dl.errors');
        } else {
            $errorCnt = $field.siblings('.inline_errors');
        }

        // remove empty errors (used to clear error list)
        errors = $.grep(errors, tempIsEmpty);

        // CSS error class
        if (! isFieldset) {
            // checkboxes uses parent <span> for marking
            var $fieldMarker = ($field.attr('type') === 'checkbox') ? $field.parent() : $field;
            $fieldMarker[errors.length ? 'addClass' : 'removeClass']('field-error');
        }

        if (errors.length) {
            // if error container doesn't exist, create it
            if ($errorCnt.length === 0) {
                if (isFieldset) {
                    $errorCnt = $('<dl class="errors"></dl>');
                    $field.find('table').before($errorCnt);
                } else {
                    $errorCnt = $('<dl class="inline_errors"></dl>');
                    $field.closest('td').append($errorCnt);
                }
            }

            var html = '';
            for (var i = 0, imax = errors.length; i < imax; i++) {
                html += '<dd>' + errors[i] + '</dd>';
            }
            $errorCnt.html(html);
        } else if ($errorCnt !== null) {
            // remove useless error container
            $errorCnt.remove();
        }
    }
};

/**
 * Validates fields and fieldsets and call displayError function as required
 */
function setDisplayError () {
    var elements = $('.optbox input[id], .optbox select[id], .optbox textarea[id]');
    // run all field validators
    var errors = {};
    for (var i = 0; i < elements.length; i++) {
        validateField(elements[i], false, errors);
    }
    // run all fieldset validators
    $('fieldset.optbox').each(function () {
        validateFieldset(this, false, errors);
    });
    window.Config.displayErrors(errors);
}

/**
 * Validates fieldset and puts errors in 'errors' object
 *
 * @param {Element} fieldset
 * @param {boolean} isKeyUp
 * @param {object}  errors
 */
function validateFieldset (fieldset, isKeyUp, errors) {
    var $fieldset = $(fieldset);
    if ($fieldset.length && typeof window.validators.fieldset[$fieldset.attr('id')] !== 'undefined') {
        var fieldsetErrors = window.validators.fieldset[$fieldset.attr('id')].apply($fieldset[0], [isKeyUp]);
        for (var fieldId in fieldsetErrors) {
            if (typeof errors[fieldId] === 'undefined') {
                errors[fieldId] = [];
            }
            if (typeof fieldsetErrors[fieldId] === 'string') {
                fieldsetErrors[fieldId] = [fieldsetErrors[fieldId]];
            }
            $.merge(errors[fieldId], fieldsetErrors[fieldId]);
        }
    }
}

/**
 * Validates form field and puts errors in 'errors' object
 *
 * @param {Element} field
 * @param {boolean} isKeyUp
 * @param {object}  errors
 */
function validateField (field, isKeyUp, errors) {
    var args;
    var result;
    var $field = $(field);
    var fieldId = $field.attr('id');
    errors[fieldId] = [];
    var functions = getFieldValidators(fieldId, isKeyUp);
    for (var i = 0; i < functions.length; i++) {
        if (typeof functions[i][1] !== 'undefined' && functions[i][1] !== null) {
            args = functions[i][1].slice(0);
        } else {
            args = [];
        }
        args.unshift(isKeyUp);
        result = functions[i][0].apply($field[0], args);
        if (result !== true) {
            if (typeof result === 'string') {
                result = [result];
            }
            $.merge(errors[fieldId], result);
        }
    }
}

/**
 * Validates form field and parent fieldset
 *
 * @param {Element} field
 * @param {boolean} isKeyUp
 */
function validateFieldAndFieldset (field, isKeyUp) {
    var $field = $(field);
    var errors = {};
    validateField($field, isKeyUp, errors);
    validateFieldset($field.closest('fieldset.optbox'), isKeyUp, errors);
    window.Config.displayErrors(errors);
}

window.Config.loadInlineConfig = () => {
    if (! Array.isArray(window.configInlineParams)) {
        return;
    }
    for (var i = 0; i < window.configInlineParams.length; ++i) {
        if (typeof window.configInlineParams[i] === 'function') {
            window.configInlineParams[i]();
        }
    }
};

window.Config.setupValidation = function () {
    validate = {};
    window.configScriptLoaded = true;
    if (window.configScriptLoaded && typeof window.configInlineParams !== 'undefined') {
        window.Config.loadInlineConfig();
    }
    // register validators and mark custom values
    var $elements = $('.optbox input[id], .optbox select[id], .optbox textarea[id]');
    $elements.each(function () {
        markField(this);
        var $el = $(this);
        $el.on('change', function () {
            validateFieldAndFieldset(this, false);
            markField(this);
        });
        var tagName = $el.attr('tagName');
        // text fields can be validated after each change
        if (tagName === 'INPUT' && $el.attr('type') === 'text') {
            $el.on('keyup', function () {
                validateFieldAndFieldset($el, true);
                markField($el);
            });
        }
        // disable textarea spellcheck
        if (tagName === 'TEXTAREA') {
            $el.attr('spellcheck', false);
        }
    });

    // check whether we've refreshed a page and browser remembered modified
    // form values
    var $checkPageRefresh = $('#check_page_refresh');
    if ($checkPageRefresh.length === 0 || $checkPageRefresh.val() === '1') {
        // run all field validators
        var errors = {};
        for (var i = 0; i < $elements.length; i++) {
            validateField($elements[i], false, errors);
        }
        // run all fieldset validators
        $('fieldset.optbox').each(function () {
            validateFieldset(this, false, errors);
        });

        window.Config.displayErrors(errors);
    } else if ($checkPageRefresh) {
        $checkPageRefresh.val('1');
    }
};

//
// END: Form validation and field operations
// ------------------------------------------------------------------

function adjustPrefsNotification () {
    var $prefsAutoLoad = $('#prefs_autoload');
    var $tableNameControl = $('#table_name_col_no');
    var $prefsAutoShowing = ($prefsAutoLoad.css('display') !== 'none');

    if ($prefsAutoShowing && $tableNameControl.length) {
        $tableNameControl.css('top', '55px');
    }
}

// ------------------------------------------------------------------
// "Restore default" and "set value" buttons
//

/**
 * Restores field's default value
 *
 * @param {string} fieldId
 *
 * @return {void}
 */
function restoreField (fieldId) {
    var $field = $('#' + fieldId);
    if ($field.length === 0 || window.defaultValues[fieldId] === undefined) {
        return;
    }
    setFieldValue($field, getFieldType($field), window.defaultValues[fieldId]);
}

window.Config.setupRestoreField = function () {
    $('div.tab-content')
        .on('mouseenter', '.restore-default, .set-value', function () {
            $(this).css('opacity', 1);
        })
        .on('mouseleave', '.restore-default, .set-value', function () {
            $(this).css('opacity', 0.25);
        })
        .on('click', '.restore-default, .set-value', function (e) {
            e.preventDefault();
            var href = $(this).attr('href');
            var fieldSel;
            if ($(this).hasClass('restore-default')) {
                fieldSel = href;
                restoreField(fieldSel.substring(1));
            } else {
                fieldSel = href.match(/^[^=]+/)[0];
                var value = href.match(/=(.+)$/)[1];
                setFieldValue($(fieldSel), 'text', value);
            }
            $(fieldSel).trigger('change');
        })
        .find('.restore-default, .set-value')
        // inline-block for IE so opacity inheritance works
        .css({ display: 'inline-block', opacity: 0.25 });
};

//
// END: "Restore default" and "set value" buttons
// ------------------------------------------------------------------

/**
 * Saves user preferences to localStorage
 *
 * @param {Element} form
 */
function savePrefsToLocalStorage (form) {
    var $form = $(form);
    var submit = $form.find('input[type=submit]');
    submit.prop('disabled', true);
    $.ajax({
        url: 'index.php?route=/preferences/manage',
        cache: false,
        type: 'POST',
        data: {
            'ajax_request': true,
            'server': window.CommonParams.get('server'),
            'submit_get_json': true
        },
        success: function (data) {
            if (typeof data !== 'undefined' && data.success === true) {
                window.localStorage.config = data.prefs;
                window.localStorage.configMtime = data.mtime;
                window.localStorage.configMtimeLocal = (new Date()).toUTCString();
                updatePrefsDate();
                $('div.localStorage-empty').hide();
                $('div.localStorage-exists').show();
                var group = $form.parent('.card-body');
                group.css('height', group.height() + 'px');
                $form.hide('fast');
                $form.prev('.click-hide-message').show('fast');
            } else {
                Functions.ajaxShowMessage(data.error);
            }
        },
        complete: function () {
            submit.prop('disabled', false);
        }
    });
}

/**
 * Updates preferences timestamp in Import form
 */
function updatePrefsDate () {
    var d = new Date(window.localStorage.configMtimeLocal);
    var msg = Messages.strSavedOn.replace(
        '@DATE@',
        Functions.formatDateTime(d)
    );
    $('#opts_import_local_storage').find('div.localStorage-exists').html(msg);
}

/**
 * Prepares message which informs that localStorage preferences are available and can be imported or deleted
 */
function offerPrefsAutoimport () {
    var hasConfig = (window.Config.isStorageSupported('localStorage')) && (window.localStorage.config || false);
    var $cnt = $('#prefs_autoload');
    if (! $cnt.length || ! hasConfig) {
        return;
    }
    $cnt.find('a').on('click', function (e) {
        e.preventDefault();
        var $a = $(this);
        if ($a.attr('href') === '#no') {
            $cnt.remove();
            $.post('index.php', {
                'server': window.CommonParams.get('server'),
                'prefs_autoload': 'hide'
            }, null, 'html');
            return;
        } else if ($a.attr('href') === '#delete') {
            $cnt.remove();
            localStorage.clear();
            $.post('index.php', {
                'server': window.CommonParams.get('server'),
                'prefs_autoload': 'hide'
            }, null, 'html');
            return;
        }
        $cnt.find('input[name=json]').val(window.localStorage.config);
        $cnt.find('form').trigger('submit');
    });
    $cnt.show();
}

/**
 * @return {function}
 */
window.Config.off = function () {
    return function () {
        $('.optbox input[id], .optbox select[id], .optbox textarea[id]').off('change').off('keyup');
        $('.optbox input[type=button][name=submit_reset]').off('click');
        $('div.tab-content').off();
        $('#import_local_storage, #export_local_storage').off('click');
        $('form.prefs-form').off('change').off('submit');
        $(document).off('click', 'div.click-hide-message');
        $('#prefs_autoload').find('a').off('click');
    };
};

/**
 * @return {function}
 */
window.Config.on = function () {
    return function () {
        var $topmenuUpt = $('#user_prefs_tabs');
        $topmenuUpt.find('a.active').attr('rel', 'samepage');
        $topmenuUpt.find('a:not(.active)').attr('rel', 'newpage');

        window.Config.setupValidation();
        adjustPrefsNotification();

        $('.optbox input[type=button][name=submit_reset]').on('click', function () {
            var fields = $(this).closest('fieldset').find('input, select, textarea');
            for (var i = 0, imax = fields.length; i < imax; i++) {
                setFieldValue(fields[i], getFieldType(fields[i]), window.defaultValues[fields[i].id]);
            }
            setDisplayError();
        });

        window.Config.setupRestoreField();

        offerPrefsAutoimport();
        var $radios = $('#import_local_storage, #export_local_storage');
        if (! $radios.length) {
            return;
        }

        // enable JavaScript dependent fields
        $radios
            .prop('disabled', false)
            .add('#export_text_file, #import_text_file')
            .on('click', function () {
                var enableId = $(this).attr('id');
                var disableId;
                if (enableId.match(/local_storage$/)) {
                    disableId = enableId.replace(/local_storage$/, 'text_file');
                } else {
                    disableId = enableId.replace(/text_file$/, 'local_storage');
                }
                $('#opts_' + disableId).addClass('disabled').find('input').prop('disabled', true);
                $('#opts_' + enableId).removeClass('disabled').find('input').prop('disabled', false);
            });

        // detect localStorage state
        var lsSupported = window.Config.isStorageSupported('localStorage', true);
        var lsExists = lsSupported ? (window.localStorage.config || false) : false;
        $('div.localStorage-' + (lsSupported ? 'un' : '') + 'supported').hide();
        $('div.localStorage-' + (lsExists ? 'empty' : 'exists')).hide();
        if (lsExists) {
            updatePrefsDate();
        }
        $('form.prefs-form').on('change', function () {
            var $form = $(this);
            var disabled = false;
            if (! lsSupported) {
                disabled = $form.find('input[type=radio][value$=local_storage]').prop('checked');
            } else if (! lsExists && $form.attr('name') === 'prefs_import' &&
                $('#import_local_storage')[0].checked
            ) {
                disabled = true;
            }
            $form.find('input[type=submit]').prop('disabled', disabled);
        }).on('submit', function (e) {
            var $form = $(this);
            if ($form.attr('name') === 'prefs_export' && $('#export_local_storage')[0].checked) {
                e.preventDefault();
                // use AJAX to read JSON settings and save them
                savePrefsToLocalStorage($form);
            } else if ($form.attr('name') === 'prefs_import' && $('#import_local_storage')[0].checked) {
                // set 'json' input and submit form
                $form.find('input[name=json]').val(window.localStorage.config);
            }
        });

        $(document).on('click', 'div.click-hide-message', function () {
            $(this)
                .hide()
                .parent('.card-body')
                .css('height', '')
                .next('form')
                .show();
        });
    };
};