$(document).ready(function() {
    window.broker = $('.dashboardContainer');

    $('#categoriesSelector').change(function() {
        var $selector = $(this);
        var message = { categoryID: $selector.val() };
        broker.trigger('dashboardCategorySelect', [message]);
    });

    broker.on('dashboardCategorySelect', function(event, message) {
        var $dashboardCategories = $('.dashboardCategory');
        var selectedIndex = +message.categoryID;
        var $selectedItem = $dashboardCategories.eq(selectedIndex).show();
        $dashboardCategories.not($selectedItem).hide();
    });


    $('.dashboardCategory').on('click', 'button', function() {
        var $button = $(this);
        var message = { categoryName: $button.text() };
        broker.trigger('categoryItemOpen', [message]);
    });

    broker.on('categoryItemOpen', function(event, message) {
        var boxHtml = '<div class="boxsizer"><article class="box">' +
                '<header class="boxHeader">' +
                    message.categoryName +
                    '<button class="boxCloseButton">&#10006;</button>'+
                '</header>' +
                'Pole informacyjne dotyczące: ' + message.categoryName +
            '</article></div>';
        $('.boxContainer').append(boxHtml);
    });


    $('.boxContainer').on('click', '.boxCloseButton', function() {
        var boxIndex = $(this).closest('.boxsizer').index();
        var message = { boxIndex: boxIndex };
        broker.trigger('categoryItemClose', [message]);
    });

    broker.on('categoryItemClose', function(event, message) {
        $('.boxContainer .boxsizer').eq(message.boxIndex).remove();
    });
});
