(function(context, $) {

  "use strict";

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


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

  $.fn.jamblasterOptions = function(options) {

    return this.each(function(index) {

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

      var $parent = $(this);
      if($parent.data('jamblasterOptions')) {
        //return;
      }

      $parent.data('jamblasterOptions', options)
      function onJamBlasterOptionSelected() {
        var $li = $(this);
        var option = $li.attr('data-jamblaster-option');

        close();
        $parent.triggerHandler(context.JK.EVENTS.JAMBLASTER_ACTION, {option: option, options: $parent.data('jamblasterOptions')});
        return false;
      };

      // if the user goes into the bubble, remove
      function waitForBubbleHover($bubble) {
        $bubble.hoverIntent({
          over: function() {
            if(timeout) {
              clearTimeout(timeout);
              timeout = null;
            }
          },
          out: function() {
            $parent.btOff();
          }});
      }

      var timeout = null;

      var html = context._.template($('#template-jamblaster-options').html(), options, { variable: 'data' })

      var extraClasses = ' '
      var width = 120;
      if(options.isDynamicPorts || options.autoconnect) {
        extraClasses += 'isDynamicPorts '
        width = 140;
      }
      context.JK.hoverBubble($parent, html, {
        trigger:'none',
        cssClass: 'jamblaster-options-popup' + extraClasses,
        spikeGirth:0,
        spikeLength:0,
        overlap: -10,
        width:120,
        closeWhenOthersOpen: true,
        offsetParent: $parent.closest('.screen'),
        positions:['bottom'],
        preShow: function() {

        },
        postShow:function(container) {
          $(container).find('li').click(onJamBlasterOptionSelected)
          if(timeout) {
            clearTimeout(timeout);
            timeout = null;
          }
          waitForBubbleHover($(container))
          timeout = setTimeout(function() {$parent.btOff()}, 6000)
        }
      });
    });
  }


})(window, jQuery);