(function(context, $) {

  "use strict";

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


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

  function setValue(val, $target) {
    if(val == "cricket") {
      $target.html("<span class='metronome-state'>Play cluster test<span class='down-arrow'></span></span>")
    }
    else {
      $target.html("<span class='metronome-state'>Play metronome<span class='down-arrow'></span></span>")
    }
  }

  $.fn.metronomeSetPlaybackMode = function(val) {
    return this.each(function (index) {
      setValue(val, $(this))
    });
  };

  $.fn.metronomePlaybackMode = function(options) {

    options = $.extend(false, {mode: 'self', positions: ['top']}, options);

    return this.each(function(index) {

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


      var $parent = $(this);
      var value = options.mode;
      setValue(options.mode, $parent)

      function onModeSelected() {
        var $li = $(this);
        var playbackMode = $li.attr('data-playback-option');

        if(playbackMode) {
          value = playbackMode;
          close();
          $parent.triggerHandler(context.JK.EVENTS.METRONOME_PLAYBACK_MODE_SELECTED, {playbackMode: playbackMode});
        }
        else {
          // if no playback mode, then this must be an attempt to open metronome window
          close();
          context.jamClient.SessionShowMetronomeGui();
        }
        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-metronome-playback-mode').html(), {
        trigger:'click',
        cssClass: 'metronome-playback-mode-selector-popup',
        spikeGirth:0,
        spikeLength:0,
        width:180,
        closeWhenOthersOpen: true,
        offsetParent: options.offsetParent || $parent.offsetParent(),
        positions: options.positions,
        preShow: function() {
          $parent.find('.down-arrow').removeClass('down-arrow').addClass('up-arrow')
        },
        postShow:function(container) {
          $(container).find('li').click(onModeSelected)
          if(timeout) {
            clearTimeout(timeout);
            timeout = null;
          }
          //waitForBubbleHover($(container))
          //timeout = setTimeout(function() {$parent.btOff()}, 3000)
        },
        postHide:function() {
          setValue(value, $parent)
        }
      });
    });
  }


})(window, jQuery);