(function (context, $) {

  "use strict";

  context.JK = context.JK || {};
  context.JK.IndividualJamTrack = function (app, dontPoke) {

    var rest = context.JK.Rest();
    var logger = context.JK.logger;
    var $page = null;
    var $previews = null;
    var $jamTracksButton = null;
    var $ctaJamTracksButton = null;

    function computeWeight (jam_track_track, instrument) {
      var weight;

      if (jam_track_track.track_type == 'Master') {
        weight = 0
      }
      else if (jam_track_track.instrument.id == instrument) {
        weight = 1 + jam_track_track.position
      }
      else {
        weight = 10000 + jam_track_track.position
      }
      return weight;
    }

    function fetchJamTrack() {
      rest.getJamTrackWithArtistInfo({plan_code: gon.jam_track_plan_code})
        .done(function (jam_track) {

          if(gon.instrument_id) {
            jam_track.tracks.sort(function(a, b) {
              var aWeight = computeWeight(a, gon.instrument_id)
              var bWeight = computeWeight(b, gon.instrument_id)
              return aWeight - bWeight
            })
          }

          context._.each(jam_track.tracks, function (track) {

            if (track.track_type == 'Click') {
              return;
            }

            var $element = $('<div class="jam-track-preview-holder"></div>')

            $previews.append($element);

            new context.JK.JamTrackPreview(app, $element, jam_track, track, {master_shows_duration: true, color:'black', master_adds_line_break: false, preload_master:true})

            if(track.track_type =='Master' && !dontPoke) {
              context.JK.HelpBubbleHelper.rotateJamTrackLandingBubbles($element.find('.jam-track-preview'), $page.find('.one_by_two .watch-video'), $page.find('.checkout'));
            }
          })

          $previews.append('<br clear = "all" />')
        })
        .fail(function () {
          app.notify({title: 'Unable to fetch JamTrack', text: "Please refresh the page or try again later."})
        })
    }
    function initialize() {

      $page = $('body')
      $previews = $page.find('.previews')
      $jamTracksButton = $page.find('.browse-jamtracks')
      $ctaJamTracksButton = $page.find('.cta-free-jamtrack');

      context.JK.Tracking.adTrack(app)
      fetchJamTrack();
    }

    this.initialize = initialize;
  }
})(window, jQuery);