/*!
 * # Fomantic-UI - Popup
 * https://github.com/fomantic/Fomantic-UI/
 *
 *
 * Released under the MIT license
 * https://opensource.org/licenses/MIT
 *
 */

(function ($, window, document) {
    'use strict';

    function isFunction(obj) {
        return typeof obj === 'function' && typeof obj.nodeType !== 'number';
    }

    window = window !== undefined && window.Math === Math
        ? window
        : globalThis;

    $.fn.popup = function (...args) {
        const $allModules = $(this);
        const $document = $(document);
        const $window = $(window);
        const $body = $('body');

        const clickEvent = 'ontouchstart' in document.documentElement
            ? 'touchstart'
            : 'click';

        let time = Date.now();
        let performance = [];

        const parameters = args[0];
        const methodInvoked = typeof parameters === 'string';
        const queryArguments = args.slice(1);
        const contextCheck = function (context, win) {
            let $context;
            if ([window, document].includes(context)) {
                $context = $(context);
            } else {
                $context = $(win.document).find(context);
                if ($context.length === 0) {
                    $context = win.frameElement ? contextCheck(context, win.parent) : $body;
                }
            }

            return $context;
        };

        let returnedValue;
        $allModules.each(function () {
            const settings = $.isPlainObject(parameters)
                ? $.extend(true, {}, $.fn.popup.settings, parameters)
                : $.extend({}, $.fn.popup.settings);

            const selector = settings.selector;
            const className = settings.className;
            const error = settings.error;
            const metadata = settings.metadata;
            const namespace = settings.namespace;

            const eventNamespace = '.' + settings.namespace;
            const moduleNamespace = 'module-' + namespace;

            const $module = $(this);
            const $context = contextCheck(settings.context, window);
            const $scrollContext = contextCheck(settings.scrollContext, window);
            const $boundary = contextCheck(settings.boundary, window);
            const $target = settings.target ? contextCheck(settings.target, window) : $module;

            let $popup;
            let $offsetParent;

            let searchDepth = 0;
            let triedPositions = false;
            let openedWithTouch = false;

            const element = this;
            let instance = $module.data(moduleNamespace);

            let documentObserver;
            let elementNamespace;
            let id;

            const module = {

                // binds events
                initialize: function () {
                    module.debug('Initializing', $module);
                    module.createID();
                    module.bind.events();
                    if (!module.exists() && settings.preserve) {
                        module.create();
                    }
                    if (settings.observeChanges) {
                        module.observeChanges();
                    }
                    module.instantiate();
                },

                instantiate: function () {
                    module.verbose('Storing instance', module);
                    instance = module;
                    $module
                        .data(moduleNamespace, instance);
                },

                observeChanges: function () {
                    documentObserver = new MutationObserver(module.event.documentChanged);
                    documentObserver.observe(document, {
                        childList: true,
                        subtree: true,
                    });
                    module.debug('Setting up mutation observer', documentObserver);
                },

                refresh: function () {
                    if (settings.popup) {
                        $popup = $document.find(settings.popup).eq(0);
                    } else if (settings.inline) {
                        $popup = $target.nextAll(selector.popup).eq(0);
                        settings.popup = $popup;
                    }
                    if (settings.popup) {
                        module.set.invisible();
                        $offsetParent = module.get.offsetParent();
                        module.remove.invisible();
                        if (settings.movePopup && module.has.popup() && module.get.offsetParent($popup)[0] !== $offsetParent[0]) {
                            module.debug('Moving popup to the same offset parent as target');
                            $popup
                                .detach()
                                .appendTo($offsetParent);
                        }
                    } else {
                        $offsetParent = settings.inline
                            ? module.get.offsetParent($target)
                            : (module.has.popup()
                                ? module.get.offsetParent($popup)
                                : $body);
                    }
                    if ($offsetParent.is('html') && $offsetParent[0] !== $body[0]) {
                        module.debug('Setting page as offset parent');
                        $offsetParent = $body;
                    }
                    if (module.get.variation()) {
                        module.set.variation();
                    }
                },

                reposition: function () {
                    module.refresh();
                    module.set.position();
                },

                destroy: function () {
                    module.debug('Destroying previous module');
                    if (documentObserver) {
                        documentObserver.disconnect();
                    }
                    // remove the element only if was created dynamically
                    if ($popup && !settings.preserve) {
                        module.removePopup();
                    }
                    // clear all timeouts
                    clearTimeout(module.hideTimer);
                    clearTimeout(module.showTimer);
                    // remove events
                    module.unbind.close();
                    module.unbind.events();
                    $module
                        .removeData(moduleNamespace);
                },

                event: {
                    start: function (event) {
                        const delay = $.isPlainObject(settings.delay)
                            ? settings.delay.show
                            : settings.delay;
                        clearTimeout(module.hideTimer);
                        if (!openedWithTouch || (openedWithTouch && settings.addTouchEvents)) {
                            module.showTimer = setTimeout(function () {
                                module.show();
                            }, delay);
                        }
                    },
                    end: function () {
                        const delay = $.isPlainObject(settings.delay)
                            ? settings.delay.hide
                            : settings.delay;
                        clearTimeout(module.showTimer);
                        module.hideTimer = setTimeout(function () {
                            module.hide();
                        }, delay);
                    },
                    touchstart: function (event) {
                        openedWithTouch = true;
                        if (settings.addTouchEvents) {
                            module.show();
                        }
                    },
                    resize: function () {
                        if (module.is.visible()) {
                            module.set.position();
                        }
                    },
                    documentChanged: function (mutations) {
                        for (const mutation of mutations) {
                            for (const node of mutation.removedNodes) {
                                if (node === element || $(node).find(element).length > 0) {
                                    module.debug('Element removed from DOM, tearing down events');
                                    module.destroy();
                                }
                            }
                        }
                    },
                    hideGracefully: function (event) {
                        const $target = $(event.target);
                        const isInDOM = document.documentElement.contains(event.target);
                        const inPopup = $target.closest(selector.popup).length > 0;
                        // don't close on clicks inside popup
                        if (event && !inPopup && isInDOM) {
                            module.debug('Click occurred outside popup hiding popup');
                            module.hide();
                        } else {
                            module.debug('Click was inside popup, keeping popup open');
                        }
                    },
                },

                // generates popup html from metadata
                create: function () {
                    const targetSibling = $target.next(selector.popup);
                    const contentFallback = !settings.popup && targetSibling.length === 0 ? $module.attr('title') : false;
                    let html = module.get.html();
                    const title = module.get.title();
                    const content = module.get.content(contentFallback);

                    if (html || content || title) {
                        module.debug('Creating pop-up html');
                        if (!html) {
                            html = settings.templates.popup({
                                title: title,
                                content: content,
                            });
                        }
                        $popup = $('<div/>')
                            .addClass(className.popup)
                            .data(metadata.activator, $module)
                            .html(html);
                        if (settings.inline) {
                            module.verbose('Inserting popup element inline', $popup);
                            $popup
                                .insertAfter($module);
                        } else {
                            module.verbose('Appending popup element to body', $popup);
                            $popup
                                .appendTo($context);
                        }
                        module.refresh();
                        module.set.variation();

                        if (settings.hoverable) {
                            module.bind.popup();
                        }
                        settings.onCreate.call($popup, element);
                    } else if (settings.popup) {
                        $document.find(settings.popup).data(metadata.activator, $module);
                        module.verbose('Used popup specified in settings');
                        module.refresh();
                        if (settings.hoverable) {
                            module.bind.popup();
                        }
                    } else if (targetSibling.length > 0) {
                        module.verbose('Pre-existing popup found');
                        settings.inline = true;
                        settings.popup = targetSibling.data(metadata.activator, $module);
                        module.refresh();
                        if (settings.hoverable) {
                            module.bind.popup();
                        }
                    } else {
                        module.debug('No content specified skipping display', element);
                    }
                },

                createID: function () {
                    id = (Math.random().toString(16) + '000000000').slice(2, 10);
                    elementNamespace = '.' + id;
                    module.verbose('Creating unique id for element', id);
                },

                // determines popup state
                toggle: function () {
                    module.debug('Toggling pop-up');
                    if (module.is.hidden()) {
                        module.debug('Popup is hidden, showing pop-up');
                        module.unbind.close();
                        module.show();
                    } else {
                        module.debug('Popup is visible, hiding pop-up');
                        module.hide();
                    }
                },

                show: function (callback = function () {}) {
                    module.debug('Showing pop-up', settings.transition);
                    if (module.is.hidden() && !(module.is.active() && module.is.dropdown())) {
                        if (!module.exists()) {
                            module.create();
                        }
                        if (settings.onShow.call($popup, element) === false) {
                            module.debug('onShow callback returned false, cancelling popup animation');

                            return;
                        }
                        if (!settings.preserve && !settings.popup) {
                            module.refresh();
                        }
                        if ($popup && module.set.position()) {
                            module.save.conditions();
                            if (settings.exclusive) {
                                module.hideAll();
                            }
                            module.animate.show(callback);
                        }
                    }
                },

                hide: function (callback = function () {}) {
                    if (module.is.visible() || module.is.animating()) {
                        if (settings.onHide.call($popup, element) === false) {
                            module.debug('onHide callback returned false, cancelling popup animation');

                            return;
                        }
                        module.remove.visible();
                        module.unbind.close();
                        module.restore.conditions();
                        module.animate.hide(callback);
                    }
                },

                hideAll: function () {
                    $document.find(selector.popup)
                        .filter('.' + className.popupVisible)
                        .each(function () {
                            $(this)
                                .data(metadata.activator)
                                .popup('hide');
                        });
                },
                exists: function () {
                    if (!$popup) {
                        return false;
                    }
                    if (settings.inline || settings.popup) {
                        return module.has.popup();
                    }

                    return $popup.closest($context).length > 0;
                },

                removePopup: function () {
                    if (module.has.popup() && !settings.popup) {
                        module.debug('Removing popup', $popup);
                        $popup.remove();
                        $popup = undefined;
                        settings.onRemove.call($popup, element);
                    }
                },

                save: {
                    conditions: function () {
                        module.cache = {
                            title: $module.attr('title'),
                        };
                        if (module.cache.title) {
                            $module.removeAttr('title');
                        }
                        module.verbose('Saving original attributes', module.cache.title);
                    },
                },
                restore: {
                    conditions: function () {
                        if (module.cache && module.cache.title) {
                            $module.attr('title', module.cache.title);
                            module.verbose('Restoring original attributes', module.cache.title);
                        }

                        return true;
                    },
                },
                supports: {
                    svg: function () {
                        return typeof SVGGraphicsElement !== 'undefined';
                    },
                },
                animate: {
                    show: function (callback) {
                        callback = isFunction(callback) ? callback : function () {};
                        if (settings.transition && module.can.useElement('transition')) {
                            module.set.visible();
                            $popup
                                .transition({
                                    animation: (settings.transition.showMethod || settings.transition) + ' in',
                                    queue: false,
                                    debug: settings.debug,
                                    verbose: settings.verbose,
                                    silent: settings.silent,
                                    duration: settings.transition.showDuration || settings.duration,
                                    onComplete: function () {
                                        module.bind.close();
                                        callback.call($popup, element);
                                        settings.onVisible.call($popup, element);
                                    },
                                });
                        }
                    },
                    hide: function (callback) {
                        callback = isFunction(callback) ? callback : function () {};
                        module.debug('Hiding pop-up');
                        if (settings.transition && $.fn.transition !== undefined) {
                            $popup
                                .transition({
                                    animation: (settings.transition.hideMethod || settings.transition) + ' out',
                                    queue: false,
                                    duration: settings.transition.hideDuration || settings.duration,
                                    debug: settings.debug,
                                    verbose: settings.verbose,
                                    silent: settings.silent,
                                    onComplete: function () {
                                        module.reset();
                                        callback.call($popup, element);
                                        settings.onHidden.call($popup, element);
                                    },
                                });
                        } else {
                            module.error(error.noTransition);
                        }
                    },
                },

                change: {
                    content: function (html) {
                        $popup.html(html);
                    },
                },

                get: {
                    html: function () {
                        $module.removeData(metadata.html);

                        return $module.data(metadata.html) || settings.html;
                    },
                    title: function () {
                        $module.removeData(metadata.title);

                        return $module.data(metadata.title) || settings.title;
                    },
                    content: function (fallback) {
                        $module.removeData(metadata.content);

                        return $module.data(metadata.content) || settings.content || fallback;
                    },
                    variation: function () {
                        $module.removeData(metadata.variation);

                        return $module.data(metadata.variation) || settings.variation;
                    },
                    popup: function () {
                        return $popup;
                    },
                    popupOffset: function () {
                        return $popup.offset();
                    },
                    calculations: function () {
                        const $popupOffsetParent = module.get.offsetParent($popup);
                        const targetElement = $target[0];
                        const isWindowEl = $boundary[0] === window;
                        const targetOffset = $target.offset();
                        const parentOffset = settings.inline || (settings.popup && settings.movePopup)
                            ? $target.offsetParent().offset()
                            : { top: 0, left: 0 };
                        const screenPosition = isWindowEl
                            ? { top: 0, left: 0 }
                            : $boundary.offset();
                        const scroll = isWindowEl
                            ? { top: $window.scrollTop(), left: $window.scrollLeft() }
                            : { top: 0, left: 0 };
                        const calculations = {
                            // element which is launching popup
                            target: {
                                element: $target[0],
                                width: $target.outerWidth(),
                                height: $target.outerHeight(),
                                top: targetOffset.top - parentOffset.top,
                                left: targetOffset.left - parentOffset.left,
                                margin: {},
                            },
                            // popup itself
                            popup: {
                                width: $popup.outerWidth(),
                                height: $popup.outerHeight(),
                            },
                            // offset container (or 3d context)
                            parent: {
                                width: $offsetParent.outerWidth(),
                                height: $offsetParent.outerHeight(),
                            },
                            // screen boundaries
                            screen: {
                                top: screenPosition.top,
                                left: screenPosition.left,
                                scroll: {
                                    top: scroll.top,
                                    left: scroll.left,
                                },
                                width: $boundary.width(),
                                height: $boundary.height(),
                            },
                        };

                        // if popup offset context is different from target, then adjust calculations
                        if ($popupOffsetParent[0] !== $offsetParent[0]) {
                            const popupOffset = $popupOffsetParent.offset();
                            calculations.target.top -= popupOffset.top;
                            calculations.target.left -= popupOffset.left;
                            calculations.parent.width = $popupOffsetParent.outerWidth();
                            calculations.parent.height = $popupOffsetParent.outerHeight();
                        }

                        // add in container calcs if fluid
                        if (settings.setFluidWidth && module.is.fluid()) {
                            calculations.container = {
                                width: $popup.parent().outerWidth(),
                            };
                            calculations.popup.width = calculations.container.width;
                        }

                        // add in margins if inline
                        calculations.target.margin.top = settings.inline
                            ? Number.parseInt(window.getComputedStyle(targetElement).getPropertyValue('margin-top'), 10)
                            : 0;
                        calculations.target.margin.left = settings.inline
                            ? (module.is.rtl()
                                ? Number.parseInt(window.getComputedStyle(targetElement).getPropertyValue('margin-right'), 10)
                                : Number.parseInt(window.getComputedStyle(targetElement).getPropertyValue('margin-left'), 10))
                            : 0;
                        // calculate screen boundaries
                        const screen = calculations.screen;
                        calculations.boundary = {
                            top: screen.top + screen.scroll.top,
                            bottom: screen.top + screen.scroll.top + screen.height,
                            left: screen.left + screen.scroll.left,
                            right: screen.left + screen.scroll.left + screen.width,
                        };

                        return calculations;
                    },
                    id: function () {
                        return id;
                    },
                    startEvent: function () {
                        if (settings.on === 'hover') {
                            return 'mouseenter';
                        }
                        if (settings.on === 'focus') {
                            return 'focus';
                        }

                        return false;
                    },
                    scrollEvent: function () {
                        return 'scroll';
                    },
                    endEvent: function () {
                        if (settings.on === 'hover') {
                            return 'mouseleave';
                        }
                        if (settings.on === 'focus') {
                            return 'blur';
                        }

                        return false;
                    },
                    distanceFromBoundary: function (offset, calculations = module.get.calculations()) {
                        let distanceFromBoundary = {};

                        // shorthand
                        const popup = calculations.popup;
                        const boundary = calculations.boundary;

                        if (offset) {
                            distanceFromBoundary = {
                                top: offset.top - boundary.top,
                                left: offset.left - boundary.left,
                                right: boundary.right - (offset.left + popup.width),
                                bottom: boundary.bottom - (offset.top + popup.height),
                            };
                            module.verbose('Distance from boundaries determined', offset, distanceFromBoundary);
                        }

                        return distanceFromBoundary;
                    },
                    offsetParent: function ($element) {
                        const element = $element !== undefined
                            ? $element[0]
                            : $target[0];
                        let parentNode = element.parentNode;
                        let $node = $(parentNode);
                        if (parentNode) {
                            let is2D = $node.css('transform') === 'none';
                            let isStatic = $node.css('position') === 'static';
                            let isBody = $node.is('body');
                            while (parentNode && !isBody && isStatic && is2D) {
                                parentNode = parentNode.parentNode;
                                $node = $(parentNode);
                                is2D = $node.css('transform') === 'none';
                                isStatic = $node.css('position') === 'static';
                                isBody = $node.is('body');
                            }
                        }

                        return $node && $node.length > 0
                            ? $node
                            : $();
                    },
                    positions: function () {
                        return {
                            'top left': false,
                            'top center': false,
                            'top right': false,
                            'bottom left': false,
                            'bottom center': false,
                            'bottom right': false,
                            'left center': false,
                            'right center': false,
                        };
                    },
                    nextPosition: function (position) {
                        const positions = position.split(' ');
                        const verticalPosition = positions[0];
                        const horizontalPosition = positions[1];
                        const opposite = {
                            top: 'bottom',
                            bottom: 'top',
                            left: 'right',
                            right: 'left',
                        };
                        const adjacent = {
                            left: 'center',
                            center: 'right',
                            right: 'left',
                        };
                        const backup = {
                            'top left': 'top center',
                            'top center': 'top right',
                            'top right': 'right center',
                            'right center': 'bottom right',
                            'bottom right': 'bottom center',
                            'bottom center': 'bottom left',
                            'bottom left': 'left center',
                            'left center': 'top left',
                        };
                        const adjacentsAvailable = verticalPosition === 'top' || verticalPosition === 'bottom';
                        let oppositeTried = false;
                        let adjacentTried = false;
                        let nextPosition = false;
                        if (!triedPositions) {
                            module.verbose('All available positions available');
                            triedPositions = module.get.positions();
                        }

                        module.debug('Recording last position tried', position);
                        triedPositions[position] = true;

                        if (settings.prefer === 'opposite') {
                            nextPosition = [opposite[verticalPosition], horizontalPosition];
                            nextPosition = nextPosition.join(' ');
                            oppositeTried = triedPositions[nextPosition] === true;
                            module.debug('Trying opposite strategy', nextPosition);
                        }
                        if ((settings.prefer === 'adjacent') && adjacentsAvailable) {
                            nextPosition = [verticalPosition, adjacent[horizontalPosition]];
                            nextPosition = nextPosition.join(' ');
                            adjacentTried = triedPositions[nextPosition] === true;
                            module.debug('Trying adjacent strategy', nextPosition);
                        }
                        if (adjacentTried || oppositeTried) {
                            module.debug('Using backup position', nextPosition);
                            nextPosition = backup[position];
                        }

                        return nextPosition;
                    },
                },

                set: {
                    position: function (position = $module.data(metadata.position) || settings.position, calculations = module.get.calculations()) {
                        // exit conditions
                        if ($target.length === 0 || $popup.length === 0) {
                            module.error(error.notFound);

                            return;
                        }
                        let offset;
                        let distanceAway;
                        let positioning;

                        offset = $module.data(metadata.offset) || settings.offset;
                        distanceAway = settings.distanceAway;

                        // shorthand
                        const target = calculations.target;
                        const popup = calculations.popup;
                        const parent = calculations.parent;

                        if (module.should.centerArrow(calculations)) {
                            module.verbose('Adjusting offset to center arrow on small target element');
                            if (position === 'top left' || position === 'bottom left') {
                                offset += target.width / 2;
                                offset -= settings.arrowPixelsFromEdge;
                            }
                            if (position === 'top right' || position === 'bottom right') {
                                offset -= target.width / 2;
                                offset += settings.arrowPixelsFromEdge;
                            }
                        }

                        if (target.width === 0 && target.height === 0 && !module.is.svg(target.element)) {
                            module.debug('Popup target is hidden, no action taken');

                            return false;
                        }

                        if (settings.inline) {
                            module.debug('Adding margin to calculation', target.margin);
                            if (position === 'left center' || position === 'right center') {
                                offset += target.margin.top;
                                distanceAway += -target.margin.left;
                            } else if (position === 'top left' || position === 'top center' || position === 'top right') {
                                offset += target.margin.left;
                                distanceAway -= target.margin.top;
                            } else {
                                offset += target.margin.left;
                                distanceAway += target.margin.top;
                            }
                        }

                        module.debug('Determining popup position from calculations', position, calculations);

                        if (module.is.rtl()) {
                            position = position.replace(/left|right/g, function (match) {
                                return match === 'left'
                                    ? 'right'
                                    : 'left';
                            });
                            module.debug('RTL: Popup position updated', position);
                        }

                        // if last attempt, use specified last resort position
                        if (searchDepth === settings.maxSearchDepth && typeof settings.lastResort === 'string') {
                            position = settings.lastResort;
                        }

                        switch (position) {
                            case 'top left': {
                                positioning = {
                                    top: 'auto',
                                    bottom: parent.height - target.top + distanceAway,
                                    left: target.left + offset,
                                    right: 'auto',
                                };

                                break;
                            }
                            case 'top center': {
                                positioning = {
                                    bottom: parent.height - target.top + distanceAway,
                                    left: target.left + (target.width / 2) - (popup.width / 2) + offset,
                                    top: 'auto',
                                    right: 'auto',
                                };

                                break;
                            }
                            case 'top right': {
                                positioning = {
                                    bottom: parent.height - target.top + distanceAway,
                                    right: parent.width - target.left - target.width - offset,
                                    top: 'auto',
                                    left: 'auto',
                                };

                                break;
                            }
                            case 'left center': {
                                positioning = {
                                    top: target.top + (target.height / 2) - (popup.height / 2) + offset,
                                    right: parent.width - target.left + distanceAway,
                                    left: 'auto',
                                    bottom: 'auto',
                                };

                                break;
                            }
                            case 'right center': {
                                positioning = {
                                    top: target.top + (target.height / 2) - (popup.height / 2) + offset,
                                    left: target.left + target.width + distanceAway,
                                    bottom: 'auto',
                                    right: 'auto',
                                };

                                break;
                            }
                            case 'bottom left': {
                                positioning = {
                                    top: target.top + target.height + distanceAway,
                                    left: target.left + offset,
                                    bottom: 'auto',
                                    right: 'auto',
                                };

                                break;
                            }
                            case 'bottom center': {
                                positioning = {
                                    top: target.top + target.height + distanceAway,
                                    left: target.left + (target.width / 2) - (popup.width / 2) + offset,
                                    bottom: 'auto',
                                    right: 'auto',
                                };

                                break;
                            }
                            case 'bottom right': {
                                positioning = {
                                    top: target.top + target.height + distanceAway,
                                    right: parent.width - target.left - target.width - offset,
                                    left: 'auto',
                                    bottom: 'auto',
                                };

                                break;
                            }
                            // no default
                        }
                        if (positioning === undefined) {
                            module.error(error.invalidPosition, position);
                        }

                        module.debug('Calculated popup positioning values', positioning);

                        // tentatively place on stage
                        $popup
                            .css(positioning)
                            .removeClass(className.position)
                            .addClass(position);
                        module.set.invisible();

                        const popupOffset = module.get.popupOffset();

                        // see if any boundaries are surpassed with this tentative position
                        const distanceFromBoundary = module.get.distanceFromBoundary(popupOffset, calculations);

                        if (!settings.forcePosition && module.is.offstage(distanceFromBoundary, position)) {
                            module.debug('Position is outside viewport', position);
                            if (searchDepth < settings.maxSearchDepth) {
                                searchDepth++;
                                position = module.get.nextPosition(position);
                                module.debug('Trying new position', position);

                                return $popup
                                    ? module.set.position(position, calculations)
                                    : false;
                            }
                            if (settings.lastResort) {
                                module.debug('No position found, showing with last position');
                            } else {
                                module.debug('Popup could not find a position to display', $popup);
                                module.error(error.cannotPlace, element);
                                module.remove.attempts();
                                module.remove.invisible();
                                module.reset();
                                settings.onUnplaceable.call($popup, element);

                                return false;
                            }
                        }
                        module.debug('Position is on stage', position);
                        module.remove.attempts();
                        module.remove.invisible();
                        if (settings.setFluidWidth && module.is.fluid()) {
                            module.set.fluidWidth(calculations);
                        }

                        return true;
                    },

                    fluidWidth: function (calculations = module.get.calculations()) {
                        module.debug('Automatically setting element width to parent width', calculations.parent.width);
                        $popup.css('width', calculations.container.width);
                    },

                    loading: function () {
                        $popup.addClass(className.loading);
                    },

                    invisible: function () {
                        $popup.addClass(className.invisible);
                    },

                    variation: function (variation = module.get.variation()) {
                        if (variation && module.has.popup()) {
                            module.verbose('Adding variation to popup', variation);
                            $popup.addClass(variation);
                        }
                    },

                    visible: function () {
                        $module.addClass(className.visible);
                    },
                },

                remove: {
                    loading: function () {
                        $popup.removeClass(className.loading);
                    },
                    invisible: function () {
                        $popup.removeClass(className.invisible);
                    },
                    variation: function (variation = module.get.variation()) {
                        if (variation) {
                            module.verbose('Removing variation', variation);
                            $popup.removeClass(variation);
                        }
                    },
                    visible: function () {
                        $module.removeClass(className.visible);
                    },
                    attempts: function () {
                        module.verbose('Resetting all searched positions');
                        searchDepth = 0;
                        triedPositions = false;
                    },
                },

                bind: {
                    events: function () {
                        module.debug('Binding popup events to module');
                        if (settings.on === 'click') {
                            $module
                                .on(clickEvent + eventNamespace, module.toggle);
                        }
                        if (settings.on === 'hover') {
                            $module
                                .on('touchstart' + eventNamespace, module.event.touchstart);
                        }
                        if (module.get.startEvent()) {
                            $module
                                .on(module.get.startEvent() + eventNamespace, module.event.start)
                                .on(module.get.endEvent() + eventNamespace, module.event.end);
                        }
                        if (settings.target) {
                            module.debug('Target set to element', $target);
                        }
                        $window.on('resize' + elementNamespace, module.event.resize);
                    },
                    popup: function () {
                        module.verbose('Allowing hover events on popup to prevent closing');
                        if ($popup && module.has.popup()) {
                            $popup
                                .on('mouseenter' + eventNamespace, module.event.start)
                                .on('mouseleave' + eventNamespace, module.event.end);
                        }
                    },
                    close: function () {
                        if (settings.hideOnScroll === true || (settings.hideOnScroll === 'auto' && settings.on !== 'click')) {
                            module.bind.closeOnScroll();
                        }
                        if (module.is.closable()) {
                            module.bind.clickaway();
                        } else if (settings.on === 'hover' && openedWithTouch) {
                            module.bind.touchClose();
                        }
                    },
                    closeOnScroll: function () {
                        module.verbose('Binding scroll close event to document');
                        $scrollContext
                            .one(module.get.scrollEvent() + elementNamespace, module.event.hideGracefully);
                    },
                    touchClose: function () {
                        module.verbose('Binding popup touchclose event to document');
                        $document
                            .on('touchstart' + elementNamespace, function (event) {
                                module.verbose('Touched away from popup');
                                module.event.hideGracefully.call(element, event);
                            });
                    },
                    clickaway: function () {
                        module.verbose('Binding popup close event to document');
                        $document
                            .on(clickEvent + elementNamespace, function (event) {
                                module.verbose('Clicked away from popup');
                                module.event.hideGracefully.call(element, event);
                            });
                    },
                },

                unbind: {
                    events: function () {
                        $window
                            .off(elementNamespace);
                        $module
                            .off(eventNamespace);
                    },
                    close: function () {
                        $document
                            .off(elementNamespace);
                        $scrollContext
                            .off(elementNamespace);
                    },
                },

                can: {
                    useElement: function (element) {
                        if ($.fn[element] !== undefined) {
                            return true;
                        }
                        module.error(error.noElement.replace('{element}', element));

                        return false;
                    },
                },

                has: {
                    popup: function () {
                        return $popup && $popup.length > 0;
                    },
                },

                should: {
                    centerArrow: function (calculations) {
                        return !module.is.basic() && calculations.target.width <= (settings.arrowPixelsFromEdge * 2);
                    },
                },

                is: {
                    closable: function () {
                        if (settings.closable === 'auto') {
                            return settings.on !== 'hover';
                        }

                        return settings.closable;
                    },
                    offstage: function (distanceFromBoundary, position) {
                        const offstage = [];
                        // return boundaries that have been surpassed
                        $.each(distanceFromBoundary, function (direction, distance) {
                            if (distance < -settings.jitter) {
                                module.debug('Position exceeds allowable distance from edge', direction, distance, position);
                                offstage.push(direction);
                            }
                        });

                        return offstage.length > 0;
                    },
                    svg: function (element) {
                        return module.supports.svg() && (element instanceof SVGGraphicsElement);
                    },
                    basic: function () {
                        return $module.hasClass(className.basic);
                    },
                    active: function () {
                        return $module.hasClass(className.active);
                    },
                    animating: function () {
                        return $popup !== undefined && $popup.hasClass(className.animating);
                    },
                    fluid: function () {
                        return $popup !== undefined && $popup.hasClass(className.fluid);
                    },
                    visible: function () {
                        return $popup !== undefined && $popup.hasClass(className.popupVisible);
                    },
                    dropdown: function () {
                        return $module.hasClass(className.dropdown);
                    },
                    hidden: function () {
                        return !module.is.visible();
                    },
                    rtl: function () {
                        return $module.attr('dir') === 'rtl' || $module.css('direction') === 'rtl' || $body.attr('dir') === 'rtl' || $body.css('direction') === 'rtl' || $context.attr('dir') === 'rtl' || $context.css('direction') === 'rtl';
                    },
                },

                reset: function () {
                    module.remove.visible();
                    if (settings.preserve) {
                        if ($.fn.transition !== undefined) {
                            $popup
                                .transition('remove transition');
                        }
                    } else {
                        module.removePopup();
                    }
                },

                setting: function (name, value) {
                    if ($.isPlainObject(name)) {
                        $.extend(true, settings, name);
                    } else if (value !== undefined) {
                        settings[name] = value;
                    } else {
                        return settings[name];
                    }
                },
                internal: function (name, value) {
                    if ($.isPlainObject(name)) {
                        $.extend(true, module, name);
                    } else if (value !== undefined) {
                        module[name] = value;
                    } else {
                        return module[name];
                    }
                },
                debug: function (...args) {
                    if (!settings.silent && settings.debug) {
                        if (settings.performance) {
                            module.performance.log(args);
                        } else {
                            module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
                            module.debug.apply(console, args);
                        }
                    }
                },
                verbose: function (...args) {
                    if (!settings.silent && settings.verbose && settings.debug) {
                        if (settings.performance) {
                            module.performance.log(args);
                        } else {
                            module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
                            module.verbose.apply(console, args);
                        }
                    }
                },
                error: function (...args) {
                    if (!settings.silent) {
                        module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
                        module.error.apply(console, args);
                    }
                },
                performance: {
                    log: function (message) {
                        let currentTime;
                        let executionTime;
                        let previousTime;
                        if (settings.performance) {
                            currentTime = Date.now();
                            previousTime = time || currentTime;
                            executionTime = currentTime - previousTime;
                            time = currentTime;
                            performance.push({
                                Name: message[0],
                                Arguments: message.slice(1),
                                Element: element,
                                'Execution Time': executionTime,
                            });
                        }
                        clearTimeout(module.performance.timer);
                        module.performance.timer = setTimeout(function () {
                            module.performance.display();
                        }, 500);
                    },
                    display: function () {
                        let title = settings.name + ':';
                        let totalTime = 0;
                        time = false;
                        clearTimeout(module.performance.timer);
                        $.each(performance, function (index, data) {
                            totalTime += data['Execution Time'];
                        });
                        title += ' ' + totalTime + 'ms';
                        if (performance.length > 0) {
                            console.groupCollapsed(title);
                            console.table(performance);
                            console.groupEnd();
                        }
                        performance = [];
                    },
                },
                invoke: function (query, passedArguments = queryArguments, context = element) {
                    let object = instance;
                    let maxDepth;
                    let found;
                    let response;
                    if (typeof query === 'string' && object !== undefined) {
                        query = query.split(/[ .]/);
                        maxDepth = query.length - 1;
                        $.each(query, function (depth, value) {
                            const camelCaseValue = depth !== maxDepth
                                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                                : query;
                            if ($.isPlainObject(object[camelCaseValue]) && (depth !== maxDepth)) {
                                object = object[camelCaseValue];
                            } else if (object[camelCaseValue] !== undefined) {
                                found = object[camelCaseValue];

                                return false;
                            } else if ($.isPlainObject(object[value]) && (depth !== maxDepth)) {
                                object = object[value];
                            } else if (object[value] !== undefined) {
                                found = object[value];

                                return false;
                            } else {
                                module.error(error.method, query);

                                return false;
                            }
                        });
                    }
                    if (isFunction(found)) {
                        response = found.apply(context, passedArguments);
                    } else if (found !== undefined) {
                        response = found;
                    }
                    if (Array.isArray(returnedValue)) {
                        returnedValue.push(response);
                    } else if (returnedValue !== undefined) {
                        returnedValue = [returnedValue, response];
                    } else if (response !== undefined) {
                        returnedValue = response;
                    }

                    return found;
                },
            };

            if (methodInvoked) {
                if (instance === undefined) {
                    module.initialize();
                }
                module.invoke(parameters);
            } else {
                if (instance !== undefined) {
                    instance.invoke('destroy');
                }
                module.initialize();
            }
        });

        return returnedValue !== undefined
            ? returnedValue
            : this;
    };

    $.fn.popup.settings = {

        name: 'Popup',

        // module settings
        silent: false,
        debug: false,
        verbose: false,
        performance: true,
        namespace: 'popup',

        // whether it should use dom mutation observers
        observeChanges: true,

        // callback only when the element was added to dom
        onCreate: function () {},

        // callback before element removed from dom
        onRemove: function () {},

        // callback before show animation
        onShow: function () {},

        // callback after show animation
        onVisible: function () {},

        // callback before hide animation
        onHide: function () {},

        // callback when popup cannot be positioned in visible screen
        onUnplaceable: function () {},

        // callback after hide animation
        onHidden: function () {},

        // when to show popup
        on: 'hover',

        // element to use to determine if popup is out of boundary
        boundary: window,

        // whether to add touchstart events when using hover
        addTouchEvents: true,

        // default position relative to element
        position: 'top left',

        // if given position should be used regardless if popup fits
        forcePosition: false,

        // name of variation to use
        variation: '',

        // whether popup should be moved to context
        movePopup: true,

        // element which popup should be relative to
        target: false,

        // jQuery selector or element that should be used as a popup
        popup: false,

        // popup should remain inline next to activator
        inline: false,

        // popup should be removed from page on hide
        preserve: false,

        // popup should not close when being hovered on
        hoverable: false,

        // explicitly set content
        content: false,

        // explicitly set HTML
        html: false,

        // explicitly set title
        title: false,

        // whether automatically close on clickaway when on click
        closable: true,

        // automatically hide on scroll
        hideOnScroll: 'auto',

        // hide other popups on show
        exclusive: false,

        // context to attach popups
        context: 'body',

        // context for binding scroll events
        scrollContext: window,

        // position to prefer when calculating new position
        prefer: 'opposite',

        // specify position to appear even if it doesn't fit
        lastResort: false,

        // number of pixels from edge of popup to pointing arrow center (used from centering)
        arrowPixelsFromEdge: 20,

        // delay used to prevent accidental refiring of animations due to user error
        delay: {
            show: 50,
            hide: 70,
        },

        // whether fluid variation should assign width explicitly
        setFluidWidth: true,

        // transition settings
        duration: 200,
        transition: 'scale',

        // distance away from the activating element in px
        distanceAway: 0,

        // number of pixels an element is allowed to be "offstage" for a position to be chosen (allows for rounding)
        jitter: 2,

        // offset on aligning axis from calculated position
        offset: 0,

        // maximum times to look for a position before failing (9 positions total)
        maxSearchDepth: 15,

        error: {
            invalidPosition: 'The position you specified is not a valid position',
            cannotPlace: 'Popup does not fit within the boundaries of the viewport',
            method: 'The method you called is not defined.',
            noElement: 'This module requires ui {element}',
            notFound: 'The target or popup you specified does not exist on the page',
        },

        metadata: {
            activator: 'activator',
            content: 'content',
            html: 'html',
            offset: 'offset',
            position: 'position',
            title: 'title',
            variation: 'variation',
        },

        className: {
            active: 'active',
            basic: 'basic',
            animating: 'animating',
            dropdown: 'dropdown',
            invisible: 'invisible',
            fluid: 'fluid',
            loading: 'loading',
            popup: 'ui popup',
            position: 'top left center bottom right',
            visible: 'visible',
            popupVisible: 'visible',
        },

        selector: {
            popup: '.ui.popup',
        },

        templates: {
            escape: function (string) {
                const escapeMap = {
                    '"': '&quot;',
                    '&': '&amp;',
                    "'": '&apos;',
                    '<': '&lt;',
                    '>': '&gt;',
                };

                return String(string).replace(/["&'<>]/g, (chr) => escapeMap[chr]);
            },
            popup: function (text) {
                let html = '';
                const escape = $.fn.popup.settings.templates.escape;
                if (text !== undefined) {
                    if (text.title) {
                        text.title = escape(text.title);
                        html += '<div class="header">' + text.title + '</div>';
                    }
                    if (text.content) {
                        text.content = escape(text.content);
                        html += '<div class="content">' + text.content + '</div>';
                    }
                }

                return html;
            },
        },

    };
})(jQuery, window, document);
