(function(context,$) {

  "use strict";
  context.JK = context.JK || {};
  context.JK.RecordingHoverBubble = function(recordingId, x, y) {
    var logger = context.JK.logger;
    var rest = context.JK.Rest();
    var hoverSelector = "#recording-hover";

    function deDupTracks(recordedTracks) {
      var tracks = [];

      // this is replicated in recording.rb model
      var t = {};
      t.instrument_ids = [];
      $.each(recordedTracks, function(index, track) {
        if (index > 0) {
          if (recordedTracks[index-1].user.id !== recordedTracks[index].user.id) {
            t = {};
            t.instrument_ids = [];
            t.instrument_ids.push(track.instrument_id);
            t.user = track.user;
            tracks.push(t);
          }
          else {
            if ($.inArray(track.instrument_id, t.instrument_ids) === -1) {
              t.instrument_ids.push(track.instrument_id);
            }
          }
        }
        else {
          t.user = track.user;
          t.instrument_ids.push(track.instrument_id);
          tracks.push(t);
        }
      });
      return tracks;
    }

    this.showBubble = function($hoverElement) {

      return rest.getClaimedRecording(recordingId)
        .done(function(response) {
          var claimedRecording = response;
          var recording = response.recording;
          $(hoverSelector).html('');

          var deDupedTracks = deDupTracks(recording.recorded_tracks);

          // musicians
          var musicianHtml = '';
          $.each(deDupedTracks, function(index, val) {
              var instrumentHtml = '';
              var musician = val.user;

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

              instrumentHtml = '<td><div class="nowrap">';
              $.each(val.instrument_ids, function(index, val) {
                instrumentHtml += '<img src="' + context.JK.getInstrumentIcon24(val) + '" title="' + context.JK.getInstrumentId(val) + '" width="24" height="24" />&nbsp;&nbsp;';
              });
              instrumentHtml += '</div></td>';
              
              musicianHtml += instrumentHtml;
              musicianHtml += '</tr>';
          });

          var template = $('#template-hover-recording').html();
          var creator = recording.band == null ? recording.owner : recording.band;

          var recordingHtml = context.JK.fillTemplate(template, {
            recordingId: recording.id,
            claimedRecordingId: claimedRecording.id,
            name: claimedRecording.name,
            genre: claimedRecording.genre_id.toUpperCase(),
            created_at: $.timeago(recording.created_at),
            description: response.description ? response.description : "",
            play_count: recording.play_count,
            comment_count: recording.comment_count,
            like_count: recording.like_count,
            creator_avatar_url: recording.band === null ? context.JK.resolveAvatarUrl(creator.photo_url) : context.JK.resolveBandAvatarUrl(creator.photo_url),
            creator_name: creator.name,
            location: creator.location,
            musicians: musicianHtml
          });
          
          $(hoverSelector).append('<h2>Recording Detail</h2>' + recordingHtml);
          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("Recording");
          }
          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);