var Wick = Wick || {};
Wick.Accordion = (function () {
    var accordionRoot = '.accordion',
        accordionToggler = '.accordion__header',
        accordionIcon = '.accordion__action',
        accordionBottomClose = '.opening-times-accordion__close',
        accordionContent = '.accordion__content',
        collapsed = 'accordion_collapsed',
        $asideAccordion = $('.aside-accordion .js-toggle-aside-accordion');

    function toggleAccordion($acc) {
        if (!$acc.length) return;

        $acc.toggleClass(collapsed);
        $acc.children(accordionContent).stop(true, true).slideToggle(200);
    }

    function getTriggerSelector($acc) {
        return $acc.attr('data-action-element') === 'icon' ? accordionIcon : accordionToggler;
    }

    function onAccordionClick(e) {
        var $trigger = $(e.currentTarget);
        var $acc = $trigger.closest(accordionRoot);
        if (!$acc.length) return;

        var triggerSel = getTriggerSelector($acc);

        if (!$trigger.is(triggerSel)) return;

        toggleAccordion($acc);
    }

    function onAccordionBottomCloseClick(e) {
        e.preventDefault();

        var $trigger = $(e.currentTarget);
        var $acc = $trigger.closest(accordionRoot);
        if (!$acc.length) return;

        if (!$acc.hasClass(collapsed)) {
            toggleAccordion($acc);
        }
    }

    function init() {
        $(document)
            .off('click.wickAccordion', accordionToggler + ',' + accordionIcon)
            .on('click.wickAccordion', accordionToggler + ',' + accordionIcon, onAccordionClick);

        $(document)
            .off('click.wickAccordionClose', accordionBottomClose)
            .on('click.wickAccordionClose', accordionBottomClose, onAccordionBottomCloseClick);

        $asideAccordion.off('click.wickAsideAccordion').on('click.wickAsideAccordion', function () {
            if (window.matchMedia('(min-width: 992px)').matches) {
                if ($(this).text().toLowerCase() !== 'useful links') {
                    $(this)
                        .closest('.aside-nav2__holder')
                        .toggleClass('is-active')
                        .find('.aside-nav2__list')
                        .slideToggle(250);
                }
            }
        });
    }

    init();
})();
