(function(context, $) {

  "use strict";

  context.JK = context.JK || {};


  // creates an iconic/graphical instrument selector. useful when there is minimal real-estate

  $.fn.instrumentSelector = function(options) {

    return this.each(function(index) {

      function select(instrument_id) {
        if(instrument_id == null) {
          $currentInstrument.text('?');
          $currentInstrument.addClass('none');
          $select.data('instrument_id', null);
        }
        else {
          $currentInstrument.empty();
          $currentInstrument.removeClass('none');
          $currentInstrument.append('<img src="' + context.JK.getInstrumentIconMap24()[instrument_id].asset + '" />');
          $select.data('instrument_id', instrument_id);
        }
      }

      function close() {
        $currentInstrument.btOff();
        $currentInstrument.focus();
      }

      function onInstrumentSelected() {
        var $li = $(this);
        var instrument_id = $li.attr('data-instrument-id');

        select(instrument_id);
        close();
        $select.triggerHandler('instrument_selected', {instrument_id: instrument_id});
        return false;
      };

      var instruments = context.JK.getInstrumentIconMap24();
      instruments = $.extend({}, instruments);
      delete instruments['_default']; //shouldn't be able to select 'default' here -- VRFS-1809
      var $select = $(context._.template($('#template-icon-instrument-select').html(), {instruments:instruments}, { variable: 'data' }));
      var $ul = $select.find('ul');
      var $currentInstrument = $select.find('.current-instrument');

      context.JK.hoverBubble($currentInstrument, $ul.html(), {
        trigger:'click',
        cssClass: 'icon-instrument-selector-popup',
        spikeGirth:0,
        spikeLength:0,
        width:150,
        closeWhenOthersOpen: true,
        preShow: function() {
        },
        postShow:function(container) {
          $(container).find('li').click(onInstrumentSelected)
        }
      });

      $currentInstrument.text('?');

      $(this).append($select);

      this.instrumentSelectorClose = close;
      this.instrumentSelectorSet = select;
    });
  }

  $.fn.instrumentSelectorClose = function() {
    return this.each(function(index){
      if (jQuery.isFunction(this.instrumentSelectorClose)) {
        this.instrumentSelectorClose();
      }
    });
  }

  $.fn.instrumentSelectorSet = function(instrumentId) {
    return this.each(function(index){
      if (jQuery.isFunction(this.instrumentSelectorSet)) {
        this.instrumentSelectorSet(instrumentId);
      }
    });
  }

})(window, jQuery);