(function(context,$) {

    /**
    * Javascript for managing genre selectors.
    */

    "use strict";

    context.JK = context.JK || {};
    context.JK.GenreSelectorHelper = (function() {

        var logger = context.JK.logger;
        var _genres = [];  // will be list of structs: [ {label:xxx, value:yyy}, {...}, ... ]

        function loadGenres() {
            var url = "/api/genres";
            $.ajax({
                type: "GET",
                url: url,
                async: false,  // do this synchronously so the event handlers in events() can be wired up
                success: genresLoaded
            });
        }

        function reset(parentSelector, defaultGenre) {
            defaultGenre = typeof(defaultGenre) == 'undefined' ? '' : defaultGenre;
            $('select', parentSelector).val(defaultGenre);
        }

        function genresLoaded(response) {
            $.each(response, function(index) {
                _genres.push({
                    value: this.id,
                    label: this.description
                });
            });
        }

        function render(parentSelector) {
            $('select', parentSelector).empty();
            var template = $('#template-genre-option').html();
            $.each(_genres, function(index, value) {
                // value will be a dictionary entry from _genres:
                // { value: xxx, label: yyy }
                var genreOptionHtml = context.JK.fillTemplate(template, value);
                $('select', parentSelector).append(genreOptionHtml);
            });

        }

        function getSelectedGenres(parentSelector) {
            var selectedGenres = [];
            var selectedVal = $('select', parentSelector).val();
            if (selectedVal !== '') {
                selectedGenres.push(selectedVal);
            }
            return selectedGenres;
        }

        function setSelectedGenres(parentSelector, genreList) {
            if (!genreList) {
                return;
            }
            var values = [];
            $.each(genreList, function(index, value) {
                values.push(value.toLowerCase());
            });
            var selectedVal = $('select', parentSelector).val(values);
        }

        function initialize() {
            loadGenres();
        }

        var me = { // This will be our singleton.
            initialize: initialize,
            getSelectedGenres: getSelectedGenres,
            setSelectedGenres: setSelectedGenres,
            reset: reset,
            render: render,
            loadGenres: loadGenres
        };

        return me;

    })();
})(window,jQuery);
