(function(context,$) {

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

    var logger = context.JK.logger;
    var rest = context.JK.Rest();
    var hoverSelector = "#musician-hover";
    var $templateLatency = null;
    var sessionUtils = context.JK.SessionUtils;

    this.showBubble = function($hoverElement) {
      $templateLatency = $("#template-account-session-latency");

      return rest.getUserDetail({id: userId})
        .done(function(response) {
          $(hoverSelector).html('');

          // instruments
          var instrumentHtml = '';
          $.each(response.instruments, function(index, val) {
            instrumentHtml += '<div class="left mr10 mb"><img src="' + context.JK.getInstrumentIcon24(val.instrument_id) + '" title="' + context.JK.getInstrumentId(val.instrument_id) + '" width="24" height="24" /></div>';
          });

          var genreHtml = '';
          $.each(response.genres, function(index, val) {
            genreHtml += val.description + ' ';
          });

          // followings
          var followingHtml = '';
          $.each(response.followings, function(index, val) {
            if (index < 4) { // display max of 4 followings
              if (index % 2 === 0) { 
                followingHtml += '<tr>';
              }

              var avatarUrl, attrId, type;

              if (val.type === "band") {
                avatarUrl = context.JK.resolveBandAvatarUrl(val.photo_url);
                attrId = "band-id";
                type = "band";
              }
              else {
                avatarUrl = context.JK.resolveAvatarUrl(val.photo_url);
                attrId = "user-id";
                type = "musician";
              }

              followingHtml += '<td width="24"><a ' + attrId + '="' + val.id + '" profileaction="' + type + '" class="avatar-tiny"><img src="' + avatarUrl + '" /></a></td>';
              followingHtml += '<td><a ' + attrId + '="' + val.id + '" profileaction="' + type + '"><strong>' + val.name + '</strong></a></td>';

              if (index % 2 > 0) {
                followingHtml += '</tr>';
              }
            }
          });

          var template = $('#template-hover-musician').html();
          if (response.biography == null) {
            response.biography = 'No Biography Available';
          }

          var sessionDisplayStyle = 'none';
          var sessionId = '';
          var joinDisplayStyle = 'none';
          if (response.sessions !== undefined && response.sessions.length > 0) {
            sessionDisplayStyle = 'block';
            var session = response.sessions[0];
            sessionId = session.id;

            if (context.jamClient && session.musician_access) {
              joinDisplayStyle = 'inline';
            }
          }

          var fullScore = null;

          if (response.internet_score && response.internet_score.length > 0) {
            if (response.internet_score[0].score && !isNaN(response.internet_score[0].score)) {
              var internetScore = parseInt(response.internet_score[0].score);
              fullScore = internetScore + calculateAudioLatency(response.my_audio_latency) + calculateAudioLatency(response.last_jam_audio_latency);
            }
          }

          // latency badge template needs these 2 properties
          $.extend(response, {
            audio_latency: response.last_jam_audio_latency,
            full_score: fullScore
          });

          var latencyBadge = context._.template(
            $templateLatency.html(),
            $.extend(response, sessionUtils.createLatency(response)),
            {variable: 'data'}
          );

          var musicianHtml = context.JK.fillTemplate(template, {
              userId: response.id,
              avatar_url: context.JK.resolveAvatarUrl(response.photo_url),
              name: response.name,
              first_name: response.first_name,
              location: response.location,
              instruments: instrumentHtml,
              genres: genreHtml,
              friend_count: response.friend_count,
              follower_count: response.follower_count,
              recording_count: response.recording_count,
              session_count: response.session_count,
              session_display: sessionDisplayStyle,
              join_display: joinDisplayStyle,
              sessionId: sessionId,
              latency_badge: latencyBadge,
              //friendAction: response.is_friend ? "removeMusicianFriend" : (response.pending_friend_request ? "" : "sendMusicianFriendRequest"),
              friendAction: response.is_friend ? "" : (response.pending_friend_request ? "" : "sendMusicianFriendRequest"),
              followAction: response.is_following ? "removeMusicianFollowing" : "addMusicianFollowing",
              biography: response.biography,
              followings: response.followings && response.followings.length > 0 ? followingHtml : "<tr><td>N/A</td></tr>",
              profile_url: "/client#/profile/" + response.id
          });

          $(hoverSelector).append('<h2>Musician Detail</h2>' + musicianHtml);

          context.JK.bindProfileClickEvents(hoverSelector);
          configureActionButtons(response);

          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("User");
          }
          else {
              context.JK.app.ajaxError(arguments);
          }
        });
    };

    function calculateAudioLatency(latency) {
      if (!latency || latency === 0) {
        return 13;
      }

      return latency;
    }

    function configureActionButtons(user) {
      var btnFriendSelector = "#btnFriend";
      var btnFollowSelector = "#btnFollow";
      var btnMessageSelector = '#btnMessage';

      // if unauthenticated or authenticated user is viewing his own profile
      if (!context.JK.currentUserId || context.JK.currentUserId === user.id) {
        $(btnFriendSelector, hoverSelector).hide();
        $(btnFollowSelector, hoverSelector).hide();
        $(btnMessageSelector, hoverSelector).hide();
      }
      else {
        if (user.is_friend) {
          $(btnFriendSelector, hoverSelector).html('CONNECTED');
          $(btnFriendSelector, hoverSelector).addClass('disabled');
        }
        if (user.is_following) {
          $(btnFollowSelector, hoverSelector).html('UNFOLLOW');
        }
        if (user.pending_friend_request) {
          //$(btnFriendSelector, hoverSelector).hide();
          $(btnFriendSelector, hoverSelector).html('REQUEST SENT');
          $(btnFriendSelector, hoverSelector).addClass('disabled');
        }
      }

    }

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

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