(function(context,$) {

  "use strict";
  context.JK = context.JK || {};
  context.JK.GenreSelectorDialog = function(app, type, genres, callback) {
    var logger = context.JK.logger;
    var rest = context.JK.Rest();
    var $dialog = null;
    var dialogId = 'genre-selector-dialog';
    var $screen = $('#' + dialogId);
    var $btnSelect = $screen.find(".btn-select-genres");
    var $instructions = $screen.find('.instructions');
    var $genres = $screen.find('.genres');    

    function beforeShow(data) {
    }

    function afterShow(data) {
      var genreList = context.JK.genres;

      $genres.empty();

      if (genreList) {
        $.each(genreList, function(index, val) {        
          $genres.append('<li>');
          var checked = '';
          if (genres && $.inArray(val.id, genres) > -1) {
            checked = 'checked';
          }

          var $input = $('<input type="checkbox" />')
          $input.val(val.id)
          if(checked == 'checked') {
            $input.attr('checked', 'checked')
          }

          $genres.append($input);
          $genres.append(val.description);
          $genres.append('</li>');
        });
      }
    }

    function afterHide() {
      $btnSelect.unbind("click")
    }

    function showDialog() {
      return app.layout.showDialog(dialogId);
    }

    function events() {
      $btnSelect.unbind("click").bind("click", function(evt) {
        evt.preventDefault();
        var selectedGenres = [];
        $genres.find('input[type=checkbox]:checked').each(function(index) {
          selectedGenres.push($(this).val());
        });

        if (callback) {
          callback(selectedGenres);
        }

        app.layout.closeDialog(dialogId);

        return false;

      });
    }

    function initialize() {
      var dialogBindings = {
        'beforeShow' : beforeShow,
        'afterShow' : afterShow,
        'afterHide': afterHide
      };

      app.bindDialog(dialogId, dialogBindings);

      $instructions.html('Select one or more genres for ' + type + ':');

      events();
    }

    this.initialize = initialize;
    this.showDialog = showDialog;
  }

  return this;
})(window,jQuery);