(function(context,$) {

  "use strict";
  context.JK = context.JK || {};
  context.JK.SessionHoverBubble = function(sessionId, x, y) {

    var logger = context.JK.logger;
    var rest = context.JK.Rest();
    var hoverSelector = "#session-hover";

    // assumes users are sorted by 
    function deDupUsers(users) {
      var deDupedUsers = [];

      var u = {};

      $.each(users, function(index, user) {
        if (index > 0) {
          // new user
          if (users[index-1].user_id !== users[index].user_id) {
            u = {};
            u.instruments = user.instruments;
            u.user = user.user;
            deDupedUsers.push(u);
          }
          else {
            u.instruments += "|" + user.instruments;
          }
        }
        else {
          u.instruments = user.instruments;
          u.user = user.user;
          deDupedUsers.push(u);
        }
      });

      return deDupedUsers;
    }

    this.showBubble = function($hoverElement) {

      return rest.getSessionHistory(sessionId)
        .done(function(response) {
          $(hoverSelector).html('');

          // musicians
          var musicianHtml = '';
          var deDupedUsers = deDupUsers(response.users);

          $.each(deDupedUsers, function(index, val) {
              var instrumentHtml = '';

              musicianHtml += '<tr><td width="50"><a href="#" class="avatar-tiny"><img src="' + context.JK.resolveAvatarUrl(val.user.photo_url) + '" /></a></td>';
              musicianHtml += '<td width="75"><a href="#">' + val.user.name + '</a></td>';

              instrumentHtml = '<td><div class="nowrap">';
              var instruments = val.instruments.split("|");
              var deDupedInstruments = [];

              $.each(instruments, function(index, instrument) {
                if ($.inArray(instrument, deDupedInstruments) === -1) {
                  deDupedInstruments.push(instrument);
                }
              });

              $.each(deDupedInstruments, function(index, instrument) {
                instrumentHtml += '<img src="' + context.JK.getInstrumentIcon24(instrument) + '" title="' + context.JK.getInstrumentId(instrument) + '" width="24" height="24" />&nbsp;';
              });

              instrumentHtml += '</div></td>';

              musicianHtml += instrumentHtml;
              musicianHtml += '</tr>';
          });

          var template = $('#template-hover-session').html();

          var sessionPageUrl = "/sessions/" + response.id;
          var sessionPageLinkText = "WEB PAGE";

          // if session hasn't begun, it must be a scheduled session so link to SESSION INFO page
          if (!response.active_music_session && !response.session_removed_at) {
            sessionPageUrl += "/details";
            sessionPageLinkText = "SESSION DETAILS";
          }

          var sessionHtml = context.JK.fillTemplate(template, {
            musicSessionId: response.id,
            name: response.name,
            description: response.description,
            genre: response.genre_id.toUpperCase(),
            comment_count: response.comment_count,
            like_count: response.like_count,
            created_at: $.timeago(response.created_at),
            musicians: musicianHtml,
            url: sessionPageUrl,
            externalLinkText: sessionPageLinkText,
            start_time: response.pretty_scheduled_start_short,
            recurrence: response.recurring_mode === 'weekly' ? 'Recurs weekly on this day at this time' : ''
          });

          $(hoverSelector).append('<h2>Session Detail</h2>' + sessionHtml);
          toggleActionButtons();

          var css = context.JK.calculateHoverPosition(x, y, $(hoverSelector).width(), $(hoverSelector).height(), $hoverElement);

          $(hoverSelector).css(css);
          $(hoverSelector).fadeIn(500);
        })
        .fail(function(xhr) {
          if(xhr.status >= 500) {
              context.JK.fetchUserNetworkOrServerFailure();
          }
          else if(xhr.status == 404) {
              context.JK.entityNotFound("Session");
          }
          else {
              context.JK.app.ajaxError(arguments);
          }
        });
    };

    function toggleActionButtons() {
      if (!context.JK.currentUserId) {
        $("#btnLike", hoverSelector).hide();
        $("#btnShare", hoverSelector).hide();
      }
    }

    this.hideBubble = function() {
      $(hoverSelector).hide();
    };

    this.id = function() {
      return hoverSelector;
    };
  }
})(window,jQuery);