(function() {
    'use strict';

    dashboard.informationBox = dashboard.informationBox || {};

    var $boxContainer = null;

    dashboard.informationBox.init = function() {
        $boxContainer = dashboard.$container.find('.boxContainer');

        $boxContainer.on('click', '.boxCloseButton', function() {
            var $button = $(this);
            dashboard.informationBox.close($button);
        });
    };

    var templateCache = {};

    function getEmbeddedTemplate(templateName) {
        var compiledTemplate = templateCache[templateName];
        if (!compiledTemplate) {
            var template = $('#' + templateName).html();
            compiledTemplate = Handlebars.compile(template);
            templateCache[templateName] = compiledTemplate;
        }
        return compiledTemplate;
    }

    dashboard.informationBox.openNew = function(itemName) {
        var boxCompiledTemplate = getEmbeddedTemplate('box-template');
        var boxHtml = boxCompiledTemplate({
            itemName: itemName
        });
        var $box = $(boxHtml).appendTo($boxContainer);

        dashboard.videoService.getVideo(itemName).then(function(result) {
            var boxContentTemplate = Handlebars.compile('<a href="{{ videoUrl }}"><img src="{{ thumbUrl }}" /></a>');
            var boxContent = boxContentTemplate({
                videoUrl: dashboard.videoService.getVideoUrl(result.id.videoId),
                thumbUrl: result.snippet.thumbnails.medium.url
            });
            
            $box.find('.boxContent').empty().append(boxContent);
        }).fail(function() {
            $buttonContainer.html('Wystąpił błąd!');
        });
    };

    dashboard.informationBox.close = function($boxElement) {
        $boxElement.closest('.boxsizer').remove();
    };

})();
