(function() {
    'use strict';

    dashboard.categories = dashboard.categories || {};

    dashboard.categories.data = [
        { title: 'jQuery conference' },
        { title: 'js conference' },
        { title: 'css conference' },
        { title: 'packt jquery' }
    ];

    dashboard.categories.init = function() {
        var $categoriesSelector = dashboard.$container.find('#categoriesSelector');
        var $categories = dashboard.$container.find('.dashboardCategoriesList');
        
        for (var i = 0; i < dashboard.categories.data.length; i++) {
            var categoryInfo = dashboard.categories.data[i];
            $categoriesSelector.append(
                '<option value="' + i + '"">' +
                    categoryInfo.title +
                '</option>');

            var $section = $('<section class="dashboardCategory">Ładowanie...</section>');
            if (i > 0) {
                $section.addClass('hidden');
            }
            $section.appendTo($categories);

            dashboard.categories.createCategoryButtons($section, categoryInfo);
        }

        $categoriesSelector.change(function() {
            var $selector = $(this);
            var categoryIndex = +$selector.val();
            dashboard.categories.selectCategory(categoryIndex);
        });

        dashboard.$container.find('.dashboardCategories').on('click', 'button', function() {
            var $button = $(this);
            var itemName = $button.text();
            dashboard.informationBox.openNew(itemName);
        });
    };

    dashboard.categories.createCategoryButtons = function($buttonContainer, categoryInfo) {
        dashboard.videoService.searchVideos(categoryInfo.title).then(function(result) {
            categoryInfo.items = result.items;

            $buttonContainer.empty()
                .append($.map(result.items, function(item) {
                    return $('<button>').text(item.snippet.title);
                }));
        }).fail(function() {
            $buttonContainer.html('Wystąpił błąd!');
        });
    };

    dashboard.categories.selectCategory = function(categoryIndex) {
        var $dashboardCategories = dashboard.$container.find('.dashboardCategory');
        var $selectedItem = $dashboardCategories.eq(categoryIndex).show();
        $dashboardCategories.not($selectedItem).hide();
    };

})();
