(function(context,$) {

  "use strict";
  context.JK = context.JK || {};
  context.JK.InstrumentSelectorDialog = function(app, type, instruments, callback) {
    var logger = context.JK.logger;
    var rest = context.JK.Rest();
    var $dialog = null;
    var dialogId = 'instrument-selector-dialog';
    var $screen = $('#' + dialogId);
    var $btnSelect = $screen.find(".btn-select-instruments");
    var $instructions = $screen.find('.instructions');
    var $instruments = $screen.find('.instruments');    
    var $instrumentSelectorContainer = $screen.find('.instrument-selector-container')
    var instrumentSelector = new JK.InstrumentSelector(app, $instrumentSelectorContainer);
    var $callback = callback
    var selectedInstruments = instruments
    function beforeShow(data) {
      instrumentSelector.initialize(false)      
      instrumentSelector.render($instrumentSelectorContainer)            
      instrumentSelector.setSelectedInstruments(selectedInstruments)
    }

    function afterShow(data) {
      // var instrumentList = context.JK.instruments;

      // $instruments.empty();

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

      //     $instruments.append('<input type="checkbox" value="' + val.id + '" ' + checked + ' />' + val.description);
      //     $instruments.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();

        selectedInstruments = instrumentSelector.getSelectedInstruments()        
        $callback(selectedInstruments)
        app.layout.closeDialog(dialogId);        
        return false;

      });
    }

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

      app.bindDialog(dialogId, dialogBindings);

      $instructions.html('Select the instruments and expertise you need for ' + type + ':');

      events();
    }

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

  return this;
})(window,jQuery);