(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 getAjaxTemplate(templateName) {
        var compiledTemplate = templateCache[templateName];
        if (compiledTemplate) {
            return $.Deferred().resolve(compiledTemplate);
        }
        return $.ajax({
            mimeType: 'text/html',
            url: templateName + '.html'
        }).then(function(template) {
            templateCache[templateName] = Handlebars.compile(template);
            return templateCache[templateName];
        });
    }

    dashboard.informationBox.openNew = function(itemName) {
        var templatePromise = getAjaxTemplate('box-template');
        templatePromise.then(function(boxCompiledTemplate) {
            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();
    };

})();
