(function(context, $) {

  "use strict";

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


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

  $.fn.lessonSessionActions = function(options) {

    return this.each(function(index) {

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

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

      $parent.data('lessonSessionActions', options)
      function onLessonActionSelected() {
        var $li = $(this);
        var lessonAction = $li.attr('data-lesson-option');

        close();
        $parent.triggerHandler(context.JK.EVENTS.LESSON_SESSION_ACTION, {lessonAction: lessonAction, options: $parent.data('lessonSessionActions')});
        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-lesson-session-actions').html(), options, { variable: 'data' })

      var extraClasses = ' '
      var width = 120;
      var otherOverlap = 22;

      if (options.attachments_only) {
        extraClasses += 'attachments-only'
        width = 120;
      }
      if(options.isRequested) {
        extraClasses += 'is-requested '
        width = 100;
      }
      else if(options.isScheduled) {
        extraClasses += 'is-scheduled '
        width = 120;
      }
      if(options.cardNotOk) {
        extraClasses += 'not-card-ok '
        width = 90;
      }
      if(options.isAdmin) {
        extraClasses += 'is-admin '
        width = 135;
      }
      if (options.chat_dialog) {
        var $sidebar = $parent.closest('.dialog')
      }
      else if (options.attachments_only) {
        var $sidebar = $parent.closest('#sidebar-div');
      }
      else {
        var $sidebar = $parent.closest('.screen')
      }
      context.JK.hoverBubble($parent, html, {
        trigger:'none',
        cssClass: 'lesson-action-popup' + extraClasses,
        spikeGirth:0,
        spikeLength:0,
        otherOverlap: ((width - 90) / 2) + 25,
        overlap: -10,
        width:width,
        closeWhenOthersOpen: true,
        offsetParent: $sidebar,
        positions:['bottom'],
        preShow: function() {

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


})(window, jQuery);