$(document).ready(function () {
    $(document).on('click', '.collapsed-dropdown', function (event) {
        $(this).toggleClass('open');
    });
    $('body').on('click', function (e) {
        if (!$('.collapsed-dropdown').is(e.target)
            && $('.collapsed-dropdown').has(e.target).length === 0
            && $('.open').has(e.target).length === 0
        ) {
            $('.collapsed-dropdown').removeClass('open');
        }
    });
    onResize();
});

$(window).resize(function () {
    onResize();
});

let collapsableFormButtonsCollapsed = false;
function onResize() {
    let windowWidth = $(window).width();
    if (!collapsableFormButtonsCollapsed && windowWidth < 992) {
        collapseCollapsableFormButtons();
        collapsableFormButtonsCollapsed = true;
    }
    else if (collapsableFormButtonsCollapsed && windowWidth >= 992) {
        expandCollapsableFormButtons();
        collapsableFormButtonsCollapsed = false;
    }
}

function collapseCollapsableFormButtons() {
    let $collapsableButtons = $(".collapsable-form-button");
    if ($collapsableButtons.length < 2) return;

    let $containerParrent = $($collapsableButtons[0]).closest(".buttons-tabbed");

    let $collapsedDropdown = $('<div class="dropdown collapsed-dropdown"></div>');
    let $collapsedDropdownButton = $('<button type="button" class="btn btn-default btn-outline"><span class="fa fa-bars"></span></button>');
    let $collapsedDropdownList = $('<ul class="dropdown-menu"></ul>');

    for (let a = $collapsableButtons.length - 1; a >= 0; a--) {
        let $li = $('<li></li>');
        let $currentButton = $($collapsableButtons[a]);
        $currentButton.appendTo($li);

        $collapsedDropdownList.append($li);
    }

    $collapsedDropdown.append($collapsedDropdownButton);
    $collapsedDropdown.append($collapsedDropdownList);
    $containerParrent.append($collapsedDropdown);
}

function expandCollapsableFormButtons() {
    let $collapsableButtons = $(".collapsable-form-button");

    if ($collapsableButtons.length < 2) return;

    for (let a = $collapsableButtons.length - 1; a >= 0; a--) {
        let $currentButton = $($collapsableButtons[a]);
        $currentButton.appendTo($collapsableButtons.closest(".buttons-tabbed"));
    }

    $(".collapsed-dropdown").remove();
}