(function( $ ) {

$.widget( "ui.nowPlaying", {

    options: {
        templateSelector: '#now-playing-template',
        adminTemplateSelector: '#now-playing-admin-template',
        playerSelector: '#player',
        recipeArraySelector: '#songs',
        showCurrentRecipeSelector: '#show-current-recipe',
        likeSelector: '.like',
        infoLinkSelector: '.info-link',
        showCurrentRecipeSelector: '#show-current-recipe'
    },

    _init: function() {
        var self = this;

        self.$player = $(self.options.playerSelector);
        self.$recipeArray = $(self.options.recipeArraySelector);
        self.$template = $(self.options.templateSelector).template();
        self.$adminTemplate = $(self.options.adminTemplateSelector).template();

        self.$player.bind('recipeItemChanged.player.nowPlaying', function (event, recipeItem) {
            self._renderPanel(recipeItem);
        });
    },

    _renderPanel: function (recipeItem) {
        var self = this;

        $.tmpl(this.$template, recipeItem).appendTo(this.element.empty());
        this._attachHandlers();

        $.user.currentIfAny().then(function (profile) {
            if (profile && profile.user && profile.user.roles) {
                $.each(profile.user.roles, function (index, role) {
                    if (role === 'Administrator') {
                        $.tmpl(self.$adminTemplate, recipeItem).appendTo(self.element);
                        self._attachHandlers();
                    }
                });
            }
        });
    },

    _attachHandlers: function () {
        var self = this;

        $(this.options.showCurrentRecipeSelector)
            .unbind('click')
            .click(function () {
                $.location().update($.tmplItem(this).data.recipePage.deepLink);
            });

        self.element.find('.deep-link')
            .unbind('click')
            .click(function (event) {
                var clickedHref = $(this).attr('href');

                event.preventDefault();
                $.location().update(clickedHref);
            });

        this.element.find(this.options.likeSelector).likeButton();
        this.element.find(this.options.infoLinkSelector).button();
        this.element.find(this.options.showCurrentRecipeSelector).button();
    } 

});

})( jQuery );

