(function(context, $) {

  "use strict";

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


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

  $.fn.trackEffects = function(options) {

    return this.each(function(index) {

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

      var $parent = $(this);

      function onOptionSelected() {
        var $li = $(this);
        var vstOperation = $li.attr('data-manage-vst-option');

        close();
        $parent.triggerHandler(context.JK.EVENTS.VST_EFFECT_SELECTED, {vstOperation: vstOperation});
        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;

      context.JK.hoverBubble($parent, $('#template-vst-effects').html(), {
        trigger:'none',
        cssClass: 'vst-effects-popup',
        spikeGirth:0,
        spikeLength:0,
        width:220,
        closeWhenOthersOpen: true,
        offsetParent: $parent.closest('.screen'),
        positions:['bottom'],
        preShow: function() {

        },
        postShow:function(container) {
          if (options && options['postShow']) {
            options['postShow']($(container))
          }
          $(container).find('li').click(onOptionSelected)
          if(timeout) {
            clearTimeout(timeout);
            timeout = null;
          }
          waitForBubbleHover($(container))
          timeout = setTimeout(function() {/**$parent.btOff()*/}, 3000)
        }
      });

      $parent.hoverIntent({
        over: function() {
          $parent.btOn();
        },
        out: function() {

        }});
    });
  }


})(window, jQuery);