/**
 * Show/Hide Searchbar
 */
(function( $ ) {

    "use strict";

    const searchButton  = $('.search');
    const searchbar     = $('#searchbar');

    function showSearchbar() {

        // -- close open menu on mobile if open -- //
        var navbarToggle =  $('*[data-navbar-toggle="open"]');
        var navCollapse = $('.navbar-collapse');
        if( $(navbarToggle).length > 0 ) {
          $(navbarToggle).attr('data-navbar-toggle', 'closed');
        }
        if( $(navCollapse).hasClass('in')) {
            $(navCollapse).removeClass('in')
        }
        // -------------------------------------- //

        $(searchbar).addClass('show').attr('aria-expanded', 'true').find('#inputSearch').focus();
        $(document).on('mouseup', handleClickOutsideSearchbar);
    }

    function hideSearchbar() {
        $(searchbar).removeClass('show').attr('aria-expanded', 'false');
        $(document).off('mouseup', handleClickOutsideSearchbar);
    }

    function handleClickOutsideSearchbar(e) {
        // ! => turns it into a boolean
        const isOutsideSearchButton = !e.target.closest('.search');
        const isOutsideSearchbar = !e.target.closest('#searchbar');
        if( isOutsideSearchbar && isOutsideSearchButton ) {
            hideSearchbar();
        }
    }

    function handleSearchButtonClick(e) {

        if( $(searchbar).hasClass('show')) {
            hideSearchbar();
        }
        else {
            showSearchbar();
        }
    }

    // button search in header menu
    $(searchButton).on('click', handleSearchButtonClick);
    
}( jQuery ));