(function(context,$) {

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

    "use strict";

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

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

        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, notSelectedString) {
            if(!notSelectedString) {
              notSelectedString = 'Unspecified'
            }
            $('select', parentSelector).empty();
            $('select', parentSelector).append('<option value="">' + notSelectedString + '</option>');
            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);
            });
            context.JK.dropdown($('select', parentSelector));
        }

        function render2($select, notSelectedString) {
          if(!notSelectedString) {
            notSelectedString = 'Any Genre'
          }
          $select.empty();
          $select.append('<option value="">' + notSelectedString + '</option>');
          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.append(genreOptionHtml);
          });
          context.JK.dropdown($select);
        }


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

        function getSelectedGenresValues(parentSelector) {
          var selectedGenres = [];
          var selectedVal = $('select', parentSelector).get(0).options[$('select', parentSelector).get(0).selectedIndex].text;
          if (selectedVal !== '') {
            selectedGenres.push(selectedVal);
          }
          return selectedGenres;
        }

        function getNameForId(genreId) {
          var name = null;
          context._.each(_genres, function(genre) {
            if(genreId == genre.value) {
              name = genre.label;
              return false;
            }
          });

          if(!name) {
            logger.warn("no genre found for genreId: " + genreId);
          }
          return name;
        }

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

            $('select', parentSelector).val(values[0]);
        }

        function initialize(app) {
          // XXX; _instruments should be populated in a template, rather than round-trip to server
          if(!context.JK.GenreSelectorDeferred) {
            // this dance is to make sure there is only one server request instead of InstrumentSelector instances *
            context.JK.GenreSelectorDeferred = rest.getGenres()
          }

          context.JK.GenreSelectorDeferred
            .done(function(response) {genresLoaded(response)})
            .fail(app.ajaxError)

          return this;
        }

        var me = { // This will be our singleton.
            initialize: initialize,
            getSelectedGenres: getSelectedGenres,
            setSelectedGenres: setSelectedGenres,
            getNameForId : getNameForId,
            getSelectedGenresValues: getSelectedGenresValues,
            reset: reset,
            render: function() {
              var _args = arguments;
              context.JK.GenreSelectorDeferred.done(function(){render.apply(self, _args)})
            },
            render2: function() {
              var _args = arguments;
              context.JK.GenreSelectorDeferred.done(function(){render2.apply(self, _args)})
            }
        };

        return me;

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