/* Minification failed. Returning unminified contents.
(43,104-105): run-time error JS1195: Expected expression: >
(43,165-166): run-time error JS1004: Expected ';': )
(44,105-106): run-time error JS1195: Expected expression: >
(44,166-167): run-time error JS1004: Expected ';': )
(48,13-14): run-time error JS1002: Syntax error: }
(54,33-34): run-time error JS1004: Expected ';': {
(62,5-6): run-time error JS1002: Syntax error: }
(65,32-33): run-time error JS1004: Expected ';': {
(73,31-32): run-time error JS1195: Expected expression: >
(73,78-79): run-time error JS1004: Expected ';': )
(92,67-68): run-time error JS1195: Expected expression: )
(92,70-71): run-time error JS1195: Expected expression: >
(92,108-109): run-time error JS1195: Expected expression: ,
(94,1-2): run-time error JS1002: Syntax error: }
(68,54-60): run-time error JS1018: 'return' statement outside of function: return
(67,47-53): run-time error JS1018: 'return' statement outside of function: return
(58,13-19): run-time error JS1018: 'return' statement outside of function: return
 */
window.mwfCustom = {
    ddlRootElement: undefined,
    ddlTimer: undefined,
    ddlTimerClearBuffer: undefined,
    ddlBuffer: ''
};

window.mwfCustom.ddl_isDropDownOpen = function () {
    return $(window.mwfCustom.ddlRootElement).find('.c-select-menu > button').attr('aria-expanded') === 'true';
}

function preventSpacebarEvent(e) {
    if (e.key === ' ') {
        if (!!window.mwfCustom.ddlRootElement) {
            if (window.mwfCustom.ddlBuffer.trim().length > 0) {
                window.mwfCustom.ddlBuffer += ' ';
                e.preventDefault();
                e.stopPropagation();
            }
        }
    }
}

function preventClickEvent(e) {
    if (window.mwfCustom.ddl_isDropDownOpen()) {
        if (window.mwfCustom.ddlBuffer.length > 1) {
            e.preventDefault();
            e.stopPropagation();
        }
    }
}

$(document).ready(function () {
    
    $(document).on('keydown', '.c-select', function (e) {
        window.mwfCustom.ddlRootElement = e.currentTarget;

        if (!!window.mwfCustom.ddlRootElement) {
            if (window.mwfCustom.ddlRootElement.getAttribute('data-is-mwf-initialized') !== 'true') {
                window.mwfCustom.ddlRootElement.setAttribute('data-is-mwf-initialized', 'true');

                // Disable spacebar while typing is active
                window.mwfCustom.ddlRootElement.querySelectorAll('.c-select-menu button').forEach(btn => btn.addEventListener('keydown', preventSpacebarEvent, true));
                window.mwfCustom.ddlRootElement.querySelectorAll('.c-select-menu .c-menu').forEach(btn => btn.addEventListener('keydown', preventSpacebarEvent, true));
                //window.mwfCustom.ddlRootElement.querySelectorAll('.c-select-menu [role=option]').forEach(btn => btn.addEventListener('keydown', preventSpacebarEvent, true));
                //window.mwfCustom.ddlRootElement.querySelectorAll('.c-select-menu [role=option]').forEach(btn => btn.addEventListener('click', preventClickEvent, true));

            }
        }

        let keyChar = e.originalEvent && e.originalEvent.key;

        // Arrow keys, enter, etc
        if (keyChar.length > 1) {
            window.clearTimeout(window.mwfCustom.ddlTimer);
            window.mwfCustom.ddlTimer = undefined;
            window.mwfCustom.ddlBuffer = '';
            return;
        }

        onKeyDown(keyChar);
    });


    function onBufferTimeout() {
        window.mwfCustom.ddlTimer = undefined;
        if (!window.mwfCustom.ddlRootElement) return;
        if (window.mwfCustom.ddlBuffer.length === 0) return;
        let needle = window.mwfCustom.ddlBuffer.toLowerCase();

        let found = $(window.mwfCustom.ddlRootElement)
            .find('li span')
            .filter((xi, xe) => $(xe).text().toLowerCase().startsWith(needle));


        if (!!found && found.length > 0) {
            if (window.mwfCustom.ddl_isDropDownOpen()) {
                found[0].focus();
            } else {
                found[0].click();
            }
        }
    }

    function onKeyDown(char) {
        window.mwfCustom.ddlBuffer += char;

        if (!!window.mwfCustom.ddlTimer) window.clearTimeout(window.mwfCustom.ddlTimer);
        window.mwfCustom.ddlTimer = window.setTimeout(onBufferTimeout, 100);

        if (!!window.mwfCustom.ddlTimerClearBuffer) window.clearTimeout(window.mwfCustom.ddlTimerClearBuffer);
        window.mwfCustom.ddlTimerClearBuffer = window.setTimeout(() => { window.mwfCustom.ddlBuffer = ''; }, 500);
    }
});;
var KEYCODE = {
    DOWN: 40,
    LEFT: 37,
    RIGHT: 39,
    SPACE: 32,
    UP: 38
}

const RadioJS = {
    /**
    * @function firstRadioButton
    * @description Returns the first radio button
    * @param {EventTarget} node Standard W3C event object
    * @returns {HTMLElement | null}
    */
    firstRadioButton: function (node) {
        var first = node.parentNode.firstChild;

        while (first) {
            if (first.nodeType === Node.ELEMENT_NODE) {
                if (first.getAttribute("role") === 'radio') return first;
            }
            first = first.nextSibling;
        }

        return null;
    },

    /**
    * @function lastRadioButton
    * @description Returns the last radio button
    * @param {EventTarget} node =  Standard W3C event object
    * @returns {HTMLElement | null}
    */
    lastRadioButton: function (node) {
        var last = node.parentNode.lastChild;

        while (last) {
            if (last.nodeType === Node.ELEMENT_NODE) {
                if (last.getAttribute("role") === 'radio') return last;
            }
            last = last.previousSibling;
        }

        return last;
    },

    /**
    * @function nextRadioButton
    * @description Returns the next radio button
    * @param  {EventTarget} node  =  Standard W3C event object
    * @returns {HTMLElement | null}
    */
    nextRadioButton: function (node) {
        var next = node.nextSibling;

        while (next) {
            if (next.nodeType === Node.ELEMENT_NODE) {
                if (next.getAttribute("role") === 'radio') return next;
            }
            next = next.nextSibling;
        }

        return null;
    },

    /**
    * @function previousRadioButton
    * @description Returns the previous radio button
    * @param {EventTarget} node  =  Standard W3C event object
    * @returns {HTMLElement | null}
    */
    previousRadioButton: function (node) {
        var prev = node.previousSibling;

        while (prev) {
            if (prev.nodeType === Node.ELEMENT_NODE) {
                if (prev.getAttribute("role") === 'radio') return prev;
            }
            prev = prev.previousSibling;
        }

        return null;
    },

    /**
    * @function setRadioButton
    * @description Toogles the state of a radio button
    * @param {EventTarget}  node  -  Standard W3C event object
    * @param {boolean} isChecked
    */
    setRadioButton: function (node, isChecked) {
        if (isChecked == 'true') {
            node.setAttribute('aria-checked', 'true')
            node.tabIndex = 0;
            node.focus()
        }
        else {
            node.setAttribute('aria-checked', 'false')
            node.tabIndex = -1;
        }
    },

    /**
     * @function onClickOption
     * @param {MouseEvent} event
     */
    onClickOption: function (event) {
        var type = event.type;

        if (type === 'click') {
            // If either enter or space is pressed, execute the funtion

            var node = event.currentTarget;

            var radioButton = RadioJS.firstRadioButton(node);

            while (radioButton) {
                RadioJS.setRadioButton(radioButton, "false");
                radioButton = RadioJS.nextRadioButton(radioButton);
            }

            RadioJS.setRadioButton(node, "true");

            event.preventDefault();
            event.stopPropagation();
        }
    },

    /**
     * @function onKeyDownOption
     * @param {KeyboardEvent} event
     */
    onKeyDownOption: function (event) {
        var type = event.type;
        var next = false;

        if (type === "keydown") {
            var node = event.currentTarget;

            switch (event.keyCode) {
                case KEYCODE.DOWN:
                case KEYCODE.RIGHT:
                    var next = RadioJS.nextRadioButton(node);
                    if (!next) next = RadioJS.firstRadioButton(node); //if node is the last node, node cycles to first.
                    break;

                case KEYCODE.UP:
                case KEYCODE.LEFT:
                    next = RadioJS.previousRadioButton(node);
                    if (!next) next = RadioJS.lastRadioButton(node); //if node is the last node, node cycles to first.
                    break;

                case KEYCODE.SPACE:
                    next = node;
                    break;
            }

            if (next) {
                var radioButton = RadioJS.firstRadioButton(node);

                while (radioButton) {
                    RadioJS.setRadioButton(radioButton, "false");
                    radioButton = RadioJS.nextRadioButton(radioButton);
                }

                //RadioJS.setRadioButton(next, "true");
                $(next).click();

                event.preventDefault();
                event.stopPropagation();
            }
        }
    },

    /**
    * @function onBlurOption
    * @description Removes anti-focus-styling from the label element encapsulating standard radio button
    * @param {FocusEvent} event - Standard W3C event object
    */
    onBlurOption: function (event) {
        event.currentTarget.className = event.currentTarget.className.replace(' x-hidden-focus', '');
    },

    /**
     * @function onMouseDownOption
     * @description Adds anti-focus styling so that a regular mouse user will not see keyboard accessible focus indicators.
     * @param {MouseEvent} event
     */
    onMouseDownOption: function (event) {
        event.currentTarget.className += ' x-hidden-focus';
    }
}



window.addEventListener('load', function () {
    var radiobuttons = document.querySelectorAll('.js-radioGroup [role=radio]');

    for (var i = 0; i < radiobuttons.length; i++) {
        var rb = radiobuttons[i];
        rb.addEventListener('mousedown', RadioJS.onMouseDownOption);
        rb.addEventListener('click', RadioJS.onClickOption);
        rb.addEventListener('keydown', RadioJS.onKeyDownOption);
        rb.addEventListener('blur', RadioJS.onBlurOption);
    }
});
;
